Add QuickQuiz project files

This commit is contained in:
Boen_Shi 2026-06-25 18:20:15 +08:00
commit 6ad79be274
254 changed files with 219458 additions and 0 deletions

18
.editorconfig Normal file
View File

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

65
.env.example Normal file
View File

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

11
.gitattributes vendored Normal file
View File

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

27
.gitignore vendored Normal file
View File

@ -0,0 +1,27 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.codex
/.cursor/
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/fonts-manifest.dev.json
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
_ide_helper.php
Homestead.json
Homestead.yaml
Thumbs.db

2
.npmrc Normal file
View File

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

124
README.md Normal file
View File

@ -0,0 +1,124 @@
# QuickQuiz
QuickQuiz 是一个前后端分离题库系统。后端为 Laravel + MySQL + JWT + hg/apidoc 注解路由,前端为 Vue 3 + Vite + TypeScript + Element Plus + UnoCSS + Pinia。
## Requirements
- PHP 8.3+
- Composer 2+
- MySQL 8 或兼容版本
- Node.js 22+
- npm 10+
## Backend Setup
```bash
composer install
copy .env.example .env
php artisan key:generate
php artisan jwt:secret --force
```
编辑 `.env` 中的 MySQL 配置:
```env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=quickquiz
DB_USERNAME=root
DB_PASSWORD=
```
phpStudy 默认 MySQL 密码常见为 `root`,如果连接失败请改为:
```env
DB_PASSWORD=root
```
创建数据库后执行:
```bash
php artisan quickquiz:install --admin-email=admin@quickquiz.local --admin-password=password --fresh
php artisan serve
```
默认管理员:
- 邮箱:`admin@quickquiz.local`
- 密码:`password`
## Frontend Setup
```bash
cd frontend
npm install
npm run dev
```
前端默认代理:
- `/api` -> `http://127.0.0.1:8000`
- `/apidoc` -> `http://127.0.0.1:8000`
## API Documentation
控制器使用 `hg/apidoc` 注解描述 URL、Method、分组和标题。项目额外提供 `App\Providers\ApidocRouteServiceProvider`,用于兼容 Laravel 13 下 `RouteMiddleware` 注解解析结构,并按注解自动注册业务 API 路由。
访问路径:
```text
http://127.0.0.1:8000/apidoc
```
## Testing
本项目测试按 MySQL 配置,默认测试库为 `quickquiz_test`。先创建测试库:
```sql
CREATE DATABASE quickquiz_test CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```
然后执行:
```bash
php artisan test
```
当前环境如果没有启动 MySQL数据库迁移和 Feature 测试会失败。
## Verification Commands
```bash
php artisan route:list --path=api
vendor\bin\pint --test
cd frontend
npm run build
```
## Import Format
当前 `question.json` 支持如下数组格式:
```json
[
{
"questionId": "405323271",
"questionText": "题干",
"answerCorrect": true,
"options": [
{ "text": "选项 A", "correct": false },
{ "text": "选项 B", "correct": true }
]
}
]
```
导入规则:
- 根据正确选项数量识别单选/多选。
- 两个选项且文本为“对/错”时识别判断题。
- `answerCorrect` 不作为答案来源。
- 解析允许为空。
- 同一题库内按题干、选项文本和正确标记去重。
- 重复题跳过;格式错误导致整批回滚。

View File

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
final class QuickQuizInstall extends Command
{
protected $signature = 'quickquiz:install
{--admin-email=admin@quickquiz.local : 首个管理员邮箱}
{--admin-password=password : 首个管理员密码}
{--fresh : 使用 migrate:fresh 重建数据库}';
protected $description = 'Install QuickQuiz by running migrations, seeders, and creating the first administrator.';
public function handle(): int
{
if (! config('app.key')) {
Artisan::call('key:generate', ['--force' => true]);
}
if (! config('jwt.secret')) {
Artisan::call('jwt:secret', ['--force' => true]);
}
Artisan::call($this->option('fresh') ? 'migrate:fresh' : 'migrate', ['--force' => true]);
$this->output->write(Artisan::output());
Artisan::call('db:seed', ['--force' => true]);
$this->output->write(Artisan::output());
User::query()->updateOrCreate([
'email' => (string) $this->option('admin-email'),
], [
'name' => '系统管理员',
'role' => 'admin',
'is_active' => true,
'password' => Hash::make((string) $this->option('admin-password')),
]);
Storage::put('installed.lock', now()->toIso8601String());
$this->info('QuickQuiz installed.');
return self::SUCCESS;
}
}

View File

@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\SchoolClass;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
#[Apidoc\Group('后台')]
#[Apidoc\Title('班级管理')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class ClassController extends Controller
{
#[Apidoc\Title('班级列表')]
#[Apidoc\Url('/api/admin/classes')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:classes'])]
public function index(Request $request): JsonResponse
{
$query = SchoolClass::query()->withCount('members')->latest();
if ($request->user()->role !== 'admin') {
$query->where('owner_id', $request->user()->id);
}
return ApiResponse::page($query->paginate((int) $request->query('per_page', 20)));
}
#[Apidoc\Title('创建班级')]
#[Apidoc\Url('/api/admin/classes')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:classes'])]
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'name' => ['required', 'string', 'max:100'],
'description' => ['nullable', 'string'],
]);
$class = SchoolClass::create($data + [
'owner_id' => $request->user()->id,
'join_code' => strtoupper(Str::random(8)),
'is_active' => true,
]);
return ApiResponse::success($class, '班级已创建');
}
#[Apidoc\Title('分配成员')]
#[Apidoc\Url('/api/admin/classes/{class}/members')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:classes'])]
public function addMember(Request $request, mixed $class): JsonResponse
{
$class = $this->resolveClass($class);
abort_if($request->user()->role !== 'admin' && $class->owner_id !== $request->user()->id, 403, '权限不足');
$data = $request->validate([
'user_id' => ['required', 'exists:users,id'],
'role' => ['nullable', 'in:student,assistant'],
]);
$class->members()->syncWithoutDetaching([
$data['user_id'] => ['role' => $data['role'] ?? 'student'],
]);
return ApiResponse::success($class->load('members'), '成员已加入');
}
private function resolveClass(mixed $class): SchoolClass
{
if ($class instanceof SchoolClass && $class->exists) {
return $class;
}
return SchoolClass::query()->findOrFail((int) $class);
}
}

View File

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin\Concerns;
use App\Models\Paper;
use App\Models\Question;
use App\Models\QuestionBank;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
trait AuthorizesOwnedResources
{
private function ownedBanksQuery(Request $request): Builder
{
$query = QuestionBank::query();
if ($request->user()->role !== 'admin') {
$query->where('owner_id', $request->user()->id);
}
return $query;
}
private function authorizeBankOwner(Request $request, QuestionBank $bank): void
{
abort_if(! $this->ownsResource($request->user(), $bank->owner_id), 403, '权限不足');
}
private function authorizeQuestionOwner(Request $request, Question $question): void
{
$question->loadMissing('bank');
abort_if(! $this->ownsResource($request->user(), $question->bank->owner_id), 403, '权限不足');
}
private function authorizePaperOwner(Request $request, Paper $paper): void
{
abort_if(! $this->ownsResource($request->user(), $paper->owner_id), 403, '权限不足');
}
private function ownsResource(User $user, int $ownerId): bool
{
return $user->role === 'admin' || $ownerId === $user->id;
}
}

View File

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\OperationLog;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
#[Apidoc\Group('后台')]
#[Apidoc\Title('操作日志')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class LogController extends Controller
{
#[Apidoc\Title('日志列表')]
#[Apidoc\Url('/api/admin/logs')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:logs'])]
public function index(Request $request): JsonResponse
{
$query = OperationLog::query()->with('user')->latest();
if ($action = $request->query('action')) {
$query->where('action', 'like', '%'.$action.'%');
}
return ApiResponse::page($query->paginate((int) $request->query('per_page', 20)));
}
}

View File

@ -0,0 +1,203 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Api\Admin\Concerns\AuthorizesOwnedResources;
use App\Http\Controllers\Controller;
use App\Models\OperationLog;
use App\Models\Paper;
use App\Models\Question;
use App\Models\QuestionBank;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
#[Apidoc\Group('后台')]
#[Apidoc\Title('试卷管理')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class PaperController extends Controller
{
use AuthorizesOwnedResources;
#[Apidoc\Title('试卷列表')]
#[Apidoc\Url('/api/admin/papers')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:papers'])]
public function index(Request $request): JsonResponse
{
$query = Paper::query()->withCount('questions')->latest();
if ($request->user()->role !== 'admin') {
$query->where('owner_id', $request->user()->id);
}
return ApiResponse::page($query->paginate((int) $request->query('per_page', 20)));
}
#[Apidoc\Title('试卷详情')]
#[Apidoc\Url('/api/admin/papers/{paper}')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:papers'])]
public function show(Request $request, mixed $paper): JsonResponse
{
$paper = $this->resolvePaper($paper);
$this->authorizePaperOwner($request, $paper);
return ApiResponse::success($paper->load('questions.options')->loadCount('questions'));
}
#[Apidoc\Title('创建固定试卷')]
#[Apidoc\Url('/api/admin/papers')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:papers'])]
public function store(Request $request): JsonResponse
{
$data = $this->validatePaper($request);
if (! empty($data['question_bank_id'])) {
$this->authorizeBankOwner($request, QuestionBank::findOrFail($data['question_bank_id']));
}
$this->authorizeQuestions($request, collect($data['questions'] ?? [])->pluck('id')->all());
$paper = Paper::create([
'owner_id' => $request->user()->id,
'question_bank_id' => $data['question_bank_id'] ?? null,
'title' => $data['title'],
'description' => $data['description'] ?? null,
'duration_minutes' => $data['duration_minutes'] ?? null,
'attempt_limit' => $data['attempt_limit'] ?? null,
'is_active' => true,
]);
$this->syncQuestions($paper, $data['questions'] ?? []);
OperationLog::create([
'user_id' => $request->user()->id,
'action' => 'paper.created',
'target_type' => Paper::class,
'target_id' => $paper->id,
'ip' => $request->ip(),
'payload' => ['title' => $paper->title],
]);
return ApiResponse::success($paper->load('questions'), '试卷已创建');
}
#[Apidoc\Title('更新固定试卷')]
#[Apidoc\Url('/api/admin/papers/{paper}')]
#[Apidoc\Method('PUT')]
#[Apidoc\RouteMiddleware(['permission:papers'])]
public function update(Request $request, mixed $paper): JsonResponse
{
$paper = $this->resolvePaper($paper);
$this->authorizePaperOwner($request, $paper);
$data = $this->validatePaper($request, true);
if (array_key_exists('question_bank_id', $data) && $data['question_bank_id'] !== null) {
$this->authorizeBankOwner($request, QuestionBank::findOrFail($data['question_bank_id']));
}
if (array_key_exists('questions', $data)) {
$this->authorizeQuestions($request, collect($data['questions'] ?? [])->pluck('id')->all());
}
$paper->update([
...collect($data)
->only(['title', 'description', 'question_bank_id', 'duration_minutes', 'attempt_limit', 'is_active'])
->all(),
]);
if (array_key_exists('questions', $data)) {
$this->syncQuestions($paper, $data['questions'] ?? []);
}
return ApiResponse::success($paper->fresh('questions')->loadCount('questions'), '试卷已更新');
}
#[Apidoc\Title('删除固定试卷')]
#[Apidoc\Url('/api/admin/papers/{paper}')]
#[Apidoc\Method('DELETE')]
#[Apidoc\RouteMiddleware(['permission:papers'])]
public function destroy(Request $request, mixed $paper): JsonResponse
{
$paper = $this->resolvePaper($paper);
$this->authorizePaperOwner($request, $paper);
$paper->delete();
OperationLog::create([
'user_id' => $request->user()->id,
'action' => 'paper.deleted',
'target_type' => Paper::class,
'target_id' => $paper->id,
'ip' => $request->ip(),
]);
return ApiResponse::success(null, '试卷已删除');
}
/**
* @return array<string, mixed>
*/
private function validatePaper(Request $request, bool $updating = false): array
{
return $request->validate([
'title' => [$updating ? 'sometimes' : 'required', 'string', 'max:120'],
'description' => ['nullable', 'string'],
'question_bank_id' => ['nullable', 'exists:question_banks,id'],
'duration_minutes' => ['nullable', 'integer', 'min:1'],
'attempt_limit' => ['nullable', 'integer', 'min:1'],
'is_active' => ['sometimes', 'boolean'],
'questions' => ['array'],
'questions.*.id' => ['required_with:questions', 'exists:questions,id'],
'questions.*.score' => ['nullable', 'numeric', 'min:0'],
]);
}
/**
* @param array<int, int> $questionIds
*/
private function authorizeQuestions(Request $request, array $questionIds): void
{
if ($questionIds === []) {
return;
}
$visibleQuestionCount = Question::query()
->whereIn('id', $questionIds)
->whereHas('bank', function ($query) use ($request): void {
if ($request->user()->role !== 'admin') {
$query->where('owner_id', $request->user()->id);
}
})
->count();
abort_if($visibleQuestionCount !== count(array_unique($questionIds)), 403, '题目权限不足');
}
/**
* @param array<int, array{id: int, score?: float|int|null}> $questions
*/
private function syncQuestions(Paper $paper, array $questions): void
{
$syncPayload = [];
foreach ($questions as $sort => $question) {
$syncPayload[$question['id']] = [
'score' => $question['score'] ?? null,
'sort' => $sort,
];
}
$paper->questions()->sync($syncPayload);
}
private function resolvePaper(mixed $paper): Paper
{
if ($paper instanceof Paper && $paper->exists) {
return $paper;
}
return Paper::query()->findOrFail((int) $paper);
}
}

View File

@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\OperationLog;
use App\Models\Permission;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
#[Apidoc\Group('后台')]
#[Apidoc\Title('权限菜单')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class PermissionController extends Controller
{
#[Apidoc\Title('权限菜单列表')]
#[Apidoc\Url('/api/admin/permissions')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:permissions'])]
public function index(): JsonResponse
{
return ApiResponse::success([
'permissions' => Permission::query()->orderBy('sort')->get(),
'role_permissions' => DB::table('role_permissions')
->select(['role', 'permission_id'])
->get()
->groupBy('role')
->map(fn ($items) => $items->pluck('permission_id')->values())
->all(),
]);
}
#[Apidoc\Title('保存角色权限')]
#[Apidoc\Url('/api/admin/roles/{role}/permissions')]
#[Apidoc\Method('PUT')]
#[Apidoc\RouteMiddleware(['permission:permissions'])]
public function syncRole(Request $request, string $role): JsonResponse
{
abort_unless(in_array($role, ['teacher', 'user'], true), 422, '角色不可配置');
$data = $request->validate(['permission_ids' => ['array'], 'permission_ids.*' => ['integer', 'exists:permissions,id']]);
DB::table('role_permissions')->where('role', $role)->delete();
foreach ($data['permission_ids'] ?? [] as $permissionId) {
DB::table('role_permissions')->insert([
'role' => $role,
'permission_id' => $permissionId,
'created_at' => now(),
'updated_at' => now(),
]);
}
OperationLog::create([
'user_id' => $request->user()->id,
'action' => 'role.permissions_updated',
'target_type' => 'role',
'target_id' => null,
'ip' => $request->ip(),
'payload' => ['role' => $role, 'permission_ids' => $data['permission_ids'] ?? []],
]);
return ApiResponse::success(null, '角色权限已更新');
}
}

View File

