add report card logic

This commit is contained in:
root
2026-03-10 17:33:03 -04:00
parent c235fd2170
commit a82f7aedbc
16 changed files with 2502 additions and 1998 deletions
@@ -0,0 +1,145 @@
<?php
namespace App\Http\Controllers\Api\Reports;
use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Reports\ReportCards\ReportCardAcknowledgementRequest;
use App\Http\Requests\Reports\ReportCards\ReportCardCompletenessRequest;
use App\Http\Requests\Reports\ReportCards\ReportCardMetaRequest;
use App\Http\Requests\Reports\ReportCards\ReportCardPdfRequest;
use App\Http\Resources\Reports\ReportCards\ReportCardAcknowledgementResource;
use App\Http\Resources\Reports\ReportCards\ReportCardClassSectionResource;
use App\Http\Resources\Reports\ReportCards\ReportCardCompletenessStudentResource;
use App\Http\Resources\Reports\ReportCards\ReportCardStudentMetaResource;
use App\Models\Configuration;
use App\Services\Reports\ReportCards\ReportCardService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
class ReportCardsController extends BaseApiController
{
public function __construct(private ReportCardService $service)
{
parent::__construct();
}
public function meta(ReportCardMetaRequest $request): JsonResponse
{
$payload = $request->validated();
$result = $this->service->meta(
$payload['school_year'] ?? null,
$payload['semester'] ?? null
);
return $this->success([
'schoolYears' => $result['schoolYears'] ?? [],
'selectedYear' => $result['selectedYear'] ?? null,
'semesters' => $result['semesters'] ?? [],
'selectedSemester' => $result['selectedSemester'] ?? null,
'students' => ReportCardStudentMetaResource::collection($result['students'] ?? []),
'classSections' => ReportCardClassSectionResource::collection($result['classSections'] ?? []),
]);
}
public function completeness(ReportCardCompletenessRequest $request): JsonResponse
{
$payload = $request->validated();
$schoolYear = $this->resolveSchoolYear($payload['school_year'] ?? null);
$semester = $this->resolveSemester($payload['semester'] ?? null);
$classSectionId = (int) ($payload['class_section_id'] ?? 0);
$result = $this->service->completeness($schoolYear, $semester, $classSectionId);
if (!($result['ok'] ?? false)) {
return $this->error($result['message'] ?? 'Unable to generate completeness report.', Response::HTTP_UNPROCESSABLE_ENTITY);
}
return $this->success([
'summary' => $result['summary'] ?? null,
'students' => ReportCardCompletenessStudentResource::collection($result['students'] ?? []),
'class_section_name' => $result['class_section_name'] ?? null,
'class_section_id' => $result['class_section_id'] ?? null,
'school_year' => $result['school_year'] ?? $schoolYear,
'semester' => $result['semester'] ?? $semester,
'roster_semester' => $result['roster_semester'] ?? null,
'used_fallback' => (bool) ($result['used_fallback'] ?? false),
], $result['message'] ?? 'Success');
}
public function acknowledgement(ReportCardAcknowledgementRequest $request): JsonResponse
{
$payload = $request->validated();
$studentId = (int) ($payload['student_id'] ?? 0);
$schoolYear = $this->resolveSchoolYear($payload['school_year'] ?? null);
$semester = $this->resolveSemester($payload['semester'] ?? null);
$result = $this->service->acknowledgement($studentId, $schoolYear, $semester);
return $this->success(new ReportCardAcknowledgementResource($result));
}
public function studentReport(ReportCardPdfRequest $request, int $studentId)
{
try {
$result = $this->service->generateSingleReport($studentId, $request->validated());
} catch (\Throwable $e) {
Log::error('Report card PDF generation failed: ' . $e->getMessage());
return $this->error('Failed to generate report card.', Response::HTTP_INTERNAL_SERVER_ERROR);
}
if (!($result['ok'] ?? false)) {
return $this->error($result['message'] ?? 'Unable to generate report card.', Response::HTTP_UNPROCESSABLE_ENTITY);
}
$disposition = ($request->boolean('download') ? 'attachment' : 'inline');
return response($result['pdf'], 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => $disposition . '; filename="' . ($result['filename'] ?? 'ReportCard.pdf') . '"',
'Cache-Control' => 'private, max-age=0, must-revalidate',
'Pragma' => 'public',
]);
}
public function classReport(ReportCardPdfRequest $request, int $classSectionId)
{
try {
$result = $this->service->generateClassReport($classSectionId, $request->validated());
} catch (\Throwable $e) {
Log::error('Class report card PDF generation failed: ' . $e->getMessage());
return $this->error('Failed to generate class report cards.', Response::HTTP_INTERNAL_SERVER_ERROR);
}
if (!($result['ok'] ?? false)) {
return $this->error($result['message'] ?? 'Unable to generate class report cards.', Response::HTTP_UNPROCESSABLE_ENTITY);
}
$disposition = ($request->boolean('download') ? 'attachment' : 'inline');
return response($result['pdf'], 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => $disposition . '; filename="' . ($result['filename'] ?? 'ClassReportCards.pdf') . '"',
'Cache-Control' => 'private, max-age=0, must-revalidate',
'Pragma' => 'public',
]);
}
private function resolveSchoolYear(?string $schoolYear): string
{
$value = trim((string) ($schoolYear ?? ''));
if ($value !== '') {
return $value;
}
return trim((string) (Configuration::getConfig('school_year') ?? ''));
}
private function resolveSemester(?string $semester): string
{
$value = trim((string) ($semester ?? ''));
if ($value !== '') {
return $value;
}
return trim((string) (Configuration::getConfig('semester') ?? ''));
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Requests\Reports\ReportCards;
use App\Http\Requests\ApiFormRequest;
class ReportCardAcknowledgementRequest extends ApiFormRequest
{
public function authorize(): bool
{
return auth()->check();
}
public function rules(): array
{
return [
'student_id' => ['required', 'integer', 'min:1'],
'school_year' => ['nullable', 'string', 'max:20'],
'semester' => ['nullable', 'string', 'max:20'],
];
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Requests\Reports\ReportCards;
use App\Http\Requests\ApiFormRequest;
class ReportCardCompletenessRequest extends ApiFormRequest
{
public function authorize(): bool
{
return auth()->check();
}
public function rules(): array
{
return [
'school_year' => ['nullable', 'string', 'max:20'],
'semester' => ['nullable', 'string', 'max:20'],
'class_section_id' => ['required', 'integer', 'min:1'],
];
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Http\Requests\Reports\ReportCards;
use App\Http\Requests\ApiFormRequest;
class ReportCardMetaRequest extends ApiFormRequest
{
public function authorize(): bool
{
return auth()->check();
}
public function rules(): array
{
return [
'school_year' => ['nullable', 'string', 'max:20'],
'semester' => ['nullable', 'string', 'max:20'],
];
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Http\Requests\Reports\ReportCards;
use App\Http\Requests\ApiFormRequest;
class ReportCardPdfRequest extends ApiFormRequest
{
public function authorize(): bool
{
return auth()->check();
}
public function rules(): array
{
return [
'school_year' => ['nullable', 'string', 'max:20'],
'semester' => ['nullable', 'string', 'max:20'],
'report_date' => ['nullable', 'date'],
'download' => ['nullable', 'boolean'],
];
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Resources\Reports\ReportCards;
use Illuminate\Http\Resources\Json\JsonResource;
class ReportCardAcknowledgementResource extends JsonResource
{
public function toArray($request): array
{
return [
'student_id' => (int) ($this['student_id'] ?? 0),
'school_year' => (string) ($this['school_year'] ?? ''),
'semester' => (string) ($this['semester'] ?? ''),
'viewed_at' => $this['viewed_at'] ?? null,
'signed_at' => $this['signed_at'] ?? null,
'signed_name' => $this['signed_name'] ?? null,
];
}
}
@@ -0,0 +1,18 @@
<?php
namespace App\Http\Resources\Reports\ReportCards;
use Illuminate\Http\Resources\Json\JsonResource;
class ReportCardClassSectionResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => (int) ($this['id'] ?? 0),
'class_section_id' => (int) ($this['class_section_id'] ?? ($this['id'] ?? 0)),
'class_section_name' => (string) ($this['class_section_name'] ?? ''),
'school_year' => (string) ($this['school_year'] ?? ''),
];
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Resources\Reports\ReportCards;
use Illuminate\Http\Resources\Json\JsonResource;
class ReportCardCompletenessStudentResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => (int) ($this['id'] ?? 0),
'name' => (string) ($this['name'] ?? ''),
'missing' => array_values($this['missing'] ?? []),
'warnings' => array_values($this['warnings'] ?? []),
'complete' => (bool) ($this['complete'] ?? false),
'viewed_at' => $this['viewed_at'] ?? null,
'signed_at' => $this['signed_at'] ?? null,
'signed_name' => $this['signed_name'] ?? null,
];
}
}
@@ -0,0 +1,18 @@
<?php
namespace App\Http\Resources\Reports\ReportCards;
use Illuminate\Http\Resources\Json\JsonResource;
class ReportCardStudentMetaResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => (int) ($this['id'] ?? 0),
'firstname' => (string) ($this['firstname'] ?? ''),
'lastname' => (string) ($this['lastname'] ?? ''),
'class_section_name' => (string) ($this['class_section_name'] ?? ''),
];
}
}
File diff suppressed because it is too large Load Diff
-120
View File
@@ -1,120 +0,0 @@
<?php
namespace App\Controllers\View;
use App\Controllers\BaseController;
use App\Models\AttendanceRecordModel;
use App\Models\BadgePrintLogModel;
use App\Models\ClassSectionModel;
use App\Models\ConfigurationModel;
use App\Models\ScoreCommentModel;
use App\Models\SemesterScoreModel;
use App\Models\StaffModel;
use App\Models\StudentClassModel;
use App\Models\StudentModel;
use App\Models\TeacherClassModel;
use App\Models\UserModel;
require_once APPPATH . 'ThirdParty/fpdf/fpdf.php';
class PrintablesBaseController extends BaseController
{
protected $userModel;
protected $studentModel;
protected $db;
protected $classSectionModel;
protected $configModel;
protected $schoolYear;
protected $semester;
protected $staffModel;
protected $teacherClassModel;
protected $semesterScoreModel;
protected $studentClassModel;
protected $stickerWidth;
protected $stickerHeight;
protected $pageW;
protected $pageH;
protected $marginL;
protected $marginT;
protected $gapX;
protected $gapY;
protected $badgePrintLogModel;
protected $scoreCommentModel;
protected $attendanceRecordModel;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->userModel = new UserModel();
$this->studentModel = new StudentModel();
$this->classSectionModel = new ClassSectionModel();
$this->configModel = new ConfigurationModel();
$this->semesterScoreModel = new SemesterScoreModel();
$this->studentClassModel = new StudentClassModel();
$this->teacherClassModel = new TeacherClassModel();
$this->staffModel = new StaffModel();
$this->badgePrintLogModel = new BadgePrintLogModel();
$this->scoreCommentModel = new ScoreCommentModel();
$this->attendanceRecordModel = new AttendanceRecordModel();
$this->schoolYear = $this->configModel->getConfig('school_year');
$this->semester = $this->configModel->getConfig('semester');
$this->stickerWidth = $this->configModel->getConfig('stickerWidth');
$this->stickerHeight = $this->configModel->getConfig('stickerHeight');
$this->pageW = $this->configModel->getConfig('pageWidth');
$this->pageH = $this->configModel->getConfig('pageHeight');
$this->marginL = $this->configModel->getConfig('leftMargin');
$this->marginT = $this->configModel->getConfig('topMargin');
$this->gapX = $this->configModel->getConfig('horizontalGap');
$this->gapY = $this->configModel->getConfig('verticalGap');
}
protected function firstExisting(array $paths)
{
foreach ($paths as $p) {
if (is_string($p) && file_exists($p)) {
return $p;
}
}
return null;
}
protected function resolveClassName($db, $classId)
{
$tables = [
['classSection', 'class_section_id'],
['classSection', 'id'],
['class_sections', 'class_section_id'],
['class_sections', 'id'],
];
foreach ($tables as [$table, $pk]) {
$result = $db->table($table)
->select('class_section_name')
->where($pk, $classId)
->get()
->getRowArray();
if ($result) {
return $result['class_section_name'] ?? null;
}
}
return null;
}
protected function fetchStudentsByClass(int $sectionId, ?string $schoolYear)
{
$b = $this->studentClassModel
->select('s.id, s.firstname, s.lastname, s.registration_grade, s.gender')
->join('students s', 's.id = student_class.student_id', 'inner')
->where('student_class.class_section_id', $sectionId)
->orderBy('s.lastname', 'ASC');
if (!empty($schoolYear)) {
$b->where('student_class.school_year', $schoolYear);
}
return $b->findAll();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,46 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
App\Support\SqliteCompat::statement(<<<'SQL'
CREATE TABLE `report_card_acknowledgements` (
`id` int UNSIGNED NOT NULL,
`parent_id` int DEFAULT NULL,
`student_id` int NOT NULL,
`school_year` varchar(20) NOT NULL,
`semester` varchar(20) NOT NULL,
`viewed_at` datetime DEFAULT NULL,
`signed_at` datetime DEFAULT NULL,
`signed_name` varchar(255) DEFAULT NULL,
`signer_ip` varchar(45) DEFAULT NULL,
`created_at` datetime DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
SQL
);
App\Support\SqliteCompat::statement(<<<'SQL'
ALTER TABLE `report_card_acknowledgements`
ADD PRIMARY KEY (`id`),
ADD KEY `idx_report_card_ack_student` (`student_id`),
ADD KEY `idx_report_card_ack_school_term` (`school_year`, `semester`);
SQL
);
App\Support\SqliteCompat::statement(<<<'SQL'
ALTER TABLE `report_card_acknowledgements`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
SQL
);
}
public function down(): void
{
Schema::dropIfExists('report_card_acknowledgements');
}
};
+10
View File
@@ -39,6 +39,7 @@ use App\Http\Controllers\Api\Settings\EventController;
use App\Http\Controllers\Api\Family\FamilyAdminController;
use App\Http\Controllers\Api\Family\FamilyController;
use App\Http\Controllers\Api\Reports\FilesController;
use App\Http\Controllers\Api\Reports\ReportCardsController;
use App\Http\Controllers\Api\Reports\StickersController;
use App\Http\Controllers\Api\Scores\FinalController;
use App\Http\Controllers\Api\Finance\FinancialController;
@@ -439,6 +440,15 @@ Route::prefix('v1')->group(function () {
Route::get('students', [StickersController::class, 'studentsByClass']);
Route::post('print', [StickersController::class, 'print']);
});
Route::prefix('reports/report-cards')->group(function () {
Route::get('meta', [ReportCardsController::class, 'meta']);
Route::get('completeness', [ReportCardsController::class, 'completeness']);
Route::get('acknowledgement', [ReportCardsController::class, 'acknowledgement']);
Route::get('students/{studentId}', [ReportCardsController::class, 'studentReport']);
Route::post('students/{studentId}', [ReportCardsController::class, 'studentReport']);
Route::get('classes/{classSectionId}', [ReportCardsController::class, 'classReport']);
Route::post('classes/{classSectionId}', [ReportCardsController::class, 'classReport']);
});
Route::prefix('subjects/curriculum')->group(function () {
Route::get('/', [SubjectCurriculumApiController::class, 'index']);
@@ -0,0 +1,298 @@
<?php
namespace Tests\Feature\Api\V1\Reports;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
class ReportCardsControllerTest extends TestCase
{
use RefreshDatabase;
public function test_meta_returns_expected_payload(): void
{
$this->seedConfig();
$user = $this->seedUser();
$this->seedReportCardData($user->id);
Sanctum::actingAs($user);
$response = $this->getJson('/api/v1/reports/report-cards/meta?school_year=2025-2026&semester=Fall');
$response->assertOk();
$response->assertJsonPath('status', true);
$this->assertNotEmpty($response->json('data.schoolYears'));
$this->assertNotEmpty($response->json('data.students'));
$this->assertArrayHasKey('id', $response->json('data.students.0'));
$this->assertNotEmpty($response->json('data.classSections'));
$this->assertArrayHasKey('class_section_id', $response->json('data.classSections.0'));
}
public function test_completeness_returns_summary_and_students(): void
{
$this->seedConfig();
$user = $this->seedUser();
$data = $this->seedReportCardData($user->id);
Sanctum::actingAs($user);
$response = $this->getJson('/api/v1/reports/report-cards/completeness?class_section_id=' . $data['class_section_id'] . '&school_year=2025-2026&semester=Fall');
$response->assertOk();
$response->assertJsonPath('status', true);
$this->assertSame(1, $response->json('data.summary.total'));
$this->assertArrayHasKey('missing', $response->json('data.students.0'));
}
public function test_acknowledgement_returns_record(): void
{
$this->seedConfig();
$user = $this->seedUser();
$data = $this->seedReportCardData($user->id);
$this->seedAcknowledgement($data['student_id']);
Sanctum::actingAs($user);
$response = $this->getJson('/api/v1/reports/report-cards/acknowledgement?student_id=' . $data['student_id'] . '&school_year=2025-2026&semester=Fall');
$response->assertOk();
$response->assertJsonPath('status', true);
$response->assertJsonPath('data.signed_name', 'Parent One');
}
public function test_student_report_returns_pdf(): void
{
$this->seedConfig();
$user = $this->seedUser();
$data = $this->seedReportCardData($user->id);
Sanctum::actingAs($user);
$response = $this->getJson('/api/v1/reports/report-cards/students/' . $data['student_id'] . '?school_year=2025-2026&semester=Fall');
$response->assertOk();
$this->assertSame('application/pdf', $response->headers->get('content-type'));
}
public function test_class_report_returns_pdf(): void
{
$this->seedConfig();
$user = $this->seedUser();
$data = $this->seedReportCardData($user->id);
Sanctum::actingAs($user);
$response = $this->getJson('/api/v1/reports/report-cards/classes/' . $data['class_section_id'] . '?school_year=2025-2026&semester=Fall');
$response->assertOk();
$this->assertSame('application/pdf', $response->headers->get('content-type'));
}
public function test_student_report_returns_error_when_missing_scores(): void
{
$this->seedConfig();
$user = $this->seedUser();
$data = $this->seedStudentOnly();
Sanctum::actingAs($user);
$response = $this->getJson('/api/v1/reports/report-cards/students/' . $data['student_id'] . '?school_year=2025-2026&semester=Fall');
$response->assertStatus(422);
$response->assertJsonPath('status', false);
}
public function test_completeness_requires_class_section_id(): void
{
$this->seedConfig();
$user = $this->seedUser();
Sanctum::actingAs($user);
$response = $this->getJson('/api/v1/reports/report-cards/completeness?school_year=2025-2026');
$response->assertStatus(422);
$response->assertJsonPath('message', 'Validation failed.');
}
public function test_acknowledgement_requires_student_id(): void
{
$this->seedConfig();
$user = $this->seedUser();
Sanctum::actingAs($user);
$response = $this->getJson('/api/v1/reports/report-cards/acknowledgement?school_year=2025-2026&semester=Fall');
$response->assertStatus(422);
$response->assertJsonPath('message', 'Validation failed.');
}
public function test_requires_authentication(): void
{
$response = $this->getJson('/api/v1/reports/report-cards/meta');
$response->assertStatus(401);
}
private function seedConfig(): void
{
DB::table('configuration')->insert([
['config_key' => 'school_year', 'config_value' => '2025-2026'],
['config_key' => 'semester', 'config_value' => 'Fall'],
]);
}
private function seedUser(): User
{
$userId = DB::table('users')->insertGetId([
'firstname' => 'Admin',
'lastname' => 'User',
'cellphone' => '9999999999',
'email' => 'reportcards@example.com',
'address_street' => '123 Street',
'city' => 'City',
'state' => 'ST',
'zip' => '12345',
'accept_school_policy' => 1,
'password' => bcrypt('password'),
'user_type' => 'primary',
'semester' => 'Fall',
'school_year' => '2025-2026',
'status' => 'Active',
]);
return User::query()->findOrFail($userId);
}
private function seedReportCardData(int $userId): array
{
DB::table('classes')->insert([
'id' => 1,
'class_name' => 'Grade 1',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('classSection')->insert([
'class_section_id' => 200,
'class_section_name' => 'Grade 1',
'class_id' => 1,
'semester' => 'Fall',
'school_year' => '2025-2026',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('students')->insert([
'id' => 100,
'school_id' => 'SCH1',
'firstname' => 'Student',
'lastname' => 'One',
'age' => 10,
'gender' => 'Male',
'photo_consent' => 1,
'parent_id' => 10,
'year_of_registration' => '2025-2026',
'semester' => 'Fall',
'school_year' => '2025-2026',
'is_active' => 1,
]);
DB::table('student_class')->insert([
'student_id' => 100,
'class_section_id' => 200,
'school_year' => '2025-2026',
'semester' => 'Fall',
'is_event_only' => 0,
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('semester_scores')->insert([
'student_id' => 100,
'school_id' => 'SCH1',
'class_section_id' => 200,
'updated_by' => $userId,
'homework_avg' => 90,
'quiz_avg' => 88,
'project_avg' => 92,
'test_avg' => 89,
'midterm_exam_score' => 91,
'final_exam_score' => 93,
'attendance_score' => 95,
'ptap_score' => 90,
'semester_score' => 91,
'semester' => 'Fall',
'school_year' => '2025-2026',
'created_at' => now(),
'updated_at' => now(),
]);
return [
'student_id' => 100,
'class_section_id' => 200,
];
}
private function seedStudentOnly(): array
{
DB::table('classes')->insert([
'id' => 2,
'class_name' => 'Grade 2',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('classSection')->insert([
'class_section_id' => 201,
'class_section_name' => 'Grade 2',
'class_id' => 2,
'semester' => 'Fall',
'school_year' => '2025-2026',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('students')->insert([
'id' => 101,
'school_id' => 'SCH2',
'firstname' => 'Student',
'lastname' => 'Two',
'age' => 11,
'gender' => 'Female',
'photo_consent' => 1,
'parent_id' => 11,
'year_of_registration' => '2025-2026',
'semester' => 'Fall',
'school_year' => '2025-2026',
'is_active' => 1,
]);
DB::table('student_class')->insert([
'student_id' => 101,
'class_section_id' => 201,
'school_year' => '2025-2026',
'semester' => 'Fall',
'is_event_only' => 0,
'created_at' => now(),
'updated_at' => now(),
]);
return [
'student_id' => 101,
'class_section_id' => 201,
];
}
private function seedAcknowledgement(int $studentId): void
{
DB::table('report_card_acknowledgements')->insert([
'parent_id' => 10,
'student_id' => $studentId,
'school_year' => '2025-2026',
'semester' => 'Fall',
'viewed_at' => now(),
'signed_at' => now(),
'signed_name' => 'Parent One',
'signer_ip' => '127.0.0.1',
'created_at' => now(),
'updated_at' => now(),
]);
}
}
@@ -0,0 +1,222 @@
<?php
namespace Tests\Unit\Services\Reports\ReportCards;
use App\Services\Reports\ReportCards\ReportCardService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class ReportCardServiceTest extends TestCase
{
use RefreshDatabase;
public function test_meta_returns_data_sets(): void
{
$this->seedConfig();
$this->seedReportCardData();
$service = new ReportCardService();
$result = $service->meta('2025-2026', 'Fall');
$this->assertNotEmpty($result['schoolYears']);
$this->assertSame('2025-2026', $result['selectedYear']);
$this->assertNotEmpty($result['students']);
$this->assertNotEmpty($result['classSections']);
}
public function test_completeness_returns_summary(): void
{
$this->seedConfig();
$data = $this->seedReportCardData();
$service = new ReportCardService();
$result = $service->completeness('2025-2026', 'Fall', $data['class_section_id']);
$this->assertTrue($result['ok']);
$this->assertSame(1, $result['summary']['total']);
$this->assertCount(1, $result['students']);
}
public function test_acknowledgement_returns_signed_data(): void
{
$this->seedConfig();
$data = $this->seedReportCardData();
$this->seedAcknowledgement($data['student_id']);
$service = new ReportCardService();
$result = $service->acknowledgement($data['student_id'], '2025-2026', 'Fall');
$this->assertSame('Parent One', $result['signed_name']);
}
public function test_generate_single_report_returns_pdf(): void
{
$this->seedConfig();
$data = $this->seedReportCardData();
$service = new ReportCardService();
$result = $service->generateSingleReport($data['student_id'], [
'school_year' => '2025-2026',
'semester' => 'Fall',
]);
$this->assertTrue($result['ok']);
$this->assertNotEmpty($result['pdf']);
$this->assertStringContainsString('ReportCard_', $result['filename']);
}
public function test_generate_single_report_handles_missing_scores(): void
{
$this->seedConfig();
$studentId = $this->seedStudentOnly();
$service = new ReportCardService();
$result = $service->generateSingleReport($studentId, [
'school_year' => '2025-2026',
'semester' => 'Fall',
]);
$this->assertFalse($result['ok']);
}
private function seedConfig(): void
{
DB::table('configuration')->insert([
['config_key' => 'school_year', 'config_value' => '2025-2026'],
['config_key' => 'semester', 'config_value' => 'Fall'],
]);
}
private function seedReportCardData(): array
{
DB::table('classes')->insert([
'id' => 1,
'class_name' => 'Grade 1',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('classSection')->insert([
'class_section_id' => 200,
'class_section_name' => 'Grade 1',
'class_id' => 1,
'semester' => 'Fall',
'school_year' => '2025-2026',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('students')->insert([
'id' => 100,
'school_id' => 'SCH1',
'firstname' => 'Student',
'lastname' => 'One',
'age' => 10,
'gender' => 'Male',
'photo_consent' => 1,
'parent_id' => 10,
'year_of_registration' => '2025-2026',
'semester' => 'Fall',
'school_year' => '2025-2026',
'is_active' => 1,
]);
DB::table('student_class')->insert([
'student_id' => 100,
'class_section_id' => 200,
'school_year' => '2025-2026',
'semester' => 'Fall',
'is_event_only' => 0,
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('semester_scores')->insert([
'student_id' => 100,
'school_id' => 'SCH1',
'class_section_id' => 200,
'homework_avg' => 90,
'quiz_avg' => 88,
'project_avg' => 92,
'test_avg' => 89,
'midterm_exam_score' => 91,
'final_exam_score' => 93,
'attendance_score' => 95,
'ptap_score' => 90,
'semester_score' => 91,
'semester' => 'Fall',
'school_year' => '2025-2026',
'created_at' => now(),
'updated_at' => now(),
]);
return [
'student_id' => 100,
'class_section_id' => 200,
];
}
private function seedStudentOnly(): int
{
DB::table('classes')->insert([
'id' => 2,
'class_name' => 'Grade 2',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('classSection')->insert([
'class_section_id' => 201,
'class_section_name' => 'Grade 2',
'class_id' => 2,
'semester' => 'Fall',
'school_year' => '2025-2026',
'created_at' => now(),
'updated_at' => now(),
]);
DB::table('students')->insert([
'id' => 101,
'school_id' => 'SCH2',
'firstname' => 'Student',
'lastname' => 'Two',
'age' => 11,
'gender' => 'Female',
'photo_consent' => 1,
'parent_id' => 11,
'year_of_registration' => '2025-2026',
'semester' => 'Fall',
'school_year' => '2025-2026',
'is_active' => 1,
]);
DB::table('student_class')->insert([
'student_id' => 101,
'class_section_id' => 201,
'school_year' => '2025-2026',
'semester' => 'Fall',
'is_event_only' => 0,
'created_at' => now(),
'updated_at' => now(),
]);
return 101;
}
private function seedAcknowledgement(int $studentId): void
{
DB::table('report_card_acknowledgements')->insert([
'parent_id' => 10,
'student_id' => $studentId,
'school_year' => '2025-2026',
'semester' => 'Fall',
'viewed_at' => now(),
'signed_at' => now(),
'signed_name' => 'Parent One',
'signer_ip' => '127.0.0.1',
'created_at' => now(),
'updated_at' => now(),
]);
}
}