@ -0,0 +1,165 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Api\Admin\Concerns\AuthorizesOwnedResources;
use App\Http\Controllers\Controller;
use App\Models\ExportJob;
use App\Models\OperationLog;
use App\Models\QuestionBank;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
#[Apidoc\Group('后台')]
#[Apidoc\Title('题库管理')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class QuestionBankController extends Controller
{
use AuthorizesOwnedResources;
#[Apidoc\Title('题库列表')]
#[Apidoc\Url('/api/admin/banks')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:banks'])]
public function index(Request $request): JsonResponse
{
$query = $this->ownedBanksQuery($request)->withCount('questions')->latest();
if ($keyword = $request->query('keyword')) {
$query->where('name', 'like', '%'.$keyword.'%');
}
return ApiResponse::page($query->paginate((int) $request->query('per_page', 20)));
}
#[Apidoc\Title('创建题库')]
#[Apidoc\Url('/api/admin/banks')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:banks.create'])]
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'name' => ['required', 'string', 'max:120'],
'description' => ['nullable', 'string'],
'visibility' => ['required', 'in:public,private,assigned'],
]);
$bank = QuestionBank::create($data + ['owner_id' => $request->user()->id, 'is_active' => true]);
OperationLog::create([
'user_id' => $request->user()->id,
'action' => 'bank.created',
'target_type' => QuestionBank::class,
'target_id' => $bank->id,
'ip' => $request->ip(),
'payload' => ['name' => $bank->name],
]);
return ApiResponse::success($bank, '题库已创建');
}
#[Apidoc\Title('更新题库')]
#[Apidoc\Url('/api/admin/banks/{bank}')]
#[Apidoc\Method('PUT')]
#[Apidoc\RouteMiddleware(['permission:banks.update'])]
public function update(Request $request, mixed $bank): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
$data = $request->validate([
'name' => ['sometimes', 'string', 'max:120'],
'description' => ['nullable', 'string'],
'visibility' => ['sometimes', 'in:public,private,assigned'],
'is_active' => ['sometimes', 'boolean'],
]);
$bank->update($data);
return ApiResponse::success($bank->fresh(), '题库已更新');
}
#[Apidoc\Title('删除题库')]
#[Apidoc\Url('/api/admin/banks/{bank}')]
#[Apidoc\Method('DELETE')]
#[Apidoc\RouteMiddleware(['permission:banks.delete'])]
public function destroy(Request $request, mixed $bank): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
$bank->delete();
OperationLog::create([
'user_id' => $request->user()->id,
'action' => 'bank.deleted',
'target_type' => QuestionBank::class,
'target_id' => $bank->id,
'ip' => $request->ip(),
]);
return ApiResponse::success(null, '题库已删除');
}
#[Apidoc\Title('题库授权')]
#[Apidoc\Url('/api/admin/banks/{bank}/shares')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:banks.share'])]
public function share(Request $request, mixed $bank): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
$data = $request->validate([
'targets' => ['array'],
'targets.*.type' => ['required', 'in:user,class'],
'targets.*.id' => ['required', 'integer'],
]);
DB::table('bank_shares')->where('question_bank_id', $bank->id)->delete();
foreach ($data['targets'] ?? [] as $target) {
DB::table('bank_shares')->insert([
'question_bank_id' => $bank->id,
'target_type' => $target['type'],
'target_id' => $target['id'],
'created_at' => now(),
'updated_at' => now(),
]);
}
$bank->update(['visibility' => ($data['targets'] ?? []) === [] ? $bank->visibility : 'assigned']);
return ApiResponse::success(null, '授权已保存');
}
#[Apidoc\Title('题库导出')]
#[Apidoc\Url('/api/admin/banks/{bank}/export')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:questions.export'])]
public function export(Request $request, mixed $bank): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
$payload = $bank->load('questions.options', 'categories', 'tags')->toArray();
$path = 'exports/bank-'.$bank->id.'-'.now()->format('YmdHis').'.json';
Storage::put($path, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
$job = ExportJob::create([
'user_id' => $request->user()->id,
'type' => 'question_bank',
'file_path' => $path,
'payload' => ['question_bank_id' => $bank->id],
]);
return ApiResponse::success($job, '题库已导出');
}
private function resolveBank(mixed $bank): QuestionBank
{
if ($bank instanceof QuestionBank && $bank->exists) {
return $bank;
}
return QuestionBank::query()->findOrFail((int) $bank);
}
}

View File

@ -0,0 +1,251 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Api\Admin\Concerns\AuthorizesOwnedResources;
use App\Http\Controllers\Controller;
use App\Models\OperationLog;
use App\Models\Question;
use App\Models\QuestionBank;
use App\Services\QuestionImportService;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
#[Apidoc\Group('后台')]
#[Apidoc\Title('题目管理')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class QuestionController extends Controller
{
use AuthorizesOwnedResources;
#[Apidoc\Title('题目列表')]
#[Apidoc\Url('/api/admin/questions')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:questions'])]
public function index(Request $request): JsonResponse
{
$query = Question::query()->with(['bank', 'options', 'tags'])->latest();
if ($request->user()->role !== 'admin') {
$query->whereHas('bank', fn ($bankQuery) => $bankQuery->where('owner_id', $request->user()->id));
}
if ($bankId = $request->query('question_bank_id')) {
$query->where('question_bank_id', $bankId);
}
if ($type = $request->query('type')) {
$query->where('type', $type);
}
if ($keyword = $request->query('keyword')) {
$query->where('content', 'like', '%'.$keyword.'%');
}
if ($request->filled('is_active')) {
$query->where('is_active', $request->boolean('is_active'));
}
return ApiResponse::page($query->paginate((int) $request->query('per_page', 20)));
}
#[Apidoc\Title('创建题目')]
#[Apidoc\Url('/api/admin/questions')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:questions.import'])]
public function store(Request $request, QuestionImportService $service): JsonResponse
{
$data = $request->validate([
'question_bank_id' => ['required', 'exists:question_banks,id'],
'content' => ['required', 'string'],
'type' => ['required', 'in:single,multiple,judge,blank'],
'explanation' => ['nullable', 'string'],
'options' => ['array'],
'answers' => ['array'],
]);
$bank = QuestionBank::findOrFail($data['question_bank_id']);
$this->authorizeBankOwner($request, $bank);
$job = $service->importRows($bank, $request->user(), [[
'content' => $data['content'],
'type' => $data['type'],
'explanation' => $data['explanation'] ?? null,
'options' => $data['options'] ?? [],
'answer' => implode('|', $data['answers'] ?? []),
]], 'manual');
return ApiResponse::success($job->load('bank'), '题目已创建');
}
#[Apidoc\Title('批量导入题目')]
#[Apidoc\Url('/api/admin/banks/{bank}/imports')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:questions.import'])]
public function import(Request $request, mixed $bank, QuestionImportService $service): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
$request->validate([
'file' => ['required', 'file', 'mimes:json,xlsx,xls,csv,txt'],
]);
$job = $service->importUploadedFile($bank, $request->user(), $request->file('file'));
OperationLog::create([
'user_id' => $request->user()->id,
'action' => 'questions.imported',
'target_type' => QuestionBank::class,
'target_id' => $bank->id,
'ip' => $request->ip(),
'payload' => ['job_id' => $job->id, 'success_count' => $job->success_count, 'skipped_count' => $job->skipped_count],
]);
return ApiResponse::success($job, '导入完成');
}
#[Apidoc\Title('校验导入题目')]
#[Apidoc\Url('/api/admin/banks/{bank}/imports/validate')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:questions.import'])]
public function validateImport(Request $request, mixed $bank, QuestionImportService $service): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
$request->validate([
'file' => ['required', 'file', 'mimes:json,xlsx,xls,csv,txt'],
]);
$prepared = $service->prepareUploadedFile($request->file('file'));
return ApiResponse::success([
...$service->validateRows($prepared['rows']),
'type' => $prepared['type'],
'file_path' => $prepared['path'],
], '校验完成');
}
#[Apidoc\Title('提交已校验题目')]
#[Apidoc\Url('/api/admin/banks/{bank}/imports/rows')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:questions.import'])]
public function importRows(Request $request, mixed $bank, QuestionImportService $service): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
$data = $request->validate([
'rows' => ['required', 'array'],
'type' => ['nullable', 'string'],
'file_path' => ['nullable', 'string'],
]);
$validation = $service->validateRows($data['rows']);
if (! $validation['valid']) {
return ApiResponse::success($validation, '校验未通过');
}
$job = $service->importRows($bank, $request->user(), $data['rows'], $data['type'] ?? 'manual', $data['file_path'] ?? null);
return ApiResponse::success($job, '导入完成');
}
#[Apidoc\Title('校验已编辑题目')]
#[Apidoc\Url('/api/admin/banks/{bank}/imports/rows/validate')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:questions.import'])]
public function validateRows(Request $request, mixed $bank, QuestionImportService $service): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
$data = $request->validate([
'rows' => ['required', 'array'],
]);
return ApiResponse::success($service->validateRows($data['rows']), '校验完成');
}
private function resolveBank(mixed $bank): QuestionBank
{
if ($bank instanceof QuestionBank && $bank->exists) {
return $bank;
}
return QuestionBank::query()->findOrFail((int) $bank);
}
#[Apidoc\Title('更新题目状态')]
#[Apidoc\Url('/api/admin/questions/{question}')]
#[Apidoc\Method('PUT')]
#[Apidoc\RouteMiddleware(['permission:banks.update'])]
public function update(Request $request, mixed $question): JsonResponse
{
$question = $this->resolveQuestion($question);
$this->authorizeQuestionOwner($request, $question);
$data = $request->validate([
'content' => ['sometimes', 'string'],
'type' => ['sometimes', 'in:single,multiple,judge,blank'],
'explanation' => ['nullable', 'string'],
'is_active' => ['sometimes', 'boolean'],
'options' => ['sometimes', 'array'],
'options.*.text' => ['nullable', 'string'],
'options.*.content' => ['nullable', 'string'],
'options.*.correct' => ['nullable', 'boolean'],
'options.*.is_correct' => ['nullable', 'boolean'],
'answers' => ['sometimes', 'array'],
]);
DB::transaction(function () use ($question, $data): void {
$question->update(collect($data)->only(['content', 'type', 'explanation', 'is_active'])->all());
if (array_key_exists('answers', $data)) {
$question->update(['answers' => array_values(array_filter($data['answers']))]);
}
if (array_key_exists('options', $data)) {
$question->options()->delete();
foreach ($data['options'] as $sort => $option) {
$content = trim((string) ($option['text'] ?? $option['content'] ?? ''));
if ($content === '') {
continue;
}
$question->options()->create([
'content' => $content,
'is_correct' => (bool) ($option['correct'] ?? $option['is_correct'] ?? false),
'sort' => $sort,
]);
}
}
});
return ApiResponse::success($question->fresh('options'), '题目已更新');
}
#[Apidoc\Title('删除题目')]
#[Apidoc\Url('/api/admin/questions/{question}')]
#[Apidoc\Method('DELETE')]
#[Apidoc\RouteMiddleware(['permission:banks.update'])]
public function destroy(Request $request, mixed $question): JsonResponse
{
$question = $this->resolveQuestion($question);
$this->authorizeQuestionOwner($request, $question);
$question->delete();
OperationLog::create([
'user_id' => $request->user()->id,
'action' => 'question.deleted',
'target_type' => Question::class,
'target_id' => $question->id,
'ip' => $request->ip(),
'payload' => ['question_bank_id' => $question->question_bank_id],
]);
return ApiResponse::success(null, '题目已删除');
}
private function resolveQuestion(mixed $question): Question
{
if ($question instanceof Question && $question->exists) {
return $question;
}
return Question::query()->findOrFail((int) $question);
}
}

View File

@ -0,0 +1,183 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\ExportJob;
use App\Models\Question;
use App\Models\QuizAttempt;
use App\Models\User;
use App\Models\WrongQuestion;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
#[Apidoc\Group('后台')]
#[Apidoc\Title('统计报表')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class ReportController extends Controller
{
#[Apidoc\Title('报表概览')]
#[Apidoc\Url('/api/admin/reports/overview')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:reports'])]
public function overview(): JsonResponse
{
$attempts = QuizAttempt::query();
$total = (clone $attempts)->count();
$correct = (clone $attempts)->sum('correct_count');
$questions = (clone $attempts)->sum('total_questions');
return ApiResponse::success([
'users' => User::query()->count(),
'questions' => Question::query()->count(),
'attempts' => $total,
'wrong_questions' => WrongQuestion::query()->whereNull('mastered_at')->count(),
'accuracy' => $questions > 0 ? round($correct / $questions * 100, 2) : 0,
]);
}
#[Apidoc\Title('练习趋势')]
#[Apidoc\Url('/api/admin/reports/trends')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:reports'])]
public function trends(): JsonResponse
{
$rows = QuizAttempt::query()
->selectRaw('date(started_at) as day, count(*) as attempts, sum(correct_count) as correct_count, sum(total_questions) as total_questions')
->where('started_at', '>=', now()->subDays(14))
->groupBy('day')
->orderBy('day')
->get();
return ApiResponse::success($rows);
}
#[Apidoc\Title('题目错误率')]
#[Apidoc\Url('/api/admin/reports/question-errors')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:reports'])]
public function questionErrors(Request $request): JsonResponse
{
$rows = DB::table('quiz_attempt_questions')
->join('questions', 'questions.id', '=', 'quiz_attempt_questions.question_id')
->selectRaw('questions.id, questions.content, count(*) as attempts, sum(case when is_correct = 0 then 1 else 0 end) as wrong_count')
->groupBy('questions.id', 'questions.content')
->orderByDesc('wrong_count')
->paginate((int) $request->query('per_page', 20));
return ApiResponse::page($rows);
}
#[Apidoc\Title('班级排行')]
#[Apidoc\Url('/api/admin/reports/class-ranking')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:reports'])]
public function classRanking(Request $request): JsonResponse
{
$rows = DB::table('classes')
->leftJoin('class_members', 'class_members.class_id', '=', 'classes.id')
->leftJoin('quiz_attempts', 'quiz_attempts.user_id', '=', 'class_members.user_id')
->when($request->user()->role !== 'admin', fn ($query) => $query->where('classes.owner_id', $request->user()->id))
->selectRaw('classes.id, classes.name, count(distinct class_members.user_id) as members_count, count(distinct quiz_attempts.id) as attempts, coalesce(sum(quiz_attempts.correct_count), 0) as correct_count, coalesce(sum(quiz_attempts.total_questions), 0) as total_questions')
->groupBy('classes.id', 'classes.name')
->orderByDesc('attempts')
->limit(20)
->get()
->map(function (object $row): array {
$totalQuestions = (int) $row->total_questions;
return [
'id' => (int) $row->id,
'name' => $row->name,
'members_count' => (int) $row->members_count,
'attempts' => (int) $row->attempts,
'correct_count' => (int) $row->correct_count,
'total_questions' => $totalQuestions,
'accuracy' => $totalQuestions > 0 ? round((int) $row->correct_count / $totalQuestions * 100, 2) : 0,
];
});
return ApiResponse::success($rows);
}
#[Apidoc\Title('题库和分类掌握度')]
#[Apidoc\Url('/api/admin/reports/mastery')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:reports'])]
public function mastery(Request $request): JsonResponse
{
$query = DB::table('quiz_attempt_questions')
->join('quiz_attempts', 'quiz_attempts.id', '=', 'quiz_attempt_questions.quiz_attempt_id')
->join('questions', 'questions.id', '=', 'quiz_attempt_questions.question_id')
->join('question_banks', 'question_banks.id', '=', 'questions.question_bank_id')
->leftJoin('question_categories', 'question_categories.id', '=', 'questions.category_id')
->whereNotNull('quiz_attempt_questions.is_correct')
->when($request->user()->role !== 'admin', fn ($builder) => $builder->where('question_banks.owner_id', $request->user()->id));
$banks = (clone $query)
->selectRaw('question_banks.id, question_banks.name, count(*) as attempts, sum(case when quiz_attempt_questions.is_correct = 1 then 1 else 0 end) as correct_count')
->groupBy('question_banks.id', 'question_banks.name')
->orderByDesc('attempts')
->limit(20)
->get()
->map(fn (object $row): array => $this->masteryRow($row));
$categories = (clone $query)
->selectRaw('question_banks.name as bank_name, question_categories.id, coalesce(question_categories.name, "未分类") as name, count(*) as attempts, sum(case when quiz_attempt_questions.is_correct = 1 then 1 else 0 end) as correct_count')
->groupBy('question_banks.name', 'question_categories.id', 'question_categories.name')
->orderByDesc('attempts')
->limit(30)
->get()
->map(fn (object $row): array => $this->masteryRow($row) + ['bank_name' => $row->bank_name]);
return ApiResponse::success([
'banks' => $banks,
'categories' => $categories,
]);
}
#[Apidoc\Title('报表导出')]
#[Apidoc\Url('/api/admin/reports/export')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:reports'])]
public function export(Request $request): JsonResponse
{
$payload = [
'overview' => $this->overview()->getData(true)['data'],
'trends' => $this->trends()->getData(true)['data'],
'class_ranking' => $this->classRanking($request)->getData(true)['data'],
'mastery' => $this->mastery($request)->getData(true)['data'],
];
$path = 'exports/report-'.now()->format('YmdHis').'.json';
Storage::put($path, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
$job = ExportJob::create([
'user_id' => $request->user()->id,
'type' => 'report',
'file_path' => $path,
'payload' => $payload,
]);
return ApiResponse::success($job, '报表已导出');
}
private function masteryRow(object $row): array
{
$attempts = (int) $row->attempts;
$correct = (int) $row->correct_count;
return [
'id' => $row->id === null ? null : (int) $row->id,
'name' => $row->name,
'attempts' => $attempts,
'correct_count' => $correct,
'accuracy' => $attempts > 0 ? round($correct / $attempts * 100, 2) : 0,
];
}
}

View File

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\OperationLog;
use App\Models\SystemSetting;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
#[Apidoc\Group('后台')]
#[Apidoc\Title('系统配置')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class SettingController extends Controller
{
#[Apidoc\Title('配置列表')]
#[Apidoc\Url('/api/admin/settings')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:settings'])]
public function index(): JsonResponse
{
return ApiResponse::success(SystemSetting::query()->orderBy('group')->orderBy('key')->get());
}
#[Apidoc\Title('保存配置')]
#[Apidoc\Url('/api/admin/settings')]
#[Apidoc\Method('PUT')]
#[Apidoc\RouteMiddleware(['permission:settings'])]
public function update(Request $request): JsonResponse
{
$data = $request->validate([
'settings' => ['required', 'array'],
]);
foreach ($data['settings'] as $key => $value) {
SystemSetting::updateOrCreate(['key' => $key], [
'value' => $value,
'group' => str_contains((string) $key, '.') ? explode('.', (string) $key)[0] : 'general',
]);
}
OperationLog::create([
'user_id' => $request->user()->id,
'action' => 'settings.updated',
'target_type' => 'system',
'target_id' => null,
'ip' => $request->ip(),
'payload' => ['keys' => array_keys($data['settings'])],
]);
return ApiResponse::success(SystemSetting::query()->get(), '配置已保存');
}
}

View File

@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Api\Admin\Concerns\AuthorizesOwnedResources;
use App\Http\Controllers\Controller;
use App\Models\QuestionBank;
use App\Models\QuestionCategory;
use App\Models\QuestionTag;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
#[Apidoc\Group('后台')]
#[Apidoc\Title('分类与标签')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class TaxonomyController extends Controller
{
use AuthorizesOwnedResources;
#[Apidoc\Title('分类列表')]
#[Apidoc\Url('/api/admin/banks/{bank}/categories')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:questions'])]
public function categories(Request $request, mixed $bank): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
return ApiResponse::success($bank->categories()->orderBy('sort')->get());
}
#[Apidoc\Title('创建分类')]
#[Apidoc\Url('/api/admin/banks/{bank}/categories')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:banks.update'])]
public function createCategory(Request $request, mixed $bank): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
$data = $request->validate([
'name' => ['required', 'string', 'max:100'],
'parent_id' => ['nullable', 'exists:question_categories,id'],
'sort' => ['nullable', 'integer', 'min:0'],
]);
$category = QuestionCategory::create($data + ['question_bank_id' => $bank->id]);
return ApiResponse::success($category, '分类已创建');
}
#[Apidoc\Title('标签列表')]
#[Apidoc\Url('/api/admin/banks/{bank}/tags')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:questions'])]
public function tags(Request $request, mixed $bank): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
return ApiResponse::success($bank->tags()->orderBy('name')->get());
}
#[Apidoc\Title('创建标签')]
#[Apidoc\Url('/api/admin/banks/{bank}/tags')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:banks.update'])]
public function createTag(Request $request, mixed $bank): JsonResponse
{
$bank = $this->resolveBank($bank);
$this->authorizeBankOwner($request, $bank);
$data = $request->validate(['name' => ['required', 'string', 'max:50']]);
$tag = QuestionTag::firstOrCreate([
'question_bank_id' => $bank->id,
'name' => $data['name'],
]);
return ApiResponse::success($tag, '标签已创建');
}
private function resolveBank(mixed $bank): QuestionBank
{
if ($bank instanceof QuestionBank && $bank->exists) {
return $bank;
}
return QuestionBank::query()->findOrFail((int) $bank);
}
}

View File

@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Models\InviteCode;
use App\Models\User;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
#[Apidoc\Group('后台')]
#[Apidoc\Title('用户与邀请码')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class UserController extends Controller
{
#[Apidoc\Title('用户列表')]
#[Apidoc\Url('/api/admin/users')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:users'])]
public function index(Request $request): JsonResponse
{
$query = User::query()->latest();
if ($keyword = $request->query('keyword')) {
$query->where(fn ($q) => $q->where('name', 'like', '%'.$keyword.'%')->orWhere('email', 'like', '%'.$keyword.'%'));
}
if ($role = $request->query('role')) {
$query->where('role', $role);
}
return ApiResponse::page($query->paginate((int) $request->query('per_page', 20)));
}
#[Apidoc\Title('创建用户')]
#[Apidoc\Url('/api/admin/users')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:users.create'])]
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'name' => ['required', 'string', 'max:50'],
'email' => ['required', 'email', 'unique:users,email'],
'password' => ['required', 'string', 'min:6'],
'role' => ['required', 'in:admin,teacher,user'],
]);
$user = User::create($data + ['created_by' => $request->user()->id, 'is_active' => true]);
return ApiResponse::success($user, '用户已创建');
}
#[Apidoc\Title('更新用户')]
#[Apidoc\Url('/api/admin/users/{user}')]
#[Apidoc\Method('PUT')]
#[Apidoc\RouteMiddleware(['permission:users.update'])]
public function update(Request $request, mixed $user): JsonResponse
{
$user = $this->resolveUser($user);
$data = $request->validate([
'name' => ['sometimes', 'string', 'max:50'],
'role' => ['sometimes', 'in:admin,teacher,user'],
'is_active' => ['sometimes', 'boolean'],
'password' => ['nullable', 'string', 'min:6'],
]);
if (! empty($data['password'])) {
$data['password'] = Hash::make($data['password']);
} else {
unset($data['password']);
}
$user->update($data);
return ApiResponse::success($user->fresh(), '用户已更新');
}
private function resolveUser(mixed $user): User
{
if ($user instanceof User && $user->exists) {
return $user;
}
return User::query()->findOrFail((int) $user);
}
#[Apidoc\Title('邀请码列表')]
#[Apidoc\Url('/api/admin/invite-codes')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['permission:users'])]
public function invites(Request $request): JsonResponse
{
return ApiResponse::page(InviteCode::query()->latest()->paginate((int) $request->query('per_page', 20)));
}
#[Apidoc\Title('创建邀请码')]
#[Apidoc\Url('/api/admin/invite-codes')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['permission:users.create'])]
public function createInvite(Request $request): JsonResponse
{
$data = $request->validate([
'role' => ['required', 'in:teacher,user'],
'max_uses' => ['required', 'integer', 'min:1', 'max:10000'],
'expires_at' => ['nullable', 'date'],
]);
$invite = InviteCode::create($data + [
'created_by' => $request->user()->id,
'code' => strtoupper(Str::random(10)),
'used_count' => 0,
'is_active' => true,
]);
return ApiResponse::success($invite, '邀请码已创建');
}
}

View File

@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\App;
use App\Http\Controllers\Controller;
use App\Models\SchoolClass;
use App\Models\WrongQuestion;
use App\Services\LearningAccessService;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
#[Apidoc\Group('用户端')]
#[Apidoc\Title('班级学习入口')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class ClassroomController extends Controller
{
#[Apidoc\Title('我的班级')]
#[Apidoc\Url('/api/app/classes')]
#[Apidoc\Method('GET')]
public function myClasses(Request $request): JsonResponse
{
return ApiResponse::success(
SchoolClass::query()
->whereHas('members', fn ($query) => $query->where('users.id', $request->user()->id))
->withCount('members')
->get(),
);
}
#[Apidoc\Title('通过班级码加入')]
#[Apidoc\Url('/api/app/classes/join')]
#[Apidoc\Method('POST')]
public function join(Request $request): JsonResponse
{
$data = $request->validate(['join_code' => ['required', 'string']]);
$class = SchoolClass::query()->where('join_code', strtoupper($data['join_code']))->where('is_active', true)->firstOrFail();
$class->members()->syncWithoutDetaching([$request->user()->id => ['role' => 'student']]);
return ApiResponse::success($class, '已加入班级');
}
#[Apidoc\Title('可学习资源')]
#[Apidoc\Url('/api/app/resources')]
#[Apidoc\Method('GET')]
public function resources(Request $request, LearningAccessService $access): JsonResponse
{
$banks = $access->visibleBanksQuery($request->user())
->withCount('questions')
->get();
$wrongCounts = WrongQuestion::query()
->where('user_id', $request->user()->id)
->whereNull('mastered_at')
->join('questions', 'questions.id', '=', 'wrong_questions.question_id')
->selectRaw('questions.question_bank_id, count(*) as total')
->groupBy('questions.question_bank_id')
->pluck('total', 'question_bank_id');
$banks->each(fn ($bank) => $bank->setAttribute('wrong_questions_count', (int) ($wrongCounts[$bank->id] ?? 0)));
$papers = $access->visiblePapersQuery($request->user())
->withCount('questions')
->latest()
->get();
return ApiResponse::success(['banks' => $banks, 'papers' => $papers]);
}
}

View File

@ -0,0 +1,189 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\App;
use App\Http\Controllers\Controller;
use App\Models\FavoriteQuestion;
use App\Models\Paper;
use App\Models\QuestionBank;
use App\Models\QuizAttempt;
use App\Models\User;
use App\Models\WrongQuestion;
use App\Services\LearningAccessService;
use App\Services\QuizService;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
#[Apidoc\Group('用户端')]
#[Apidoc\Title('做题')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
final class QuizController extends Controller
{
#[Apidoc\Title('开始背题/刷题/抽题')]
#[Apidoc\Url('/api/app/banks/{bank}/attempts')]
#[Apidoc\Method('POST')]
public function startBank(Request $request, mixed $bank, QuizService $service, LearningAccessService $access): JsonResponse
{
$bank = $this->resolveBank($bank);
abort_if(! $access->canAccessBank($this->currentUser($request), $bank), 403);
$data = $request->validate([
'mode' => ['required', 'in:memorize,wrong_memorize,practice,wrong_practice,sequence,random,wrong_random'],
'category_id' => ['nullable', 'exists:question_categories,id'],
'type' => ['nullable'],
'type.*' => ['in:single,multiple,judge,blank'],
'tag_ids' => ['nullable', 'array'],
'tag_ids.*' => ['integer', 'exists:question_tags,id'],
'limit' => ['nullable', 'integer', 'min:1', 'max:100'],
]);
return ApiResponse::success($service->startPractice($this->currentUser($request), $bank, $data['mode'], $data), '已开始');
}
#[Apidoc\Title('开始整卷测试')]
#[Apidoc\Url('/api/app/papers/{paper}/attempts')]
#[Apidoc\Method('POST')]
public function startPaper(Request $request, mixed $paper, QuizService $service, LearningAccessService $access): JsonResponse
{
$paper = $this->resolvePaper($paper);
abort_if(! $access->canAccessPaper($this->currentUser($request), $paper), 403);
return ApiResponse::success($service->startPaper($this->currentUser($request), $paper), '已开始');
}
#[Apidoc\Title('继续作答')]
#[Apidoc\Url('/api/app/attempts/{attempt}')]
#[Apidoc\Method('GET')]
public function show(Request $request, mixed $attempt): JsonResponse
{
$attempt = $this->resolveAttempt($attempt);
abort_if($attempt->user_id !== $this->currentUser($request)->id, 403);
return ApiResponse::success($attempt->load('items.question.options'));
}
#[Apidoc\Title('提交单题答案')]
#[Apidoc\Url('/api/app/attempts/{attempt}/answer')]
#[Apidoc\Method('POST')]
public function answer(Request $request, mixed $attempt, QuizService $service): JsonResponse
{
$attempt = $this->resolveAttempt($attempt);
$data = $request->validate([
'question_id' => ['required', 'exists:questions,id'],
'answer' => ['array'],
'duration_seconds' => ['nullable', 'integer', 'min:0'],
]);
return ApiResponse::success(
$service->answer($this->currentUser($request), $attempt, (int) $data['question_id'], $data['answer'] ?? [], (int) ($data['duration_seconds'] ?? 0)),
'已作答',
);
}
#[Apidoc\Title('保存作答位置')]
#[Apidoc\Url('/api/app/attempts/{attempt}/position')]
#[Apidoc\Method('PUT')]
public function updatePosition(Request $request, mixed $attempt): JsonResponse
{
$attempt = $this->resolveAttempt($attempt);
$user = $this->currentUser($request);
abort_if($attempt->user_id !== $user->id, 403);
$data = $request->validate([
'current_index' => ['required', 'integer', 'min:0'],
]);
$maxIndex = max(0, $attempt->total_questions - 1);
$attempt->update([
'current_index' => min((int) $data['current_index'], $maxIndex),
]);
return ApiResponse::success($attempt->fresh(), '位置已保存');
}
#[Apidoc\Title('交卷')]
#[Apidoc\Url('/api/app/attempts/{attempt}/submit')]
#[Apidoc\Method('POST')]
public function submit(Request $request, mixed $attempt, QuizService $service): JsonResponse
{
$attempt = $this->resolveAttempt($attempt);
return ApiResponse::success($service->submit($this->currentUser($request), $attempt), '已交卷');
}
#[Apidoc\Title('错题列表')]
#[Apidoc\Url('/api/app/wrong-questions')]
#[Apidoc\Method('GET')]
public function wrongQuestions(Request $request): JsonResponse
{
return ApiResponse::page(
WrongQuestion::query()
->where('user_id', $this->currentUser($request)->id)
->whereNull('mastered_at')
->when($request->query('question_bank_id'), fn ($query, $bankId) => $query->whereHas(
'question',
fn ($questionQuery) => $questionQuery->where('question_bank_id', $bankId),
))
->with('question.options')
->latest()
->paginate((int) $request->query('per_page', 20)),
);
}
#[Apidoc\Title('收藏和笔记')]
#[Apidoc\Url('/api/app/favorites')]
#[Apidoc\Method('POST')]
public function favorite(Request $request): JsonResponse
{
$data = $request->validate([
'question_id' => ['required', 'exists:questions,id'],
'note' => ['nullable', 'string'],
]);
$favorite = FavoriteQuestion::updateOrCreate([
'user_id' => $this->currentUser($request)->id,
'question_id' => $data['question_id'],
], [
'note' => $data['note'] ?? null,
]);
return ApiResponse::success($favorite, '已保存');
}
private function currentUser(Request $request): User
{
return JWTAuth::parseToken()->authenticate() ?? auth('api')->user() ?? $request->user();
}
private function resolveAttempt(mixed $attempt): QuizAttempt
{
if ($attempt instanceof QuizAttempt && $attempt->exists) {
return $attempt;
}
return QuizAttempt::query()->findOrFail((int) $attempt);
}
private function resolveBank(mixed $bank): QuestionBank
{
if ($bank instanceof QuestionBank && $bank->exists) {
return $bank;
}
return QuestionBank::query()->findOrFail((int) $bank);
}
private function resolvePaper(mixed $paper): Paper
{
if ($paper instanceof Paper && $paper->exists) {
return $paper;
}
return Paper::query()->findOrFail((int) $paper);
}
}

View File

@ -0,0 +1,217 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\InviteCode;
use App\Models\OperationLog;
use App\Models\User;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tymon\JWTAuth\Facades\JWTAuth;
#[Apidoc\Group('认证')]
#[Apidoc\Title('认证接口')]
final class AuthController extends Controller
{
#[Apidoc\Title('邀请码注册')]
#[Apidoc\Url('/api/auth/register')]
#[Apidoc\Method('POST')]
public function register(Request $request): JsonResponse
{
$data = $request->validate([
'name' => ['required', 'string', 'max:50'],
'email' => ['required', 'email', 'max:120', 'unique:users,email'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
'invite_code' => ['required', 'string'],
]);
$invite = InviteCode::query()->where('code', $data['invite_code'])->lockForUpdate()->first();
if (! $invite || ! $invite->available()) {
throw ValidationException::withMessages(['invite_code' => '邀请码无效']);
}
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'role' => $invite->role,
'is_active' => true,
'password' => Hash::make($data['password']),
]);
$invite->increment('used_count');
return ApiResponse::success($this->tokenPayload($user), '注册成功');
}
#[Apidoc\Title('验证码')]
#[Apidoc\Url('/api/auth/captcha')]
#[Apidoc\Method('GET')]
public function captcha(Request $request): JsonResponse
{
$code = (string) random_int(1000, 9999);
$request->session()->put('captcha', $code);
return ApiResponse::success([
'captcha' => $code,
'expires_in' => 300,
], '验证码已生成');
}
#[Apidoc\Title('登录')]
#[Apidoc\Url('/api/auth/login')]
#[Apidoc\Method('POST')]
public function login(Request $request): JsonResponse
{
$data = $request->validate([
'email' => ['required', 'email'],
'password' => ['required', 'string'],
'captcha' => ['nullable', 'string'],
]);
$key = 'login:'.$request->ip().':'.$data['email'];
$user = User::query()->where('email', $data['email'])->first();
if (RateLimiter::tooManyAttempts($key, 5) || ($user?->failed_login_count ?? 0) >= 5) {
$captcha = (string) ($data['captcha'] ?? '');
$expectedCaptcha = (string) session('captcha', '');
if ($captcha === '' || $expectedCaptcha === '' || $captcha !== $expectedCaptcha) {
return ApiResponse::error('请输入验证码', 429, 429, ['captcha_required' => true]);
}
}
if (! $user || ! Hash::check($data['password'], $user->password)) {
RateLimiter::hit($key, 300);
$user?->update([
'failed_login_count' => $user->failed_login_count + 1,
'last_failed_login_at' => now(),
]);
return ApiResponse::error('账号或密码错误', 422, 422, [
'captcha_required' => RateLimiter::attempts($key) >= 5,
]);
}
if (! $user->is_active) {
return ApiResponse::error('账号已被禁用', 403, 403);
}
RateLimiter::clear($key);
$user->update(['failed_login_count' => 0, 'last_login_at' => now()]);
OperationLog::create([
'user_id' => $user->id,
'action' => 'auth.login',
'ip' => $request->ip(),
]);
return ApiResponse::success($this->tokenPayload($user), '登录成功');
}
#[Apidoc\Title('刷新Token')]
#[Apidoc\Url('/api/auth/refresh')]
#[Apidoc\Method('POST')]
public function refresh(): JsonResponse
{
return ApiResponse::success([
'token' => JWTAuth::refresh(JWTAuth::getToken()),
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60,
]);
}
#[Apidoc\Title('当前用户')]
#[Apidoc\Url('/api/auth/me')]
#[Apidoc\Method('GET')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
public function me(Request $request): JsonResponse
{
return ApiResponse::success($request->user()->loadMissing('permissions'));
}
#[Apidoc\Title('退出登录')]
#[Apidoc\Url('/api/auth/logout')]
#[Apidoc\Method('POST')]
#[Apidoc\RouteMiddleware(['jwt.auth'])]
public function logout(): JsonResponse
{
JWTAuth::invalidate(JWTAuth::getToken());
return ApiResponse::success(null, '已退出');
}
#[Apidoc\Title('发送找回密码邮件')]
#[Apidoc\Url('/api/auth/forgot-password')]
#[Apidoc\Method('POST')]
public function forgotPassword(Request $request): JsonResponse
{
$data = $request->validate(['email' => ['required', 'email']]);
$user = User::query()->where('email', $data['email'])->first();
if (! $user) {
return ApiResponse::success(null, '如果邮箱存在,系统会发送重置邮件');
}
$token = Password::broker()->createToken($user);
if (config('mail.default') !== 'smtp' || ! config('mail.mailers.smtp.host')) {
OperationLog::create([
'user_id' => $user->id,
'action' => 'auth.password_reset_token_created',
'payload' => ['token' => $token],
]);
return ApiResponse::success(['token' => $token], '邮件未配置,已返回重置 token');
}
Mail::raw("QuickQuiz 密码重置 Token{$token}", fn ($message) => $message->to($user->email)->subject('QuickQuiz 密码重置'));
return ApiResponse::success(null, '重置邮件已发送');
}
#[Apidoc\Title('重置密码')]
#[Apidoc\Url('/api/auth/reset-password')]
#[Apidoc\Method('POST')]
public function resetPassword(Request $request): JsonResponse
{
$data = $request->validate([
'email' => ['required', 'email'],
'token' => ['required', 'string'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
]);
$status = Password::broker()->reset($data, function (User $user, string $password): void {
$user->forceFill([
'password' => Hash::make($password),
'remember_token' => Str::random(60),
])->save();
});
if ($status !== Password::PASSWORD_RESET) {
return ApiResponse::error('重置失败', 422, 422, ['status' => $status]);
}
return ApiResponse::success(null, '密码已重置');
}
private function tokenPayload(User $user): array
{
return [
'token' => JWTAuth::fromUser($user),
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60,
'user' => $user,
];
}
}

View File

@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Support\ApiResponse;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
#[Apidoc\Group('安装')]
#[Apidoc\Title('安装向导')]
final class InstallController extends Controller
{
#[Apidoc\Title('安装状态')]
#[Apidoc\Url('/api/install/status')]
#[Apidoc\Method('GET')]
public function status(): JsonResponse
{
return ApiResponse::success([
'installed' => Storage::exists('installed.lock'),
'database' => config('database.default'),
]);
}
#[Apidoc\Title('测试数据库连接')]
#[Apidoc\Url('/api/install/database-test')]
#[Apidoc\Method('POST')]
public function databaseTest(Request $request): JsonResponse
{
$data = $request->validate([
'host' => ['required', 'string'],
'port' => ['required', 'integer'],
'database' => ['required', 'string'],
'username' => ['required', 'string'],
'password' => ['nullable', 'string'],
]);
config()->set('database.connections.install_test', [
'driver' => 'mysql',
'host' => $data['host'],
'port' => $data['port'],
'database' => $data['database'],
'username' => $data['username'],
'password' => $data['password'] ?? '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
]);
DB::connection('install_test')->select('select 1');
return ApiResponse::success(['ok' => true], '数据库连接成功');
}
#[Apidoc\Title('执行安装')]
#[Apidoc\Url('/api/install/run')]
#[Apidoc\Method('POST')]
public function run(Request $request): JsonResponse
{
$data = $request->validate([
'admin_email' => ['required', 'email'],
'admin_password' => ['required', 'string', 'min:6'],
'fresh' => ['boolean'],
]);
Artisan::call('quickquiz:install', [
'--admin-email' => $data['admin_email'],
'--admin-password' => $data['admin_password'],
'--fresh' => (bool) ($data['fresh'] ?? false),
]);
return ApiResponse::success([
'output' => Artisan::output(),
'installed' => true,
], '安装完成');
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}

View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Support\ApiResponse;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class EnsurePermission
{
public function handle(Request $request, Closure $next, string $permission): Response
{
$user = $request->user();
if (! $user || ! $user->hasPermission($permission)) {
return ApiResponse::error('权限不足', 403, 403);
}
return $next($request);
}
}

View File

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use App\Support\ApiResponse;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;
final class JwtAuthenticate
{
public function handle(Request $request, Closure $next): Response
{
try {
$user = JWTAuth::parseToken()->authenticate();
} catch (JWTException) {
return ApiResponse::error('登录令牌无效', 401, 401);
}
if (! $user || ! $user->is_active) {
return ApiResponse::error('账号不可用', 401, 401);
}
auth()->setUser($user);
auth('api')->setUser($user);
$request->setUserResolver(fn () => $user);
return $next($request);
}
}

16
app/Models/ExportJob.php Normal file
View File

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class ExportJob extends Model
{
protected $table = 'exports';
protected $fillable = ['user_id', 'type', 'file_path', 'payload'];
protected $casts = ['payload' => 'array'];
}

View File

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class FavoriteQuestion extends Model
{
protected $fillable = ['user_id', 'question_id', 'note'];
}

14
app/Models/ImportJob.php Normal file
View File

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class ImportJob extends Model
{
protected $fillable = ['user_id', 'question_bank_id', 'type', 'file_path', 'status', 'total_count', 'success_count', 'skipped_count', 'report'];
protected $casts = ['report' => 'array'];
}

24
app/Models/InviteCode.php Normal file
View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class InviteCode extends Model
{
protected $fillable = ['created_by', 'code', 'role', 'max_uses', 'used_count', 'expires_at', 'is_active'];
protected $casts = [
'expires_at' => 'datetime',
'is_active' => 'boolean',
];
public function available(): bool
{
return $this->is_active
&& $this->used_count < $this->max_uses
&& (! $this->expires_at || $this->expires_at->isFuture());
}
}

View File

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class OperationLog extends Model
{
protected $fillable = ['user_id', 'action', 'target_type', 'target_id', 'ip', 'payload'];
protected $casts = ['payload' => 'array'];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

26
app/Models/Paper.php Normal file
View File

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
final class Paper extends Model
{
use SoftDeletes;
protected $fillable = ['owner_id', 'question_bank_id', 'title', 'description', 'duration_minutes', 'attempt_limit', 'is_active'];
protected $casts = ['is_active' => 'boolean'];
public function questions(): BelongsToMany
{
return $this->belongsToMany(Question::class, 'paper_questions')
->withPivot(['score', 'sort'])
->withTimestamps()
->orderByPivot('sort');
}
}

18
app/Models/Permission.php Normal file
View File

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
final class Permission extends Model
{
protected $fillable = ['code', 'name', 'type', 'parent_code', 'menu_path', 'icon', 'sort'];
public function roles(): BelongsToMany
{
return $this->belongsToMany(User::class, 'role_permissions', 'permission_id', 'role', 'id', 'role');
}
}

59
app/Models/Question.php Normal file
View File

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
final class Question extends Model
{
use SoftDeletes;
protected $fillable = [
'question_bank_id',
'category_id',
'creator_id',
'type',
'content',
'explanation',
'answers',
'source_question_id',
'dedup_hash',
'is_active',
];
protected $casts = [
'answers' => 'array',
'is_active' => 'boolean',
];
public function bank(): BelongsTo
{
return $this->belongsTo(QuestionBank::class, 'question_bank_id');
}
public function options(): HasMany
{
return $this->hasMany(QuestionOption::class)->orderBy('sort');
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(QuestionTag::class, 'question_tag');
}
public function wrongQuestions(): HasMany
{
return $this->hasMany(WrongQuestion::class);
}
public function correctOptionIds(): array
{
return $this->options->where('is_correct', true)->pluck('id')->map(fn ($id) => (int) $id)->values()->all();
}
}

View File

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
final class QuestionBank extends Model
{
use SoftDeletes;
protected $fillable = ['owner_id', 'name', 'description', 'visibility', 'is_active'];
protected $casts = ['is_active' => 'boolean'];
public function owner(): BelongsTo
{
return $this->belongsTo(User::class, 'owner_id');
}
public function questions(): HasMany
{
return $this->hasMany(Question::class);
}
public function categories(): HasMany
{
return $this->hasMany(QuestionCategory::class);
}
public function tags(): HasMany
{
return $this->hasMany(QuestionTag::class);
}
}

View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class QuestionCategory extends Model
{
protected $fillable = ['question_bank_id', 'parent_id', 'name', 'sort'];
public function bank(): BelongsTo
{
return $this->belongsTo(QuestionBank::class, 'question_bank_id');
}
public function children(): HasMany
{
return $this->hasMany(self::class, 'parent_id');
}
}

View File

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class QuestionOption extends Model
{
protected $fillable = ['question_id', 'content', 'is_correct', 'sort'];
protected $casts = ['is_correct' => 'boolean'];
public function question(): BelongsTo
{
return $this->belongsTo(Question::class);
}
}

View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
final class QuestionTag extends Model
{
protected $fillable = ['question_bank_id', 'name'];
public function bank(): BelongsTo
{
return $this->belongsTo(QuestionBank::class, 'question_bank_id');
}
public function questions(): BelongsToMany
{
return $this->belongsToMany(Question::class, 'question_tag');
}
}

View File

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
final class QuizAttempt extends Model
{
protected $fillable = [
'user_id',
'paper_id',
'question_bank_id',
'mode',
'status',
'draw_rule',
'started_at',
'expires_at',
'submitted_at',
'score',
'total_questions',
'correct_count',
'current_index',
];
protected $casts = [
'draw_rule' => 'array',
'started_at' => 'datetime',
'expires_at' => 'datetime',
'submitted_at' => 'datetime',
'score' => 'decimal:2',
];
public function items(): HasMany
{
return $this->hasMany(QuizAttemptQuestion::class)->orderBy('sort');
}
}

View File

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class QuizAttemptQuestion extends Model
{
protected $fillable = [
'quiz_attempt_id',
'question_id',
'score',
'sort',
'answer',
'is_correct',
'duration_seconds',
'explanation_viewed',
'answered_at',
];
protected $casts = [
'answer' => 'array',
'is_correct' => 'boolean',
'explanation_viewed' => 'boolean',
'answered_at' => 'datetime',
'score' => 'decimal:2',
];
public function question(): BelongsTo
{
return $this->belongsTo(Question::class);
}
}

View File

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
final class SchoolClass extends Model
{
use SoftDeletes;
protected $table = 'classes';
protected $fillable = ['owner_id', 'name', 'join_code', 'description', 'is_active'];
protected $casts = ['is_active' => 'boolean'];
public function owner(): BelongsTo
{
return $this->belongsTo(User::class, 'owner_id');
}
public function members(): BelongsToMany
{
return $this->belongsToMany(User::class, 'class_members', 'class_id', 'user_id')
->withPivot('role')
->withTimestamps();
}
}

View File

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class SystemSetting extends Model
{
protected $fillable = ['key', 'value', 'group'];
protected $casts = ['value' => 'array'];
}

86
app/Models/User.php Normal file
View File

@ -0,0 +1,86 @@
<?php
namespace App\Models;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable, SoftDeletes;
protected $fillable = [
'name',
'email',
'phone',
'role',
'is_active',
'created_by',
'password',
'failed_login_count',
'last_failed_login_at',
'last_login_at',
];
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'is_active' => 'boolean',
'last_failed_login_at' => 'datetime',
'last_login_at' => 'datetime',
];
}
public function permissions(): BelongsToMany
{
return $this->belongsToMany(Permission::class, 'role_permissions', 'role', 'permission_id', 'role', 'id');
}
public function hasPermission(string $code): bool
{
if ($this->role === 'admin') {
return true;
}
return Permission::query()
->where('code', $code)
->whereExists(function ($query): void {
$query->selectRaw('1')
->from('role_permissions')
->whereColumn('role_permissions.permission_id', 'permissions.id')
->where('role_permissions.role', $this->role);
})
->exists();
}
public function getJWTIdentifier(): mixed
{
return $this->getKey();
}
public function getJWTCustomClaims(): array
{
return [
'role' => $this->role,
'name' => $this->name,
];
}
}

View File

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
final class WrongQuestion extends Model
{
protected $fillable = ['user_id', 'question_id', 'wrong_count', 'consecutive_correct_count', 'last_wrong_at', 'mastered_at'];
protected $casts = [
'last_wrong_at' => 'datetime',
'mastered_at' => 'datetime',
];
public function question(): BelongsTo
{
return $this->belongsTo(Question::class);
}
}

View File

@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace App\Providers;
use hg\apidoc\utils\AutoRegisterRouts;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
final class ApidocRouteServiceProvider extends ServiceProvider
{
public function boot(): void
{
$config = config('apidoc');
$config['auto_register_routes'] = true;
foreach ((new AutoRegisterRouts($config))->getAppsApis() as $controller) {
$classMiddleware = $this->normalizeMiddleware($controller['middleware'] ?? []);
foreach ($controller['methods'] ?? [] as $method) {
$middleware = array_values(array_unique(array_merge(
$classMiddleware,
$this->normalizeMiddleware($method['middleware'] ?? []),
)));
$route = Route::match(
$this->normalizeMethods($method['method'] ?? 'GET'),
$method['url'],
'\\'.$method['controller'].'@'.$method['name'],
);
if ($middleware !== []) {
$route->middleware($middleware);
}
}
}
}
/**
* @return array<int, string>
*/
private function normalizeMethods(mixed $method): array
{
if (is_string($method)) {
return array_values(array_filter(array_map('trim', explode(',', strtoupper($method)))));
}
if (is_array($method)) {
$value = $method['name'] ?? $method;
if (is_string($value)) {
return $this->normalizeMethods($value);
}
if (is_array($value)) {
return array_values(array_filter(array_map(
fn (mixed $item): string => strtoupper((string) $item),
$value,
)));
}
}
return ['GET'];
}
/**
* @return array<int, string>
*/
private function normalizeMiddleware(mixed $middleware): array
{
if (is_string($middleware)) {
return [$middleware];
}
if (! is_array($middleware)) {
return [];
}
$value = $middleware['name'] ?? $middleware;
if (is_string($value)) {
return [$value];
}
if (! is_array($value)) {
return [];
}
return array_values(array_filter(array_map(
fn (mixed $item): string => (string) $item,
$value,
)));
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Schema::defaultStringLength(191);
}
}

View File

@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\Paper;
use App\Models\QuestionBank;
use App\Models\SchoolClass;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
final class LearningAccessService
{
public function visibleBanksQuery(User $user): Builder
{
$classIds = $this->classIds($user);
return QuestionBank::query()
->where('is_active', true)
->where(function (Builder $query) use ($user, $classIds): void {
$query->where('visibility', 'public')
->orWhere('owner_id', $user->id)
->orWhereExists(function ($sub) use ($user): void {
$sub->selectRaw('1')
->from('bank_shares')
->whereColumn('bank_shares.question_bank_id', 'question_banks.id')
->where('target_type', 'user')
->where('target_id', $user->id);
})
->orWhereExists(function ($sub) use ($classIds): void {
$sub->selectRaw('1')
->from('bank_shares')
->whereColumn('bank_shares.question_bank_id', 'question_banks.id')
->where('target_type', 'class')
->whereIn('target_id', $classIds);
});
});
}
public function visiblePapersQuery(User $user): Builder
{
return Paper::query()
->where('is_active', true)
->where(function (Builder $query) use ($user): void {
$query->where('owner_id', $user->id)
->orWhereIn('question_bank_id', $this->visibleBanksQuery($user)->select('id'));
});
}
public function canAccessBank(User $user, QuestionBank $bank): bool
{
return $this->visibleBanksQuery($user)->whereKey($bank->id)->exists();
}
public function canAccessPaper(User $user, Paper $paper): bool
{
return $this->visiblePapersQuery($user)->whereKey($paper->id)->exists();
}
private function classIds(User $user): Collection
{
return SchoolClass::query()
->whereHas('members', fn (Builder $query) => $query->where('users.id', $user->id))
->pluck('id');
}
}

View File

@ -0,0 +1,314 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\ImportJob;
use App\Models\Question;
use App\Models\QuestionBank;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Facades\Excel;
final class QuestionImportService
{
public function importJsonText(QuestionBank $bank, User $user, string $json, ?string $filePath = null): ImportJob
{
$rows = json_decode($json, true);
if (! is_array($rows)) {
throw ValidationException::withMessages(['file' => 'JSON 必须是题目数组']);
}
return $this->importRows($bank, $user, $rows, 'json', $filePath);
}
public function importUploadedFile(QuestionBank $bank, User $user, UploadedFile $file): ImportJob
{
$prepared = $this->prepareUploadedFile($file);
return $this->importRows($bank, $user, $prepared['rows'], $prepared['type'], $prepared['path']);
}
/**
* @return array{type:string,path:string,rows:array<int, array<string, mixed>>}
*/
public function prepareUploadedFile(UploadedFile $file): array
{
$path = $file->store('imports');
$extension = strtolower($file->getClientOriginalExtension());
if ($extension === 'json') {
$content = Storage::get($path);
$rows = json_decode($content, true);
if (! is_array($rows)) {
throw ValidationException::withMessages(['file' => 'JSON 必须是题目数组']);
}
return ['type' => 'json', 'path' => $path, 'rows' => $rows];
}
$sheets = Excel::toArray(new class implements ToArray
{
public function array(array $array): array
{
return $array;
}
}, Storage::path($path));
$rows = $this->normalizeExcelRows($sheets[0] ?? []);
return ['type' => 'excel', 'path' => $path, 'rows' => $rows];
}
/**
* @param array<int, array<string, mixed>> $rows
* @return array{valid:bool,rows:array<int, array<string, mixed>>,errors:array<int, array{row:int,message:string}>}
*/
public function validateRows(array $rows): array
{
$errors = [];
foreach ($rows as $index => $row) {
try {
$this->normalizeQuestionRow($row, $index + 1);
} catch (ValidationException $exception) {
$errors[] = [
'row' => $index + 1,
'message' => collect($exception->errors())->flatten()->first() ?? '格式错误',
];
}
}
return [
'valid' => $errors === [],
'rows' => $rows,
'errors' => $errors,
];
}
/**
* @param array<int, array<string, mixed>> $rows
*/
public function importRows(QuestionBank $bank, User $user, array $rows, string $type, ?string $filePath = null): ImportJob
{
return DB::transaction(function () use ($bank, $user, $rows, $type, $filePath): ImportJob {
$job = ImportJob::create([
'user_id' => $user->id,
'question_bank_id' => $bank->id,
'type' => $type,
'file_path' => $filePath,
'status' => 'running',
'total_count' => count($rows),
'report' => [],
]);
$report = [];
$success = 0;
$skipped = 0;
foreach ($rows as $index => $row) {
$normalized = $this->normalizeQuestionRow($row, $index + 1);
$hash = $this->dedupHash($normalized['content'], $normalized['options']);
$exists = Question::query()
->where('question_bank_id', $bank->id)
->where('dedup_hash', $hash)
->exists();
if ($exists) {
$skipped++;
$report[] = ['row' => $index + 1, 'status' => 'skipped', 'message' => '重复题目已跳过'];
continue;
}
$question = Question::create([
'question_bank_id' => $bank->id,
'category_id' => null,
'creator_id' => $user->id,
'type' => $normalized['type'],
'content' => $normalized['content'],
'explanation' => $normalized['explanation'],
'answers' => $normalized['answers'],
'source_question_id' => $normalized['source_question_id'],
'dedup_hash' => $hash,
'is_active' => true,
]);
foreach ($normalized['options'] as $sort => $option) {
$question->options()->create([
'content' => $option['text'],
'is_correct' => $option['correct'],
'sort' => $sort,
]);
}
$success++;
$report[] = ['row' => $index + 1, 'status' => 'success', 'message' => '导入成功'];
}
$job->update([
'status' => 'finished',
'success_count' => $success,
'skipped_count' => $skipped,
'report' => $report,
]);
return $job->fresh();
});
}
/**
* @param array<string, mixed> $row
* @return array{type:string,content:string,explanation:?string,answers:array<int, mixed>,source_question_id:?string,options:array<int, array{text:string,correct:bool}>}
*/
private function normalizeQuestionRow(array $row, int $rowNumber): array
{
$content = trim((string) ($row['questionText'] ?? $row['content'] ?? $row['题干'] ?? ''));
if ($content === '') {
throw ValidationException::withMessages(['file' => "{$rowNumber} 行题干不能为空"]);
}
$options = $row['options'] ?? null;
if (! is_array($options)) {
$options = $this->optionsFromFlatRow($row);
}
$normalizedOptions = [];
foreach ($options as $option) {
if (! is_array($option)) {
continue;
}
$text = trim((string) ($option['text'] ?? $option['content'] ?? $option['选项'] ?? ''));
if ($text === '') {
continue;
}
$normalizedOptions[] = [
'text' => $text,
'correct' => (bool) ($option['correct'] ?? $option['is_correct'] ?? false),
];
}
$correctCount = count(array_filter($normalizedOptions, fn (array $option): bool => $option['correct']));
if ($correctCount < 1 && empty($row['answer'])) {
throw ValidationException::withMessages(['file' => "{$rowNumber} 行至少需要一个正确答案"]);
}
$type = $this->detectType($normalizedOptions, $correctCount, (string) ($row['type'] ?? ''));
if ($type === 'blank') {
$answers = array_values(array_filter(array_map('trim', explode('|', (string) ($row['answer'] ?? '')))));
if ($answers === []) {
throw ValidationException::withMessages(['file' => "{$rowNumber} 行填空题答案不能为空"]);
}
return [
'type' => 'blank',
'content' => $content,
'explanation' => $row['explanation'] ?? null,
'answers' => $answers,
'source_question_id' => isset($row['questionId']) ? (string) $row['questionId'] : null,
'options' => [],
];
}
return [
'type' => $type,
'content' => $content,
'explanation' => $row['explanation'] ?? null,
'answers' => [],
'source_question_id' => isset($row['questionId']) ? (string) $row['questionId'] : null,
'options' => $normalizedOptions,
];
}
/**
* @param array<string, mixed> $row
* @return array<int, array{text:string,correct:bool}>
*/
private function optionsFromFlatRow(array $row): array
{
$answer = strtoupper(trim((string) ($row['answer'] ?? $row['答案'] ?? '')));
$letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
$correctLetters = array_filter(array_map('trim', preg_split('/[,|]/', $answer) ?: []));
$options = [];
foreach ($letters as $letter) {
$text = $row[$letter] ?? $row['option_'.$letter] ?? $row['选项'.$letter] ?? null;
if ($text === null || trim((string) $text) === '') {
continue;
}
$options[] = [
'text' => trim((string) $text),
'correct' => in_array($letter, $correctLetters, true),
];
}
return $options;
}
/**
* @param array<int, array{text:string,correct:bool}> $options
*/
private function detectType(array $options, int $correctCount, string $explicit): string
{
$explicit = strtolower($explicit);
if (in_array($explicit, ['single', 'multiple', 'judge', 'blank'], true)) {
return $explicit;
}
if ($options === []) {
return 'blank';
}
$texts = array_map(fn (array $option): string => $option['text'], $options);
sort($texts);
if (count($options) === 2 && $texts === ['对', '错']) {
return 'judge';
}
return $correctCount > 1 ? 'multiple' : 'single';
}
/**
* @param array<int, array{text:string,correct:bool}> $options
*/
private function dedupHash(string $content, array $options): string
{
return hash('sha256', json_encode([
'content' => preg_replace('/\s+/u', '', $content),
'options' => array_map(fn (array $option): array => [
'text' => preg_replace('/\s+/u', '', $option['text']),
'correct' => $option['correct'],
], $options),
], JSON_UNESCAPED_UNICODE));
}
/**
* @param array<int, array<int, mixed>> $rows
* @return array<int, array<string, mixed>>
*/
private function normalizeExcelRows(array $rows): array
{
if ($rows === []) {
return [];
}
$headers = array_map(fn ($header): string => trim((string) $header), array_shift($rows));
return array_values(array_filter(array_map(function (array $row) use ($headers): array {
$item = [];
foreach ($headers as $index => $header) {
if ($header !== '') {
$item[$header] = $row[$index] ?? null;
}
}
return $item;
}, $rows), fn (array $row): bool => array_filter($row) !== []));
}
}

View File

@ -0,0 +1,287 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\Paper;
use App\Models\Question;
use App\Models\QuestionBank;
use App\Models\QuizAttempt;
use App\Models\QuizAttemptQuestion;
use App\Models\User;
use App\Models\WrongQuestion;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
final class QuizService
{
public function startPractice(User $user, QuestionBank $bank, string $mode, array $filters = []): QuizAttempt
{
$resumeAttempt = $this->findResumeAttempt($user, $bank, $mode, $filters);
if ($resumeAttempt !== null) {
return $resumeAttempt->load('items.question.options');
}
$query = Question::query()
->where('question_bank_id', $bank->id)
->where('is_active', true)
->with(['options', 'tags']);
if (str_contains($mode, 'wrong')) {
$query->whereHas('wrongQuestions', fn ($wrongQuery) => $wrongQuery
->where('user_id', $user->id)
->whereNull('mastered_at'));
}
if (! empty($filters['category_id'])) {
$query->where('category_id', $filters['category_id']);
}
if (! empty($filters['type'])) {
$types = is_array($filters['type']) ? $filters['type'] : [$filters['type']];
$query->whereIn('type', array_values(array_filter($types)));
}
if (! empty($filters['tag_ids']) && is_array($filters['tag_ids'])) {
$tagIds = array_values(array_filter(array_map('intval', $filters['tag_ids'])));
if ($tagIds !== []) {
$query->whereHas('tags', fn ($tagQuery) => $tagQuery->whereIn('question_tags.id', $tagIds));
}
}
if (in_array($mode, ['random', 'wrong_random'], true)) {
$limit = min(max((int) ($filters['limit'] ?? 20), 1), 100);
$questions = $query
->orderBy('type')
->orderBy('id')
->get()
->groupBy('type')
->pipe(fn ($groups) => $groups->flatMap(fn ($items) => $items->shuffle()))
->take($limit)
->values();
} else {
$query->orderBy('id');
if (array_key_exists('limit', $filters)) {
$query->limit(min(max((int) $filters['limit'], 1), 100));
}
$questions = $query->get();
}
if ($questions->isEmpty()) {
throw ValidationException::withMessages(['question_bank_id' => '没有可用题目']);
}
return $this->createAttempt($user, $mode, $questions->all(), [
'question_bank_id' => $bank->id,
'draw_rule' => $filters,
]);
}
private function findResumeAttempt(User $user, QuestionBank $bank, string $mode, array $filters): ?QuizAttempt
{
if (in_array($mode, ['random', 'wrong_random'], true)) {
return null;
}
return QuizAttempt::query()
->where('user_id', $user->id)
->where('question_bank_id', $bank->id)
->where('mode', $mode)
->where('status', 'in_progress')
->latest()
->get()
->first(function (QuizAttempt $attempt) use ($filters): bool {
return $this->sameDrawRule($attempt->draw_rule ?? [], $filters);
});
}
/**
* @param array<string, mixed> $left
* @param array<string, mixed> $right
*/
private function sameDrawRule(array $left, array $right): bool
{
$normalize = function (array $rule): array {
$rule['tag_ids'] = array_values(array_filter(array_map('intval', (array) ($rule['tag_ids'] ?? []))));
sort($rule['tag_ids']);
$rule['type'] = array_values(array_filter((array) ($rule['type'] ?? [])));
sort($rule['type']);
unset($rule['limit']);
return $rule;
};
return $normalize($left) == $normalize($right);
}
public function startPaper(User $user, Paper $paper): QuizAttempt
{
$questions = $paper->questions()->with('options')->get();
if ($questions->isEmpty()) {
throw ValidationException::withMessages(['paper_id' => '试卷没有题目']);
}
if ($paper->attempt_limit !== null) {
$usedAttempts = QuizAttempt::query()
->where('user_id', $user->id)
->where('paper_id', $paper->id)
->whereIn('status', ['in_progress', 'submitted'])
->count();
if ($usedAttempts >= $paper->attempt_limit) {
throw ValidationException::withMessages(['paper_id' => '已达到试卷作答次数限制']);
}
}
return $this->createAttempt($user, 'paper', $questions->all(), [
'paper_id' => $paper->id,
'question_bank_id' => $paper->question_bank_id,
'expires_at' => $paper->duration_minutes ? now()->addMinutes($paper->duration_minutes) : null,
]);
}
public function answer(User $user, QuizAttempt $attempt, int $questionId, array $answer, int $durationSeconds = 0): QuizAttemptQuestion
{
if ($attempt->user_id !== $user->id) {
throw ValidationException::withMessages(['attempt' => '无权访问该记录']);
}
if ($attempt->status !== 'in_progress') {
throw ValidationException::withMessages(['attempt' => '该记录已结束']);
}
if ($attempt->expires_at && $attempt->expires_at->isPast()) {
$this->submit($user, $attempt);
throw ValidationException::withMessages(['attempt' => '测试已超时并自动交卷']);
}
$item = $attempt->items()->where('question_id', $questionId)->with('question.options')->firstOrFail();
$isCorrect = $this->judge($item->question, $answer);
$item->update([
'answer' => array_values($answer),
'is_correct' => $isCorrect,
'duration_seconds' => $durationSeconds,
'answered_at' => now(),
]);
$this->syncWrongQuestion($user, $item->question, $isCorrect);
return $item->fresh('question.options');
}
public function submit(User $user, QuizAttempt $attempt): QuizAttempt
{
if ($attempt->user_id !== $user->id) {
throw ValidationException::withMessages(['attempt' => '无权访问该记录']);
}
$items = $attempt->items()->get();
$correct = $items->where('is_correct', true)->count();
$score = $items->where('is_correct', true)->sum('score');
$attempt->update([
'status' => 'submitted',
'submitted_at' => now(),
'correct_count' => $correct,
'score' => $score,
]);
return $attempt->fresh('items.question.options');
}
/**
* @param array<int, Question> $questions
* @param array<string, mixed> $attributes
*/
private function createAttempt(User $user, string $mode, array $questions, array $attributes): QuizAttempt
{
return DB::transaction(function () use ($user, $mode, $questions, $attributes): QuizAttempt {
$attempt = QuizAttempt::create([
'user_id' => $user->id,
'paper_id' => $attributes['paper_id'] ?? null,
'question_bank_id' => $attributes['question_bank_id'] ?? null,
'mode' => $mode,
'status' => 'in_progress',
'draw_rule' => $attributes['draw_rule'] ?? null,
'started_at' => now(),
'expires_at' => $attributes['expires_at'] ?? null,
'total_questions' => count($questions),
]);
foreach ($questions as $sort => $question) {
$attempt->items()->create([
'question_id' => $question->id,
'score' => $this->questionScore($question),
'sort' => $sort,
]);
}
return $attempt->fresh('items.question.options');
});
}
private function judge(Question $question, array $answer): bool
{
if ($question->type === 'blank') {
$expected = array_map('trim', $question->answers ?? []);
$actual = array_map('trim', array_map('strval', $answer));
return $expected === $actual;
}
$correct = $question->correctOptionIds();
$actual = array_map('intval', $answer);
sort($correct);
sort($actual);
return $correct === $actual;
}
private function syncWrongQuestion(User $user, Question $question, bool $isCorrect): void
{
$wrong = WrongQuestion::firstOrNew([
'user_id' => $user->id,
'question_id' => $question->id,
]);
if ($isCorrect) {
if ($wrong->exists) {
$wrong->consecutive_correct_count++;
if ($wrong->consecutive_correct_count >= 3) {
$wrong->mastered_at = now();
}
$wrong->save();
}
return;
}
$wrong->wrong_count = $wrong->exists ? $wrong->wrong_count + 1 : 1;
$wrong->consecutive_correct_count = 0;
$wrong->mastered_at = null;
$wrong->last_wrong_at = now();
$wrong->save();
}
private function defaultScore(string $type): float
{
return match ($type) {
'multiple' => 2.0,
'blank' => 2.0,
default => 1.0,
};
}
private function questionScore(Question $question): float
{
$pivotScore = $question->getAttribute('pivot')?->score;
if ($pivotScore !== null) {
return (float) $pivotScore;
}
return $this->defaultScore($question->type);
}
}

View File

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace App\Support;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\JsonResponse;
final class ApiResponse
{
public static function success(mixed $data = null, string $message = 'ok', int $code = 0): JsonResponse
{
return response()->json([
'code' => $code,
'message' => $message,
'data' => $data,
]);
}
public static function error(string $message, int $code = 1, int $status = 400, mixed $data = null): JsonResponse
{
return response()->json([
'code' => $code,
'message' => $message,
'data' => $data,
], $status);
}
public static function page(LengthAwarePaginator $paginator, string $message = 'ok'): JsonResponse
{
return self::success([
'items' => $paginator->items(),
'meta' => [
'current_page' => $paginator->currentPage(),
'per_page' => $paginator->perPage(),
'total' => $paginator->total(),
'last_page' => $paginator->lastPage(),
],
], $message);
}
}

18
artisan Normal file
View File

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

27
bootstrap/app.php Normal file
View File

@ -0,0 +1,27 @@
<?php
use App\Http\Middleware\EnsurePermission;
use App\Http\Middleware\JwtAuthenticate;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'jwt.auth' => JwtAuthenticate::class,
'permission' => EnsurePermission::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen(
fn (Request $request) => $request->is('api/*'),
);
})->create();

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

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

9
bootstrap/providers.php Normal file
View File

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

91
composer.json Normal file
View File

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

9450
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

67
config/apidoc.php Normal file
View File

@ -0,0 +1,67 @@
<?php
return [
'title' => 'QuickQuiz API',
'desc' => 'QuickQuiz 题库系统接口文档',
'apps' => [
[
'title' => 'QuickQuiz',
'path' => 'app/Http/Controllers',
'key' => 'api',
],
],
'definitions' => 'app/Http/Controllers/Definitions',
'auto_url' => [
'letter_rule' => 'lcfirst',
'prefix' => '',
'filter_keys' => ['App', 'Http', 'Controllers'],
],
'auto_register_routes' => false,
'cache' => [
'enable' => false,
],
'auth' => [
'enable' => false,
'password' => '123456',
'secret_key' => 'quickquiz-apidoc',
'expire' => 86400,
],
'params' => [
'header' => [
['name' => 'Authorization', 'type' => 'string', 'require' => false, 'desc' => 'Bearer JWT token'],
],
'query' => [],
'body' => [],
],
'responses' => [
'success' => [
['name' => 'code', 'desc' => '业务代码', 'type' => 'int', 'require' => true],
['name' => 'message', 'desc' => '业务信息', 'type' => 'string', 'require' => true],
['name' => 'data', 'desc' => '业务数据', 'main' => true, 'type' => 'object', 'require' => true],
],
'error' => [
['name' => 'code', 'desc' => '业务代码', 'type' => 'int', 'require' => true],
['name' => 'message', 'desc' => '业务信息', 'type' => 'string', 'require' => true],
],
],
'responses_status' => [
['name' => '200', 'desc' => '请求成功'],
['name' => '401', 'desc' => '登录令牌无效'],
['name' => '403', 'desc' => '权限不足'],
['name' => '422', 'desc' => '参数错误'],
],
'route_prefix' => '/apidoc',
'default_author' => 'QuickQuiz',
'default_method' => 'GET',
'allowCrossDomain' => true,
'ignored_annitation' => [],
'ignored_methods' => [],
'database' => [],
'docs' => [],
'generator' => [],
'code_template' => [],
'share' => [
'enable' => false,
'actions' => [],
],
];

126
config/app.php Normal file
View File

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

121
config/auth.php Normal file
View File

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

136
config/cache.php Normal file
View File

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

184
config/database.php Normal file
View File

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

80
config/filesystems.php Normal file
View File

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

305
config/jwt.php Normal file
View File

@ -0,0 +1,305 @@
<?php
use Tymon\JWTAuth\Providers\Auth\Illuminate;
use Tymon\JWTAuth\Providers\JWT\Lcobucci;
use Tymon\JWTAuth\Providers\JWT\Provider;
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
/*
|--------------------------------------------------------------------------
| JWT Authentication Secret
|--------------------------------------------------------------------------
|
| Don't forget to set this in your .env file, as it will be used to sign
| your tokens. A helper command is provided for this:
| `php artisan jwt:secret`
|
| Note: This will be used for Symmetric algorithms only (HMAC),
| since RSA and ECDSA use a private/public key combo (See below).
|
*/
'secret' => env('JWT_SECRET'),
/*
|--------------------------------------------------------------------------
| JWT Authentication Keys
|--------------------------------------------------------------------------
|
| The algorithm you are using, will determine whether your tokens are
| signed with a random string (defined in `JWT_SECRET`) or using the
| following public & private keys.
|
| Symmetric Algorithms:
| HS256, HS384 & HS512 will use `JWT_SECRET`.
|
| Asymmetric Algorithms:
| RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
|
*/
'keys' => [
/*
|--------------------------------------------------------------------------
| Public Key
|--------------------------------------------------------------------------
|
| A path or resource to your public key.
|
| E.g. 'file://path/to/public/key'
|
*/
'public' => env('JWT_PUBLIC_KEY'),
/*
|--------------------------------------------------------------------------
| Private Key
|--------------------------------------------------------------------------
|
| A path or resource to your private key.
|
| E.g. 'file://path/to/private/key'
|
*/
'private' => env('JWT_PRIVATE_KEY'),
/*
|--------------------------------------------------------------------------
| Passphrase
|--------------------------------------------------------------------------
|
| The passphrase for your private key. Can be null if none set.
|
*/
'passphrase' => env('JWT_PASSPHRASE'),
],
/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour.
|
| You can also set this to null, to yield a never expiring token.
| Some people may want this behaviour for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
| Notice: If you set this to null you should remove 'exp' element from 'required_claims' list.
|
*/
'ttl' => env('JWT_TTL', 60),
/*
|--------------------------------------------------------------------------
| Refresh time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token can be refreshed
| within. I.E. The user can refresh their token within a 2 week window of
| the original token being created until they must re-authenticate.
| Defaults to 2 weeks.
|
| You can also set this to null, to yield an infinite refresh time.
| Some may want this instead of never expiring tokens for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
|
*/
'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),
/*
|--------------------------------------------------------------------------
| JWT hashing algorithm
|--------------------------------------------------------------------------
|
| Specify the hashing algorithm that will be used to sign the token.
|
*/
'algo' => env('JWT_ALGO', Provider::ALGO_HS256),
/*
|--------------------------------------------------------------------------
| Required Claims
|--------------------------------------------------------------------------
|
| Specify the required claims that must exist in any token.
| A TokenInvalidException will be thrown if any of these claims are not
| present in the payload.
|
*/
'required_claims' => [
'iss',
'iat',
'exp',
'nbf',
'sub',
'jti',
],
/*
|--------------------------------------------------------------------------
| Persistent Claims
|--------------------------------------------------------------------------
|
| Specify the claim keys to be persisted when refreshing a token.
| `sub` and `iat` will automatically be persisted, in
| addition to the these claims.
|
| Note: If a claim does not exist then it will be ignored.
|
*/
'persistent_claims' => [
// 'foo',
// 'bar',
],
/*
|--------------------------------------------------------------------------
| Lock Subject
|--------------------------------------------------------------------------
|
| This will determine whether a `prv` claim is automatically added to
| the token. The purpose of this is to ensure that if you have multiple
| authentication models e.g. `App\User` & `App\OtherPerson`, then we
| should prevent one authentication request from impersonating another,
| if 2 tokens happen to have the same id across the 2 different models.
|
| Under specific circumstances, you may want to disable this behaviour
| e.g. if you only have one authentication model, then you would save
| a little on token size.
|
*/
'lock_subject' => true,
/*
|--------------------------------------------------------------------------
| Leeway
|--------------------------------------------------------------------------
|
| This property gives the jwt timestamp claims some "leeway".
| Meaning that if you have any unavoidable slight clock skew on
| any of your servers then this will afford you some level of cushioning.
|
| This applies to the claims `iat`, `nbf` and `exp`.
|
| Specify in seconds - only if you know you need it.
|
*/
'leeway' => env('JWT_LEEWAY', 0),
/*
|--------------------------------------------------------------------------
| Blacklist Enabled
|--------------------------------------------------------------------------
|
| In order to invalidate tokens, you must have the blacklist enabled.
| If you do not want or need this functionality, then set this to false.
|
*/
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),
/*
| -------------------------------------------------------------------------
| Blacklist Grace Period
| -------------------------------------------------------------------------
|
| When multiple concurrent requests are made with the same JWT,
| it is possible that some of them fail, due to token regeneration
| on every request.
|
| Set grace period in seconds to prevent parallel request failure.
|
*/
'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),
/*
|--------------------------------------------------------------------------
| Cookies encryption
|--------------------------------------------------------------------------
|
| By default Laravel encrypt cookies for security reason.
| If you decide to not decrypt cookies, you will have to configure Laravel
| to not encrypt your cookie token by adding its name into the $except
| array available in the middleware "EncryptCookies" provided by Laravel.
| see https://laravel.com/docs/master/responses#cookies-and-encryption
| for details.
|
| Set it to true if you want to decrypt cookies.
|
*/
'decrypt_cookies' => false,
/*
|--------------------------------------------------------------------------
| Providers
|--------------------------------------------------------------------------
|
| Specify the various providers used throughout the package.
|
*/
'providers' => [
/*
|--------------------------------------------------------------------------
| JWT Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to create and decode the tokens.
|
*/
'jwt' => Lcobucci::class,
/*
|--------------------------------------------------------------------------
| Authentication Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to authenticate users.
|
*/
'auth' => Illuminate::class,
/*
|--------------------------------------------------------------------------
| Storage Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to store tokens in the blacklist.
|
*/
'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
],
];

132
config/logging.php Normal file
View File

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

118
config/mail.php Normal file
View File

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

129
config/queue.php Normal file
View File

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

38
config/services.php Normal file
View File

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

233
config/session.php Normal file
View File

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

1
database/.gitignore vendored Normal file
View File

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

View File

@ -0,0 +1,45 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,281 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('permissions', function (Blueprint $table): void {
$table->id();
$table->string('code')->unique();
$table->string('name');
$table->string('type')->default('button');
$table->string('parent_code')->nullable()->index();
$table->string('menu_path')->nullable();
$table->string('icon')->nullable();
$table->unsignedInteger('sort')->default(0);
$table->timestamps();
});
Schema::create('role_permissions', function (Blueprint $table): void {
$table->id();
$table->string('role')->index();
$table->foreignId('permission_id')->constrained()->cascadeOnDelete();
$table->timestamps();
$table->unique(['role', 'permission_id']);
});
Schema::create('system_settings', function (Blueprint $table): void {
$table->id();
$table->string('key')->unique();
$table->json('value')->nullable();
$table->string('group')->default('general')->index();
$table->timestamps();
});
Schema::create('question_banks', function (Blueprint $table): void {
$table->id();
$table->foreignId('owner_id')->constrained('users')->cascadeOnDelete();
$table->string('name');
$table->text('description')->nullable();
$table->string('visibility')->default('private')->index();
$table->boolean('is_active')->default(true)->index();
$table->softDeletes();
$table->timestamps();
});
Schema::create('question_categories', function (Blueprint $table): void {
$table->id();
$table->foreignId('question_bank_id')->constrained()->cascadeOnDelete();
$table->foreignId('parent_id')->nullable()->constrained('question_categories')->nullOnDelete();
$table->string('name');
$table->unsignedInteger('sort')->default(0);
$table->timestamps();
});
Schema::create('question_tags', function (Blueprint $table): void {
$table->id();
$table->foreignId('question_bank_id')->constrained()->cascadeOnDelete();
$table->string('name');
$table->timestamps();
$table->unique(['question_bank_id', 'name']);
});
Schema::create('questions', function (Blueprint $table): void {
$table->id();
$table->foreignId('question_bank_id')->constrained()->cascadeOnDelete();
$table->foreignId('category_id')->nullable()->constrained('question_categories')->nullOnDelete();
$table->foreignId('creator_id')->constrained('users')->cascadeOnDelete();
$table->string('type')->index();
$table->text('content');
$table->text('explanation')->nullable();
$table->json('answers')->nullable();
$table->string('source_question_id')->nullable()->index();
$table->char('dedup_hash', 64)->index();
$table->boolean('is_active')->default(true)->index();
$table->softDeletes();
$table->timestamps();
});
Schema::create('question_options', function (Blueprint $table): void {
$table->id();
$table->foreignId('question_id')->constrained()->cascadeOnDelete();
$table->text('content');
$table->boolean('is_correct')->default(false);
$table->unsignedInteger('sort')->default(0);
$table->timestamps();
});
Schema::create('question_tag', function (Blueprint $table): void {
$table->id();
$table->foreignId('question_id')->constrained()->cascadeOnDelete();
$table->foreignId('question_tag_id')->constrained()->cascadeOnDelete();
$table->unique(['question_id', 'question_tag_id']);
});
Schema::create('classes', function (Blueprint $table): void {
$table->id();
$table->foreignId('owner_id')->constrained('users')->cascadeOnDelete();
$table->string('name');
$table->string('join_code')->unique();
$table->text('description')->nullable();
$table->boolean('is_active')->default(true)->index();
$table->softDeletes();
$table->timestamps();
});
Schema::create('class_members', function (Blueprint $table): void {
$table->id();
$table->foreignId('class_id')->constrained('classes')->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('role')->default('student');
$table->timestamps();
$table->unique(['class_id', 'user_id']);
});
Schema::create('bank_shares', function (Blueprint $table): void {
$table->id();
$table->foreignId('question_bank_id')->constrained()->cascadeOnDelete();
$table->string('target_type')->index();
$table->unsignedBigInteger('target_id')->index();
$table->timestamps();
$table->unique(['question_bank_id', 'target_type', 'target_id']);
});
Schema::create('invite_codes', function (Blueprint $table): void {
$table->id();
$table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
$table->string('code')->unique();
$table->string('role')->default('user');
$table->unsignedInteger('max_uses')->default(1);
$table->unsignedInteger('used_count')->default(0);
$table->timestamp('expires_at')->nullable();
$table->boolean('is_active')->default(true)->index();
$table->timestamps();
});
Schema::create('papers', function (Blueprint $table): void {
$table->id();
$table->foreignId('owner_id')->constrained('users')->cascadeOnDelete();
$table->foreignId('question_bank_id')->nullable()->constrained()->nullOnDelete();
$table->string('title');
$table->text('description')->nullable();
$table->unsignedInteger('duration_minutes')->nullable();
$table->unsignedInteger('attempt_limit')->nullable();
$table->boolean('is_active')->default(true)->index();
$table->softDeletes();
$table->timestamps();
});
Schema::create('paper_questions', function (Blueprint $table): void {
$table->id();
$table->foreignId('paper_id')->constrained()->cascadeOnDelete();
$table->foreignId('question_id')->constrained()->cascadeOnDelete();
$table->decimal('score', 8, 2)->nullable();
$table->unsignedInteger('sort')->default(0);
$table->timestamps();
$table->unique(['paper_id', 'question_id']);
});
Schema::create('quiz_attempts', function (Blueprint $table): void {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('paper_id')->nullable()->constrained()->nullOnDelete();
$table->foreignId('question_bank_id')->nullable()->constrained()->nullOnDelete();
$table->string('mode')->index();
$table->string('status')->default('in_progress')->index();
$table->json('draw_rule')->nullable();
$table->timestamp('started_at');
$table->timestamp('expires_at')->nullable();
$table->timestamp('submitted_at')->nullable();
$table->decimal('score', 8, 2)->default(0);
$table->unsignedInteger('total_questions')->default(0);
$table->unsignedInteger('correct_count')->default(0);
$table->unsignedInteger('current_index')->default(0);
$table->timestamps();
});
Schema::create('quiz_attempt_questions', function (Blueprint $table): void {
$table->id();
$table->foreignId('quiz_attempt_id')->constrained()->cascadeOnDelete();
$table->foreignId('question_id')->constrained()->cascadeOnDelete();
$table->decimal('score', 8, 2)->default(0);
$table->unsignedInteger('sort')->default(0);
$table->json('answer')->nullable();
$table->boolean('is_correct')->nullable();
$table->unsignedInteger('duration_seconds')->default(0);
$table->boolean('explanation_viewed')->default(false);
$table->timestamp('answered_at')->nullable();
$table->timestamps();
$table->unique(['quiz_attempt_id', 'question_id']);
});
Schema::create('wrong_questions', function (Blueprint $table): void {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('question_id')->constrained()->cascadeOnDelete();
$table->unsignedInteger('wrong_count')->default(1);
$table->unsignedInteger('consecutive_correct_count')->default(0);
$table->timestamp('last_wrong_at')->nullable();
$table->timestamp('mastered_at')->nullable();
$table->timestamps();
$table->unique(['user_id', 'question_id']);
});
Schema::create('favorite_questions', function (Blueprint $table): void {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('question_id')->constrained()->cascadeOnDelete();
$table->text('note')->nullable();
$table->timestamps();
$table->unique(['user_id', 'question_id']);
});
Schema::create('import_jobs', function (Blueprint $table): void {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('question_bank_id')->constrained()->cascadeOnDelete();
$table->string('type');
$table->string('file_path')->nullable();
$table->string('status')->default('pending')->index();
$table->unsignedInteger('total_count')->default(0);
$table->unsignedInteger('success_count')->default(0);
$table->unsignedInteger('skipped_count')->default(0);
$table->json('report')->nullable();
$table->timestamps();
});
Schema::create('operation_logs', function (Blueprint $table): void {
$table->id();
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
$table->string('action')->index();
$table->string('target_type')->nullable();
$table->unsignedBigInteger('target_id')->nullable();
$table->ipAddress('ip')->nullable();
$table->json('payload')->nullable();
$table->timestamps();
});
Schema::create('exports', function (Blueprint $table): void {
$table->id();
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
$table->string('type')->index();
$table->string('file_path');
$table->json('payload')->nullable();
$table->timestamps();
});
}
public function down(): void
{
foreach ([
'exports',
'operation_logs',
'import_jobs',
'favorite_questions',
'wrong_questions',
'quiz_attempt_questions',
'quiz_attempts',
'paper_questions',
'papers',
'invite_codes',
'bank_shares',
'class_members',
'classes',
'question_tag',
'question_options',
'questions',
'question_tags',
'question_categories',
'question_banks',
'system_settings',
'role_permissions',
'permissions',
] as $table) {
Schema::dropIfExists($table);
}
}
};

View File

@ -0,0 +1,106 @@
<?php
namespace Database\Seeders;
use App\Models\Permission;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Seed the application's database.
*/
public function run(): void
{
$admin = User::query()->firstOrCreate(
['email' => 'admin@quickquiz.local'],
[
'name' => '系统管理员',
'role' => 'admin',
'is_active' => true,
'password' => Hash::make('password'),
],
);
$permissions = [
['code' => 'dashboard', 'name' => '控制台', 'type' => 'menu', 'menu_path' => '/admin/dashboard', 'sort' => 10],
['code' => 'users', 'name' => '用户管理', 'type' => 'menu', 'menu_path' => '/admin/users', 'sort' => 20],
['code' => 'users.create', 'name' => '新增用户', 'type' => 'button', 'parent_code' => 'users'],
['code' => 'users.update', 'name' => '编辑用户', 'type' => 'button', 'parent_code' => 'users'],
['code' => 'users.disable', 'name' => '禁用用户', 'type' => 'button', 'parent_code' => 'users'],
['code' => 'permissions', 'name' => '权限管理', 'type' => 'menu', 'menu_path' => '/admin/permissions', 'sort' => 30],
['code' => 'classes', 'name' => '班级管理', 'type' => 'menu', 'menu_path' => '/admin/classes', 'sort' => 40],
['code' => 'banks', 'name' => '题库管理', 'type' => 'menu', 'menu_path' => '/admin/banks', 'sort' => 50],
['code' => 'banks.create', 'name' => '新增题库', 'type' => 'button', 'parent_code' => 'banks'],
['code' => 'banks.update', 'name' => '编辑题库', 'type' => 'button', 'parent_code' => 'banks'],
['code' => 'banks.delete', 'name' => '删除题库', 'type' => 'button', 'parent_code' => 'banks'],
['code' => 'banks.share', 'name' => '题库授权', 'type' => 'button', 'parent_code' => 'banks'],
['code' => 'questions', 'name' => '题目管理', 'type' => 'menu', 'menu_path' => '/admin/questions', 'sort' => 60],
['code' => 'questions.import', 'name' => '批量导入', 'type' => 'button', 'parent_code' => 'questions'],
['code' => 'questions.export', 'name' => '题库导出', 'type' => 'button', 'parent_code' => 'questions'],
['code' => 'papers', 'name' => '试卷管理', 'type' => 'menu', 'menu_path' => '/admin/papers', 'sort' => 70],
['code' => 'reports', 'name' => '统计报表', 'type' => 'menu', 'menu_path' => '/admin/reports', 'sort' => 80],
['code' => 'settings', 'name' => '系统配置', 'type' => 'menu', 'menu_path' => '/admin/settings', 'sort' => 90],
['code' => 'logs', 'name' => '操作日志', 'type' => 'menu', 'menu_path' => '/admin/logs', 'sort' => 100],
];
foreach ($permissions as $permission) {
Permission::query()->updateOrCreate(['code' => $permission['code']], $permission);
}
$teacherPermissions = Permission::query()
->whereIn('code', ['dashboard', 'classes', 'banks', 'banks.create', 'banks.update', 'banks.delete', 'banks.share', 'questions', 'questions.import', 'questions.export', 'papers', 'reports'])
->pluck('id');
foreach ($teacherPermissions as $permissionId) {
DB::table('role_permissions')->updateOrInsert([
'role' => 'teacher',
'permission_id' => $permissionId,
], [
'created_at' => now(),
'updated_at' => now(),
]);
}
$settings = [
'site.name' => 'QuickQuiz',
'register.enabled' => true,
'invite.required' => true,
'score.single' => 1,
'score.multiple' => 2,
'score.judge' => 1,
'score.blank' => 2,
'test.default_duration_minutes' => 45,
'mail.enabled' => false,
'sms.enabled' => false,
];
foreach ($settings as $key => $value) {
DB::table('system_settings')->updateOrInsert([
'key' => $key,
], [
'value' => json_encode($value, JSON_UNESCAPED_UNICODE),
'group' => str_contains($key, '.') ? explode('.', $key)[0] : 'general',
'created_at' => now(),
'updated_at' => now(),
]);
}
DB::table('operation_logs')->insert([
'user_id' => $admin->id,
'action' => 'system.seeded',
'target_type' => 'system',
'target_id' => null,
'ip' => null,
'payload' => json_encode(['message' => 'Initial roles, permissions, and settings seeded'], JSON_UNESCAPED_UNICODE),
'created_at' => now(),
'updated_at' => now(),
]);
}
}

24
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

3
frontend/.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"recommendations": ["Vue.volar"]
}

5
frontend/README.md Normal file
View File

@ -0,0 +1,5 @@
# Vue 3 + TypeScript + Vite
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).

10
frontend/auto-imports.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
export {}
declare global {
}

48
frontend/components.d.ts vendored Normal file
View File

@ -0,0 +1,48 @@
/* eslint-disable */
// @ts-nocheck
// biome-ignore lint: disable
// oxlint-disable
// ------
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
export {}
/* prettier-ignore */
declare module 'vue' {
export interface GlobalComponents {
ElAlert: typeof import('element-plus/es')['ElAlert']
ElButton: typeof import('element-plus/es')['ElButton']
ElCheckbox: typeof import('element-plus/es')['ElCheckbox']
ElCheckboxGroup: typeof import('element-plus/es')['ElCheckboxGroup']
ElDialog: typeof import('element-plus/es')['ElDialog']
ElDrawer: typeof import('element-plus/es')['ElDrawer']
ElEmpty: typeof import('element-plus/es')['ElEmpty']
ElForm: typeof import('element-plus/es')['ElForm']
ElFormItem: typeof import('element-plus/es')['ElFormItem']
ElIcon: typeof import('element-plus/es')['ElIcon']
ElInput: typeof import('element-plus/es')['ElInput']
ElInputNumber: typeof import('element-plus/es')['ElInputNumber']
ElMenu: typeof import('element-plus/es')['ElMenu']
ElMenuItem: typeof import('element-plus/es')['ElMenuItem']
ElOption: typeof import('element-plus/es')['ElOption']
ElPagination: typeof import('element-plus/es')['ElPagination']
ElRadio: typeof import('element-plus/es')['ElRadio']
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
ElSegmented: typeof import('element-plus/es')['ElSegmented']
ElSelect: typeof import('element-plus/es')['ElSelect']
ElSwitch: typeof import('element-plus/es')['ElSwitch']
ElTable: typeof import('element-plus/es')['ElTable']
ElTableColumn: typeof import('element-plus/es')['ElTableColumn']
ElTabPane: typeof import('element-plus/es')['ElTabPane']
ElTabs: typeof import('element-plus/es')['ElTabs']
ElTag: typeof import('element-plus/es')['ElTag']
ElTree: typeof import('element-plus/es')['ElTree']
ElUpload: typeof import('element-plus/es')['ElUpload']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
}
export interface GlobalDirectives {
vLoading: typeof import('element-plus/es')['ElLoadingDirective']
}
}

13
frontend/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

3865
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

34
frontend/package.json Normal file
View File

@ -0,0 +1,34 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.2",
"axios": "^1.18.1",
"crypto-js": "^4.2.0",
"echarts": "^6.1.0",
"element-plus": "^2.14.2",
"pinia": "^3.0.4",
"vue": "^3.5.38",
"vue-echarts": "^8.0.1",
"vue-router": "^5.1.0"
},
"devDependencies": {
"@types/node": "^24.13.2",
"@unocss/preset-wind3": "^66.7.2",
"@vitejs/plugin-vue": "^6.0.7",
"@vue/tsconfig": "^0.9.1",
"typescript": "~6.0.2",
"unocss": "^66.7.2",
"unplugin-auto-import": "^21.0.0",
"unplugin-vue-components": "^32.1.0",
"vite": "^8.1.0",
"vue-tsc": "^3.3.5"
}
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

24
frontend/public/icons.svg Normal file
View File

@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

3
frontend/src/App.vue Normal file
View File

@ -0,0 +1,3 @@
<template>
<RouterView />
</template>

217
frontend/src/api/admin.ts Normal file
View File

@ -0,0 +1,217 @@
import { apiDelete, apiGet, apiPost, apiPut } from './http'
import type { ImportJob, PageData, Paper, Permission, Question, QuestionBank, SchoolClass, TaxonomyItem, User } from '@/types/api'
export function fetchBanks(params?: Record<string, unknown>) {
return apiGet<PageData<QuestionBank>>('/api/admin/banks', params)
}
export function createBank(payload: Partial<QuestionBank>) {
return apiPost<QuestionBank>('/api/admin/banks', payload)
}
export function updateBank(bankId: number, payload: Partial<QuestionBank>) {
return apiPut<QuestionBank>(`/api/admin/banks/${bankId}`, payload)
}
export function deleteBank(bankId: number) {
return apiDelete<null>(`/api/admin/banks/${bankId}`)
}
export function shareBank(bankId: number, targets: Array<{ type: 'user' | 'class'; id: number }>) {
return apiPost<null>(`/api/admin/banks/${bankId}/shares`, { targets })
}
export function fetchQuestions(params?: Record<string, unknown>) {
return apiGet<PageData<Question>>('/api/admin/questions', params)
}
export function createQuestion(payload: Record<string, unknown>) {
return apiPost('/api/admin/questions', payload)
}
export function updateQuestion(questionId: number, payload: Partial<Question>) {
return apiPut<Question>(`/api/admin/questions/${questionId}`, payload)
}
export function deleteQuestion(questionId: number) {
return apiDelete<null>(`/api/admin/questions/${questionId}`)
}
export function importQuestions(bankId: number, file: File) {
const form = new FormData()
form.append('file', file)
return apiPost<ImportJob>(`/api/admin/banks/${bankId}/imports`, form)
}
export function validateQuestionImport(bankId: number, file: File) {
const form = new FormData()
form.append('file', file)
return apiPost<{
valid: boolean
rows: Array<Record<string, unknown>>
errors: Array<{ row: number; message: string }>
type: string
file_path: string
}>(`/api/admin/banks/${bankId}/imports/validate`, form)
}
export function importQuestionRows(bankId: number, payload: {
rows: Array<Record<string, unknown>>
type?: string
file_path?: string
}) {
return apiPost<ImportJob>(`/api/admin/banks/${bankId}/imports/rows`, payload)
}
export function validateQuestionRows(bankId: number, payload: {
rows: Array<Record<string, unknown>>
}) {
return apiPost<{
valid: boolean
rows: Array<Record<string, unknown>>
errors: Array<{ row: number; message: string }>
}>(`/api/admin/banks/${bankId}/imports/rows/validate`, payload)
}
export function exportBank(bankId: number) {
return apiPost(`/api/admin/banks/${bankId}/export`)
}
export function fetchCategories(bankId: number) {
return apiGet<TaxonomyItem[]>(`/api/admin/banks/${bankId}/categories`)
}
export function createCategory(bankId: number, payload: { name: string; parent_id?: number; sort?: number }) {
return apiPost(`/api/admin/banks/${bankId}/categories`, payload)
}
export function fetchTags(bankId: number) {
return apiGet<TaxonomyItem[]>(`/api/admin/banks/${bankId}/tags`)
}
export function createTag(bankId: number, payload: { name: string }) {
return apiPost(`/api/admin/banks/${bankId}/tags`, payload)
}
export function fetchUsers(params?: Record<string, unknown>) {
return apiGet<PageData<User>>('/api/admin/users', params)
}
export function fetchClasses(params?: Record<string, unknown>) {
return apiGet<PageData<SchoolClass>>('/api/admin/classes', params)
}
export function createClass(payload: { name: string; description?: string }) {
return apiPost<SchoolClass>('/api/admin/classes', payload)
}
export function addClassMember(classId: number, payload: { user_id: number; role?: string }) {
return apiPost<SchoolClass>(`/api/admin/classes/${classId}/members`, payload)
}
export function fetchPapers(params?: Record<string, unknown>) {
return apiGet<PageData<Paper>>('/api/admin/papers', params)
}
export function fetchPaper(paperId: number) {
return apiGet<Paper>(`/api/admin/papers/${paperId}`)
}
export function createPaper(payload: {
title: string
description?: string
question_bank_id?: number
duration_minutes?: number
attempt_limit?: number
is_active?: boolean
questions?: Array<{ id: number; score?: number }>
}) {
return apiPost<Paper>('/api/admin/papers', payload)
}
export function updatePaper(paperId: number, payload: {
title?: string
description?: string
question_bank_id?: number
duration_minutes?: number
attempt_limit?: number
is_active?: boolean
questions?: Array<{ id: number; score?: number }>
}) {
return apiPut<Paper>(`/api/admin/papers/${paperId}`, payload)
}
export function deletePaper(paperId: number) {
return apiDelete<null>(`/api/admin/papers/${paperId}`)
}
export function createUser(payload: { name: string; email: string; password: string; role: string }) {
return apiPost<User>('/api/admin/users', payload)
}
export function updateUser(userId: number, payload: {
name?: string
role?: string
is_active?: boolean
password?: string
}) {
return apiPut<User>(`/api/admin/users/${userId}`, payload)
}
export function fetchInvites(params?: Record<string, unknown>) {
return apiGet<PageData<Record<string, unknown>>>('/api/admin/invite-codes', params)
}
export function createInvite(payload: { role: string; max_uses: number; expires_at?: string }) {
return apiPost('/api/admin/invite-codes', payload)
}
export function fetchPermissions() {
return apiGet<{
permissions: Permission[]
role_permissions: Record<string, number[]>
}>('/api/admin/permissions')
}
export function syncRolePermissions(role: string, permissionIds: number[]) {
return apiPut(`/api/admin/roles/${role}/permissions`, { permission_ids: permissionIds })
}
export function fetchSettings() {
return apiGet<Array<{ key: string; value: unknown; group: string }>>('/api/admin/settings')
}
export function saveSettings(settings: Record<string, unknown>) {
return apiPut('/api/admin/settings', { settings })
}
export function fetchReportOverview() {
return apiGet<Record<string, number>>('/api/admin/reports/overview')
}
export function fetchReportTrends() {
return apiGet<Array<Record<string, unknown>>>('/api/admin/reports/trends')
}
export function fetchQuestionErrors(params?: Record<string, unknown>) {
return apiGet<PageData<Record<string, unknown>>>('/api/admin/reports/question-errors', params)
}
export function fetchClassRanking() {
return apiGet<Array<Record<string, unknown>>>('/api/admin/reports/class-ranking')
}
export function fetchMastery() {
return apiGet<{
banks: Array<Record<string, unknown>>
categories: Array<Record<string, unknown>>
}>('/api/admin/reports/mastery')
}
export function exportReport() {
return apiPost('/api/admin/reports/export')
}
export function fetchLogs(params?: Record<string, unknown>) {
return apiGet<PageData<Record<string, unknown>>>('/api/admin/logs', params)
}

58
frontend/src/api/auth.ts Normal file
View File

@ -0,0 +1,58 @@
import { apiGet, apiPost } from './http'
import type { User } from '@/types/api'
export interface LoginPayload {
email: string
password: string
captcha?: string
}
export interface LoginResult {
token: string
token_type: string
expires_in: number
user: User
}
export function login(payload: LoginPayload) {
return apiPost<LoginResult>('/api/auth/login', payload)
}
export function register(payload: {
name: string
email: string
password: string
password_confirmation: string
invite_code: string
}) {
return apiPost<LoginResult>('/api/auth/register', payload)
}
export function me() {
return apiGet<User>('/api/auth/me')
}
export function captcha() {
return apiGet<{ captcha: string; expires_in: number }>('/api/auth/captcha')
}
export function forgotPassword(email: string) {
return apiPost<{ token?: string }>('/api/auth/forgot-password', { email })
}
export function resetPassword(payload: {
email: string
token: string
password: string
password_confirmation: string
}) {
return apiPost('/api/auth/reset-password', payload)
}
export function installStatus() {
return apiGet<{ installed: boolean; database: string }>('/api/install/status')
}
export function runInstall(payload: { admin_email: string; admin_password: string; fresh?: boolean }) {
return apiPost('/api/install/run', payload)
}

57
frontend/src/api/http.ts Normal file
View File

@ -0,0 +1,57 @@
import axios from 'axios'
import type { ApiResponse } from '@/types/api'
import { useAuthStore } from '@/stores/auth'
export const http = axios.create({
baseURL: '',
timeout: 20000,
})
http.interceptors.request.use((config) => {
const auth = useAuthStore()
if (auth.token) {
config.headers.Authorization = `Bearer ${auth.token}`
}
return config
})
http.interceptors.response.use(
(response) => response.data,
async (error) => {
const auth = useAuthStore()
if (error.response?.status === 401 && auth.token) {
auth.clearSession()
}
return Promise.reject(error)
},
)
export async function apiGet<T>(url: string, params?: Record<string, unknown>): Promise<ApiResponse<T>> {
return http.get(url, { params }) as unknown as ApiResponse<T>
}
export async function apiPost<T>(url: string, data?: unknown): Promise<ApiResponse<T>> {
return http.post(url, data) as unknown as ApiResponse<T>
}
export async function apiPut<T>(url: string, data?: unknown): Promise<ApiResponse<T>> {
return http.put(url, data) as unknown as ApiResponse<T>
}
export function apiPutKeepalive(url: string, data?: unknown) {
const auth = useAuthStore()
return fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
...(auth.token ? { Authorization: `Bearer ${auth.token}` } : {}),
},
body: JSON.stringify(data ?? {}),
keepalive: true,
})
}
export async function apiDelete<T>(url: string): Promise<ApiResponse<T>> {
return http.delete(url) as unknown as ApiResponse<T>
}

42
frontend/src/api/quiz.ts Normal file
View File

@ -0,0 +1,42 @@
import { apiGet, apiPost, apiPut, apiPutKeepalive } from './http'
import type { PageData, QuizAttempt, WrongQuestion } from '@/types/api'
export function fetchResources() {
return apiGet('/api/app/resources')
}
export function startBankAttempt(bankId: number, payload: Record<string, unknown>) {
return apiPost<QuizAttempt>(`/api/app/banks/${bankId}/attempts`, payload)
}
export function startPaperAttempt(paperId: number) {
return apiPost<QuizAttempt>(`/api/app/papers/${paperId}/attempts`)
}
export function fetchAttempt(attemptId: number) {
return apiGet<QuizAttempt>(`/api/app/attempts/${attemptId}`)
}
export function answerQuestion(attemptId: number, payload: { question_id: number; answer: Array<number | string>; duration_seconds?: number }) {
return apiPost(`/api/app/attempts/${attemptId}/answer`, payload)
}
export function updateAttemptPosition(attemptId: number, currentIndex: number) {
return apiPut<QuizAttempt>(`/api/app/attempts/${attemptId}/position`, { current_index: currentIndex })
}
export function updateAttemptPositionKeepalive(attemptId: number, currentIndex: number) {
return apiPutKeepalive(`/api/app/attempts/${attemptId}/position`, { current_index: currentIndex })
}
export function submitAttempt(attemptId: number) {
return apiPost<QuizAttempt>(`/api/app/attempts/${attemptId}/submit`)
}
export function fetchWrongQuestions(params?: Record<string, unknown>) {
return apiGet<PageData<WrongQuestion>>('/api/app/wrong-questions', params)
}
export function saveFavorite(payload: { question_id: number; note?: string }) {
return apiPost('/api/app/favorites', payload)
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

View File

@ -0,0 +1,145 @@
<script setup lang="ts">
import { computed, shallowRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Collection, DataAnalysis, Files, House, Key, Menu, Notebook, OfficeBuilding, PriceTag, Setting, Tickets, User } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const collapsed = shallowRef(false)
const activeMenu = computed(() => route.path)
const menus = [
{ path: '/admin/dashboard', label: '控制台', icon: House, permission: 'dashboard' },
{ path: '/admin/banks', label: '题库管理', icon: Collection, permission: 'banks' },
{ path: '/admin/questions', label: '题目管理', icon: Files, permission: 'questions' },
{ path: '/admin/taxonomy', label: '分类标签', icon: PriceTag, permission: 'questions' },
{ path: '/admin/papers', label: '试卷管理', icon: Notebook, permission: 'papers' },
{ path: '/admin/classes', label: '班级管理', icon: OfficeBuilding, permission: 'classes' },
{ path: '/admin/reports', label: '统计报表', icon: DataAnalysis, permission: 'reports' },
{ path: '/admin/users', label: '用户权限', icon: User, permission: 'users' },
{ path: '/admin/permissions', label: '角色权限', icon: Key, permission: 'permissions' },
{ path: '/admin/settings', label: '系统配置', icon: Setting, permission: 'settings' },
{ path: '/admin/logs', label: '操作日志', icon: Tickets, permission: 'logs' },
]
const visibleMenus = computed(() => menus.filter((item) => auth.can(item.permission)))
</script>
<template>
<div class="admin-shell">
<aside class="admin-aside" :class="{ 'admin-aside--collapsed': collapsed }">
<div class="brand">
<span class="brand-mark">Q</span>
<span v-show="!collapsed" class="brand-name">QuickQuiz</span>
</div>
<ElMenu :default-active="activeMenu" class="admin-menu" :collapse="collapsed" router>
<ElMenuItem v-for="item in visibleMenus" :key="item.path" :index="item.path">
<ElIcon><component :is="item.icon" /></ElIcon>
<span>{{ item.label }}</span>
</ElMenuItem>
</ElMenu>
</aside>
<main class="admin-main">
<header class="admin-topbar">
<ElButton :icon="Menu" circle @click="collapsed = !collapsed" />
<div>
<p class="page-title">题库工作台</p>
<p class="muted text-sm">管理题库导入题目查看学习数据</p>
</div>
<ElButton type="primary" plain @click="router.push('/quiz')">进入学习端</ElButton>
</header>
<section class="admin-content">
<RouterView />
</section>
</main>
</div>
</template>
<style scoped>
.admin-shell {
display: flex;
min-height: 100vh;
}
.admin-aside {
width: 236px;
min-height: 100vh;
border-right: 1px solid var(--qq-line);
background: rgba(255, 255, 255, 0.88);
transition: width 0.2s ease;
}
.admin-aside--collapsed {
width: 76px;
}
.brand {
display: flex;
align-items: center;
gap: 10px;
height: 64px;
padding: 0 18px;
border-bottom: 1px solid var(--qq-line);
}
.brand-mark {
display: inline-grid;
place-items: center;
width: 36px;
height: 36px;
border-radius: 8px;
background: var(--qq-moss);
color: white;
font-weight: 800;
}
.brand-name {
font-weight: 800;
font-size: 18px;
}
.admin-menu {
border-right: 0;
background: transparent;
}
.admin-main {
min-width: 0;
flex: 1;
}
.admin-topbar {
display: flex;
align-items: center;
gap: 16px;
min-height: 64px;
padding: 12px 22px;
border-bottom: 1px solid var(--qq-line);
background: rgba(247, 248, 244, 0.92);
}
.admin-topbar > div {
flex: 1;
}
.admin-content {
padding: 22px;
}
@media (max-width: 760px) {
.admin-shell {
display: block;
}
.admin-aside {
width: 100%;
min-height: auto;
}
.admin-aside--collapsed .admin-menu {
display: none;
}
.admin-content {
padding: 14px;
}
}
</style>

View File

@ -0,0 +1,50 @@
<script setup lang="ts">
import { useRouter } from 'vue-router'
import { Collection, Setting } from '@element-plus/icons-vue'
const router = useRouter()
</script>
<template>
<div class="quiz-shell">
<header class="quiz-header">
<button class="quiz-brand" @click="router.push('/quiz')">
<Collection class="w-5 h-5" />
<span>QuickQuiz</span>
</button>
<ElButton :icon="Setting" circle @click="router.push('/admin')" />
</header>
<RouterView />
</div>
</template>
<style scoped>
.quiz-shell {
min-height: 100vh;
}
.quiz-header {
position: sticky;
top: 0;
z-index: 10;
display: flex;
align-items: center;
justify-content: space-between;
height: 56px;
padding: 0 16px;
border-bottom: 1px solid var(--qq-line);
background: rgba(247, 248, 244, 0.94);
backdrop-filter: blur(12px);
}
.quiz-brand {
display: inline-flex;
align-items: center;
gap: 8px;
border: 0;
background: transparent;
color: var(--qq-ink);
font-weight: 800;
cursor: pointer;
}
</style>

15
frontend/src/main.ts Normal file
View File

@ -0,0 +1,15 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import 'element-plus/dist/index.css'
import 'virtual:uno.css'
import './style.css'
import App from './App.vue'
import { router } from './router'
createApp(App)
.use(createPinia())
.use(router)
.use(ElementPlus, { locale: zhCn, size: 'default' })
.mount('#app')

View File

@ -0,0 +1,54 @@
import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
export const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/login', component: () => import('@/views/LoginView.vue') },
{ path: '/register', component: () => import('@/views/RegisterView.vue') },
{ path: '/install', component: () => import('@/views/InstallView.vue') },
{
path: '/admin',
component: () => import('@/layouts/AdminLayout.vue'),
meta: { requiresAuth: true },
children: [
{ path: '', redirect: '/admin/dashboard' },
{ path: 'dashboard', component: () => import('@/views/admin/DashboardView.vue') },
{ path: 'banks', component: () => import('@/views/admin/BanksView.vue') },
{ path: 'questions', component: () => import('@/views/admin/QuestionsView.vue') },
{ path: 'taxonomy', component: () => import('@/views/admin/TaxonomyView.vue') },
{ path: 'papers', component: () => import('@/views/admin/PapersView.vue') },
{ path: 'classes', component: () => import('@/views/admin/ClassesView.vue') },
{ path: 'reports', component: () => import('@/views/admin/ReportsView.vue') },
{ path: 'users', component: () => import('@/views/admin/UsersView.vue') },
{ path: 'permissions', component: () => import('@/views/admin/PermissionsView.vue') },
{ path: 'settings', component: () => import('@/views/admin/SettingsView.vue') },
{ path: 'logs', component: () => import('@/views/admin/LogsView.vue') },
],
},
{
path: '/quiz',
component: () => import('@/layouts/QuizLayout.vue'),
meta: { requiresAuth: true },
children: [
{ path: '', component: () => import('@/views/app/ResourcesView.vue') },
{ path: 'wrong-questions', component: () => import('@/views/app/WrongQuestionsView.vue') },
{ path: ':attemptId', component: () => import('@/views/app/QuizView.vue') },
],
},
{ path: '/', redirect: '/quiz' },
],
})
router.beforeEach(async (to) => {
const auth = useAuthStore()
if (auth.token && !auth.user) {
await auth.loadMe().catch(() => auth.clearSession())
}
if (to.meta.requiresAuth && !auth.isAuthed) {
return '/login'
}
if (to.path === '/login' && auth.isAuthed) {
return '/quiz'
}
})

View File

@ -0,0 +1,38 @@
import { computed, shallowRef } from 'vue'
import { defineStore } from 'pinia'
import type { User } from '@/types/api'
import { login as loginApi, me } from '@/api/auth'
export const useAuthStore = defineStore('auth', () => {
const token = shallowRef(localStorage.getItem('qq_token') || '')
const user = shallowRef<User | null>(null)
const isAuthed = computed(() => Boolean(token.value))
const isAdmin = computed(() => user.value?.role === 'admin')
const permissionCodes = computed(() => new Set(user.value?.permissions?.map((item) => item.code) ?? []))
function can(permission: string) {
return user.value?.role === 'admin' || permissionCodes.value.has(permission)
}
async function login(email: string, password: string) {
const response = await loginApi({ email, password })
token.value = response.data.token
user.value = response.data.user
localStorage.setItem('qq_token', token.value)
}
async function loadMe() {
if (!token.value) return
const response = await me()
user.value = response.data
}
function clearSession() {
token.value = ''
user.value = null
localStorage.removeItem('qq_token')
}
return { token, user, isAuthed, isAdmin, permissionCodes, can, login, loadMe, clearSession }
})

160
frontend/src/stores/quiz.ts Normal file
View File

@ -0,0 +1,160 @@
import { computed, shallowRef } from 'vue'
import { defineStore } from 'pinia'
import type { QuizAttempt } from '@/types/api'
import {
answerQuestion,
fetchAttempt,
startBankAttempt,
submitAttempt,
updateAttemptPosition,
updateAttemptPositionKeepalive,
} from '@/api/quiz'
export const useQuizStore = defineStore('quiz', () => {
const attempt = shallowRef<QuizAttempt | null>(null)
const currentIndex = shallowRef(0)
const pendingSyncs = new Set<Promise<unknown>>()
const lastSavedPosition = shallowRef(0)
const positionDirty = shallowRef(false)
const currentItem = computed(() => attempt.value?.items[currentIndex.value] ?? null)
const answeredCount = computed(() => attempt.value?.items.filter((item) => item.answer && item.answer.length > 0).length ?? 0)
function clear() {
attempt.value = null
currentIndex.value = 0
lastSavedPosition.value = 0
positionDirty.value = false
pendingSyncs.clear()
}
async function start(bankId: number, mode: string, limit = 20) {
const response = await startBankAttempt(bankId, { mode, limit })
attempt.value = response.data
currentIndex.value = 0
lastSavedPosition.value = response.data.current_index || 0
positionDirty.value = false
}
async function resume(attemptId: number) {
const response = await fetchAttempt(attemptId)
attempt.value = response.data
currentIndex.value = response.data.current_index || 0
lastSavedPosition.value = currentIndex.value
positionDirty.value = false
}
async function answer(answer: Array<number | string>, durationSeconds = 0) {
if (!attempt.value || !currentItem.value) return
const currentAttempt = attempt.value
const currentQuestion = currentItem.value.question
const questionId = currentItem.value.question_id
if (currentAttempt.mode !== 'paper') {
const isCorrect = judgeAnswer(currentQuestion, answer)
attempt.value = {
...currentAttempt,
correct_count: updateCorrectCount(currentAttempt, questionId, isCorrect),
items: currentAttempt.items.map((item) => item.question_id === questionId
? {
...item,
answer: [...answer] as number[] | string[],
is_correct: isCorrect,
}
: item),
}
const sync = answerQuestion(currentAttempt.id, {
question_id: questionId,
answer,
duration_seconds: durationSeconds,
}).catch(() => undefined).finally(() => {
pendingSyncs.delete(sync)
})
pendingSyncs.add(sync)
return
}
await answerQuestion(attempt.value.id, {
question_id: questionId,
answer,
duration_seconds: durationSeconds,
})
await resume(attempt.value.id)
}
async function submit() {
if (!attempt.value) return
await Promise.allSettled([...pendingSyncs])
const response = await submitAttempt(attempt.value.id)
attempt.value = response.data
}
function setPosition(index = currentIndex.value) {
if (!attempt.value) return
const maxIndex = Math.max(0, attempt.value.items.length - 1)
const nextIndex = Math.min(Math.max(index, 0), maxIndex)
currentIndex.value = nextIndex
positionDirty.value = nextIndex !== lastSavedPosition.value
}
async function savePosition(index = currentIndex.value, force = false) {
if (!attempt.value || attempt.value.status !== 'in_progress') return
setPosition(index)
if (!force && (!positionDirty.value || currentIndex.value === lastSavedPosition.value)) return
await updateAttemptPosition(attempt.value.id, index)
lastSavedPosition.value = currentIndex.value
positionDirty.value = false
}
function savePositionOnUnload() {
if (!attempt.value || attempt.value.status !== 'in_progress') return
if (!positionDirty.value || currentIndex.value === lastSavedPosition.value) return
void updateAttemptPositionKeepalive(attempt.value.id, currentIndex.value)
lastSavedPosition.value = currentIndex.value
positionDirty.value = false
}
function updateCorrectCount(currentAttempt: QuizAttempt, questionId: number, isCorrect: boolean) {
const previousItem = currentAttempt.items.find((item) => item.question_id === questionId)
const previousCorrect = previousItem?.is_correct === true ? 1 : 0
const nextCorrect = isCorrect ? 1 : 0
return Math.max(0, currentAttempt.correct_count - previousCorrect + nextCorrect)
}
function judgeAnswer(question: QuizAttempt['items'][number]['question'], answer: Array<number | string>) {
if (question.type === 'blank') {
const expected = (question.answers ?? []).map((value) => String(value).trim())
const actual = answer.map((value) => String(value).trim())
return expected.length === actual.length && expected.every((value, index) => value === actual[index])
}
const expected = question.options
.filter((option) => option.is_correct)
.map((option) => Number(option.id))
.sort((left, right) => left - right)
const actual = answer
.map((value) => Number(value))
.sort((left, right) => left - right)
return expected.length === actual.length && expected.every((value, index) => value === actual[index])
}
return {
attempt,
currentIndex,
currentItem,
answeredCount,
clear,
start,
resume,
answer,
submit,
setPosition,
savePosition,
savePositionOnUnload,
}
})

61
frontend/src/style.css Normal file
View File

@ -0,0 +1,61 @@
:root {
--qq-ink: #17211b;
--qq-muted: #68736b;
--qq-paper: #f7f8f4;
--qq-line: #dfe5dd;
--qq-moss: #1f6f5b;
--qq-indigo: #4157c7;
--qq-amber: #c98522;
--el-color-primary: #1f6f5b;
font-family: Inter, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
color: var(--qq-ink);
background: var(--qq-paper);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
background:
linear-gradient(90deg, rgba(31, 111, 91, 0.04) 1px, transparent 1px),
linear-gradient(rgba(65, 87, 199, 0.035) 1px, transparent 1px),
var(--qq-paper);
background-size: 28px 28px;
}
#app {
min-height: 100vh;
}
.page-title {
margin: 0;
font-size: 22px;
line-height: 1.2;
font-weight: 750;
letter-spacing: 0;
}
.muted {
color: var(--qq-muted);
}
.el-card {
border-radius: 8px;
}
.el-loading-mask {
background-color: transparent !important;
backdrop-filter: none;
}
.el-loading-parent--relative {
background-color: transparent !important;
}

134
frontend/src/types/api.ts Normal file
View File

@ -0,0 +1,134 @@
export interface ApiResponse<T> {
code: number
message: string
data: T
}
export interface PageMeta {
current_page: number
per_page: number
total: number
last_page: number
}
export interface PageData<T> {
items: T[]
meta: PageMeta
}
export interface User {
id: number
name: string
email: string
role: 'admin' | 'teacher' | 'user'
is_active: boolean
permissions?: Permission[]
}
export interface Permission {
id: number
code: string
name: string
type: 'menu' | 'button'
parent_code?: string
menu_path?: string
sort?: number
}
export interface QuestionBank {
id: number
name: string
description?: string
visibility: 'public' | 'private' | 'assigned'
questions_count?: number
wrong_questions_count?: number
is_active: boolean
}
export interface ImportJob {
id: number
question_bank_id: number
type: string
status: string
total_count: number
success_count: number
skipped_count: number
report?: Array<Record<string, unknown>>
}
export interface QuestionOption {
id: number
content: string
is_correct: boolean
sort: number
}
export interface Question {
id: number
question_bank_id: number
type: 'single' | 'multiple' | 'judge' | 'blank'
content: string
explanation?: string
answers?: string[]
options: QuestionOption[]
is_active: boolean
}
export interface SchoolClass {
id: number
name: string
description?: string
join_code: string
members_count?: number
is_active: boolean
}
export interface Paper {
id: number
title: string
description?: string
question_bank_id?: number
duration_minutes?: number
attempt_limit?: number
questions_count?: number
questions?: Array<Question & { pivot?: { score?: string | number; sort?: number } }>
is_active: boolean
}
export interface TaxonomyItem {
id: number
question_bank_id: number
parent_id?: number
name: string
sort?: number
}
export interface AttemptItem {
id: number
question_id: number
answer?: number[] | string[]
is_correct?: boolean
explanation_viewed: boolean
question: Question
}
export interface QuizAttempt {
id: number
mode: 'memorize' | 'practice' | 'random' | 'paper'
status: 'in_progress' | 'submitted'
total_questions: number
correct_count: number
score: string
current_index: number
expires_at?: string
items: AttemptItem[]
}
export interface WrongQuestion {
id: number
question_id: number
wrong_count: number
consecutive_correct_count: number
last_wrong_at?: string
question: Question
}

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