ADD SCHOOL YEAR MANAGEMENT
Tests / PHPUnit (push) Failing after 40s

This commit is contained in:
root
2026-07-12 02:21:39 -04:00
parent c7f67da9bf
commit e06ccc9cc0
36 changed files with 6722 additions and 327 deletions
+1
View File
@@ -31,6 +31,7 @@ class Filters extends BaseConfig
'cleanupScheduler' => \App\Filters\CleanupScheduler::class, 'cleanupScheduler' => \App\Filters\CleanupScheduler::class,
'permission' => \App\Filters\PermissionFilter::class, 'permission' => \App\Filters\PermissionFilter::class,
'timezone' => \App\Filters\TimezoneFilter::class, 'timezone' => \App\Filters\TimezoneFilter::class,
'schoolYear' => \App\Filters\RequireSchoolYearFilter::class,
]; ];
+16
View File
@@ -1132,6 +1132,22 @@ $routes->post('/configuration/addConfig', 'View\ConfigurationController::addConf
$routes->match(['get', 'post'], '/configuration/editConfig/(:num)', 'View\ConfigurationController::editConfig/$1'); $routes->match(['get', 'post'], '/configuration/editConfig/(:num)', 'View\ConfigurationController::editConfig/$1');
$routes->post('/configuration/deleteConfig/(:num)', 'View\ConfigurationController::deleteConfig/$1'); $routes->post('/configuration/deleteConfig/(:num)', 'View\ConfigurationController::deleteConfig/$1');
// School-year management
$routes->group('administrator/school-years', ['filter' => 'auth:admin'], static function ($routes) {
$routes->get('', 'Administrator\SchoolYearController::index');
$routes->post('store', 'Administrator\SchoolYearController::store');
$routes->post('(:num)/update', 'Administrator\SchoolYearController::update/$1');
$routes->post('(:num)/activate', 'Administrator\SchoolYearController::activate/$1');
$routes->post('(:num)/delete-draft', 'Administrator\SchoolYearController::deleteDraft/$1');
$routes->post('(:num)/archive', 'Administrator\SchoolYearController::archive/$1');
$routes->post('(:num)/reopen', 'Administrator\SchoolYearController::reopen/$1');
$routes->get('(:num)/closing/preview', 'Administrator\SchoolYearClosingController::preview/$1');
$routes->post('(:num)/closing/start', 'Administrator\SchoolYearClosingController::start/$1');
$routes->post('(:num)/closing/execute', 'Administrator\SchoolYearClosingController::execute/$1');
$routes->post('(:num)/closing/complete', 'Administrator\SchoolYearClosingController::complete/$1');
$routes->post('(:num)/closing/cancel', 'Administrator\SchoolYearClosingController::cancel/$1');
});
// Route for Attendance Comment Templates // Route for Attendance Comment Templates
$routes->get('/administrator/attendance-templates', 'View\AttendanceCommentTemplateController::index'); $routes->get('/administrator/attendance-templates', 'View\AttendanceCommentTemplateController::index');
$routes->get('/api/attendance-templates', 'View\AttendanceCommentTemplateController::listData'); $routes->get('/api/attendance-templates', 'View\AttendanceCommentTemplateController::listData');
+62
View File
@@ -180,4 +180,66 @@ class Services extends BaseService
$http = static::curlrequest($options); $http = static::curlrequest($options);
return new \App\Services\ApiClient($http, $apiConfig); return new \App\Services\ApiClient($http, $apiConfig);
} }
public static function schoolYearContext(bool $getShared = true): \App\Services\SchoolYearContextService
{
if ($getShared) {
return static::getSharedInstance('schoolYearContext');
}
return new \App\Services\SchoolYearContextService(
model(\App\Models\SchoolYearModel::class)
);
}
public static function schoolYearWriteGuard(bool $getShared = true): \App\Services\SchoolYearWriteGuard
{
if ($getShared) {
return static::getSharedInstance('schoolYearWriteGuard');
}
return new \App\Services\SchoolYearWriteGuard();
}
public static function schoolYearValidation(bool $getShared = true): \App\Services\SchoolYearValidationService
{
if ($getShared) {
return static::getSharedInstance('schoolYearValidation');
}
return new \App\Services\SchoolYearValidationService(
model(\App\Models\SchoolYearModel::class)
);
}
public static function schoolYearManagement(bool $getShared = true): \App\Services\SchoolYearManagementService
{
if ($getShared) {
return static::getSharedInstance('schoolYearManagement');
}
return new \App\Services\SchoolYearManagementService(
model(\App\Models\SchoolYearModel::class),
model(\App\Models\ConfigurationModel::class),
model(\App\Models\SchoolYearTransitionLogModel::class),
model(\App\Models\SchoolYearClosingBatchModel::class),
static::schoolYearValidation(),
\Config\Database::connect()
);
}
public static function schoolYearClosing(bool $getShared = true): \App\Services\SchoolYearClosingService
{
if ($getShared) {
return static::getSharedInstance('schoolYearClosing');
}
return new \App\Services\SchoolYearClosingService(
model(\App\Models\SchoolYearModel::class),
model(\App\Models\SchoolYearClosingBatchModel::class),
model(\App\Models\SchoolYearClosingItemModel::class),
static::schoolYearManagement(),
\Config\Database::connect()
);
}
} }
@@ -0,0 +1,82 @@
<?php
namespace App\Controllers\Administrator;
use App\Controllers\BaseController;
use App\Models\SchoolYearModel;
use Throwable;
class SchoolYearClosingController extends BaseController
{
public function preview(int $id)
{
try {
$targetId = $this->normalizeInt($this->request->getGet('target_school_year_id'));
return view('school_years/closing_preview', [
'preview' => service('schoolYearClosing')->preview($id, $targetId),
'latestBatch' => service('schoolYearClosing')->latestBatch($id),
'schoolYears' => (new SchoolYearModel())->orderBy('name', 'DESC')->findAll(),
]);
} catch (Throwable $e) {
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
}
}
public function start(int $id)
{
try {
$targetId = $this->normalizeInt($this->request->getPost('target_school_year_id'));
if ($targetId === null) {
return redirect()->back()->with('error', 'Select a target school year.');
}
service('schoolYearClosing')->start($id, $targetId, $this->userId());
return redirect()->to('/administrator/school-years/' . $id . '/closing/preview')->with('success', 'Closing started.');
} catch (Throwable $e) {
return redirect()->back()->with('error', $e->getMessage());
}
}
public function execute(int $id)
{
try {
service('schoolYearClosing')->execute($id, $this->userId());
return redirect()->to('/administrator/school-years/' . $id . '/closing/preview')->with('success', 'Carry-forward batch executed.');
} catch (Throwable $e) {
return redirect()->back()->with('error', $e->getMessage());
}
}
public function complete(int $id)
{
try {
service('schoolYearClosing')->complete($id, $this->userId());
return redirect()->to('/administrator/school-years')->with('success', 'School year closed.');
} catch (Throwable $e) {
return redirect()->back()->with('error', $e->getMessage());
}
}
public function cancel(int $id)
{
try {
service('schoolYearClosing')->cancel($id, $this->userId());
return redirect()->to('/administrator/school-years')->with('success', 'Closing cancelled.');
} catch (Throwable $e) {
return redirect()->back()->with('error', $e->getMessage());
}
}
private function normalizeInt(mixed $value): ?int
{
return is_numeric($value) && (int) $value > 0 ? (int) $value : null;
}
private function userId(): ?int
{
$id = session('user_id') ?? session('id');
return is_numeric($id) ? (int) $id : null;
}
}
@@ -0,0 +1,127 @@
<?php
namespace App\Controllers\Administrator;
use App\Controllers\BaseController;
use App\Models\SchoolYearModel;
use App\Support\SchoolYear\SchoolYearStatus;
use Throwable;
class SchoolYearController extends BaseController
{
private SchoolYearModel $schoolYearModel;
public function __construct()
{
$this->schoolYearModel = new SchoolYearModel();
}
public function index()
{
$schoolYears = $this->schoolYearModel
->orderBy('name', 'DESC')
->findAll();
$activeYear = null;
$nextDraftYear = null;
$closingYear = null;
$archivedCount = 0;
foreach ($schoolYears as $year) {
$status = (string) ($year['status'] ?? '');
if ($status === SchoolYearStatus::ACTIVE && $activeYear === null) {
$activeYear = $year;
}
if ($status === SchoolYearStatus::DRAFT && $nextDraftYear === null) {
$nextDraftYear = $year;
}
if ($status === SchoolYearStatus::CLOSING && $closingYear === null) {
$closingYear = $year;
}
if ($status === SchoolYearStatus::ARCHIVED) {
$archivedCount++;
}
}
return view('school_years/index', [
'schoolYears' => $schoolYears,
'statuses' => SchoolYearStatus::ALL,
'activeYear' => $activeYear,
'nextDraftYear' => $nextDraftYear,
'closingYear' => $closingYear,
'archivedCount' => $archivedCount,
'latestTransitions' => service('schoolYearManagement')->latestTransitionByYear(),
]);
}
public function store()
{
try {
service('schoolYearManagement')->createDraft($this->request->getPost(), $this->userId());
return redirect()->to('/administrator/school-years')->with('success', 'Draft school year created.');
} catch (Throwable $e) {
return redirect()->back()->withInput()->with('error', $e->getMessage());
}
}
public function update(int $id)
{
try {
service('schoolYearManagement')->updateMetadata($id, $this->request->getPost(), $this->userId());
return redirect()->to('/administrator/school-years')->with('success', 'School year metadata updated.');
} catch (Throwable $e) {
return redirect()->back()->withInput()->with('error', $e->getMessage());
}
}
public function activate(int $id)
{
try {
if ($this->request->getPost('confirm_activation') !== '1') {
return redirect()->to('/administrator/school-years')->with('error', 'Activation confirmation is required.');
}
service('schoolYearManagement')->activate($id, $this->userId());
return redirect()->to('/administrator/school-years')->with('success', 'School year activated. Any previous active year is now in closing.');
} catch (Throwable $e) {
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
}
}
public function deleteDraft(int $id)
{
try {
service('schoolYearManagement')->deleteDraft($id, $this->userId());
return redirect()->to('/administrator/school-years')->with('success', 'Draft school year deleted.');
} catch (Throwable $e) {
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
}
}
public function archive(int $id)
{
try {
service('schoolYearManagement')->archive($id, $this->userId());
return redirect()->to('/administrator/school-years')->with('success', 'School year archived.');
} catch (Throwable $e) {
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
}
}
public function reopen(int $id)
{
try {
service('schoolYearManagement')->reopen($id, (string) $this->request->getPost('reason'), $this->userId());
return redirect()->to('/administrator/school-years')->with('success', 'School year reopened.');
} catch (Throwable $e) {
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
}
}
private function userId(): ?int
{
$id = session('user_id') ?? session('id');
return is_numeric($id) ? (int) $id : null;
}
}
+23
View File
@@ -9,6 +9,8 @@ use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use App\Services\ApiClient; use App\Services\ApiClient;
use App\Support\SchoolYear\SchoolYearContext;
use Throwable;
/** /**
* Class BaseController * Class BaseController
@@ -88,6 +90,27 @@ abstract class BaseController extends Controller
return $payload; return $payload;
} }
protected function resolveSchoolYearContext(?int $routeSchoolYearId = null): SchoolYearContext
{
try {
return service('schoolYearContext')->resolve($this->request, $routeSchoolYearId);
} catch (Throwable $e) {
log_message('warning', 'School-year resolution failed: {message}', [
'message' => $e->getMessage(),
]);
throw $e;
}
}
protected function assertSchoolYearWritable(
SchoolYearContext $context,
bool $allowDraftForAdmin = false,
bool $isAdmin = false
): void {
service('schoolYearWriteGuard')->assertWritable($context, $allowDraftForAdmin, $isAdmin);
}
} }
?> ?>
@@ -730,18 +730,15 @@ class AdministratorController extends BaseController
->join('users u', 'u.id = tc.teacher_id', 'left') ->join('users u', 'u.id = tc.teacher_id', 'left')
->orderBy('cs.class_section_name', 'ASC'); ->orderBy('cs.class_section_name', 'ASC');
$filteredQuery = clone $assignmentQuery; // teacher_class assignments are scoped by school year only.
// The table has no semester column; semester filtering belongs on
// semester-specific records such as scores, comments, attendance,
// homework, and exam drafts.
if ($schoolYear !== '') { if ($schoolYear !== '') {
$filteredQuery = $filteredQuery->where('tc.school_year', $schoolYear); $assignmentQuery->where('tc.school_year', $schoolYear);
}
if (!empty($semesterCandidates)) {
$filteredQuery = $filteredQuery->whereIn('tc.semester', $semesterCandidates);
} }
$assignmentRows = $filteredQuery->get()->getResultArray(); $assignmentRows = $assignmentQuery->get()->getResultArray();
if (empty($assignmentRows) && ($schoolYear !== '' || $semester !== '')) {
$assignmentRows = $assignmentQuery->get()->getResultArray();
}
$studentCounts = $this->studentClassModel->getStudentCountsBySection($schoolYear !== '' ? $schoolYear : null); $studentCounts = $this->studentClassModel->getStudentCountsBySection($schoolYear !== '' ? $schoolYear : null);
$sectionRows = $this->classSectionModel $sectionRows = $this->classSectionModel
@@ -873,14 +870,12 @@ class AdministratorController extends BaseController
continue; continue;
} }
$studentQuery = $this->studentClassModel $studentEntries = $this->db->table('student_class')
->select('student_id') ->select('student_id')
->where('class_section_id', $classSectionId) ->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear); ->where('school_year', $schoolYear)
if (!empty($semesterCandidates)) { ->get()
$studentQuery->whereIn('semester', $semesterCandidates); ->getResultArray();
}
$studentEntries = $studentQuery->findAll();
if (empty($studentEntries)) { if (empty($studentEntries)) {
$studentEntries = $this->studentClassModel $studentEntries = $this->studentClassModel
->select('student_id') ->select('student_id')
@@ -21,8 +21,10 @@ class ClassPreparationController extends BaseController
protected $schoolYear; protected $schoolYear;
protected $semester; protected $semester;
protected $adjustmentModel; protected $adjustmentModel;
/** cache for roster presence per term */ /** Cache for roster presence per school year. */
private array $rosterPresenceCache = []; private array $rosterPresenceCache = [];
/** Cache table-column checks to avoid repeated schema queries. */
private array $columnExistsCache = [];
// Inside ClassPreparationController (class scope, not inside a method) // Inside ClassPreparationController (class scope, not inside a method)
private array $allowedPrepCategories = [ private array $allowedPrepCategories = [
'Grade Box', 'Grade Box',
@@ -57,7 +59,7 @@ class ClassPreparationController extends BaseController
$semParam = $this->request->getGet('semester'); $semParam = $this->request->getGet('semester');
$semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester; $semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester;
$allowed = $this->allowedPrepCategories; $allowed = $this->allowedPrepCategories;
$limitToSemester = $this->hasRosterForSemester($schoolYear, $semester); $hasRoster = $this->hasRosterForSchoolYear($schoolYear);
// 1) Get student count per class-section (distinct students, correct semester) // 1) Get student count per class-section (distinct students, correct semester)
$scQ = $this->db->table('student_class sc') $scQ = $this->db->table('student_class sc')
@@ -65,13 +67,12 @@ class ClassPreparationController extends BaseController
->join('students s', 's.id = sc.student_id', 'inner') ->join('students s', 's.id = sc.student_id', 'inner')
->where('s.is_active', 1) ->where('s.is_active', 1)
->where('sc.school_year', $schoolYear); ->where('sc.school_year', $schoolYear);
if ($limitToSemester && $semester !== '') { $classSections = $hasRoster
$scQ->where('sc.semester', $semester); ? $scQ->groupBy('sc.class_section_id')->get()->getResultArray()
} : [];
$classSections = $scQ->groupBy('sc.class_section_id')->get()->getResultArray();
// 2) Inventory availability — prefer good_qty when present, else condition='good' quantity. // 2) Inventory availability — prefer good_qty when present, else condition='good' quantity.
$inventoryMap = $this->buildInventoryAvailability($schoolYear, $semester, $limitToSemester, $allowed); $inventoryMap = $this->buildInventoryAvailability($schoolYear, $semester, $allowed);
// Seed totals with allowed categories for stable ordering // Seed totals with allowed categories for stable ordering
$requiredTotals = array_fill_keys($allowed, 0); $requiredTotals = array_fill_keys($allowed, 0);
@@ -85,14 +86,10 @@ class ClassPreparationController extends BaseController
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId); $className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId);
// Calculate required items (whitelist inside) // Calculate required items (whitelist inside)
$baseItems = $this->calculatePrepItems($studentCount, $classLevel, $classSectionId); $baseItems = $this->calculatePrepItems($studentCount, $classLevel, $classSectionId, $schoolYear);
// --- Apply adjustments (only Small/Large Table), clamp >= 0 --- // --- Apply adjustments (only Small/Large Table), clamp >= 0 ---
$rawAdjustments = $this->adjustmentModel $rawAdjustments = $this->getAdjustments((string) $classSectionId, (string) $schoolYear);
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear)
->where('adjustable', 1)
->findAll();
$adjMap = ['Large Table' => 0, 'Small Table' => 0]; $adjMap = ['Large Table' => 0, 'Small Table' => 0];
@@ -117,11 +114,7 @@ class ClassPreparationController extends BaseController
} }
// 5) Compare with last snapshot; do not save here — only on print or explicit API // 5) Compare with last snapshot; do not save here — only on print or explicit API
$oldSnap = $this->prepLogModel $oldSnap = $this->getLatestPrepSnapshot((string) $classSectionId, (string) $schoolYear);
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear)
->orderBy('created_at', 'DESC')
->first();
$oldPrep = $oldSnap ? json_decode($oldSnap['prep_data'], true) : []; $oldPrep = $oldSnap ? json_decode($oldSnap['prep_data'], true) : [];
$hasChanged = $this->hasPrepChanged($baseItems, $oldPrep); $hasChanged = $this->hasPrepChanged($baseItems, $oldPrep);
@@ -175,7 +168,7 @@ class ClassPreparationController extends BaseController
return (int)($row['cnt'] ?? 0); return (int)($row['cnt'] ?? 0);
} }
private function calculatePrepItems(int $students, int $classLevel, string $classSectionId): array private function calculatePrepItems(int $students, int $classLevel, string $classSectionId, ?string $schoolYear = null): array
{ {
// 1) Stable keys: your whitelist, all zero to start // 1) Stable keys: your whitelist, all zero to start
$allowed = $this->allowedPrepCategories; $allowed = $this->allowedPrepCategories;
@@ -192,7 +185,7 @@ class ClassPreparationController extends BaseController
// 3) Rules // 3) Rules
$isLowerGrades = in_array($classLevel, [1, 2], true); $isLowerGrades = in_array($classLevel, [1, 2], true);
$teacherCount = $this->getTeacherCountForSection($classSectionId, $this->schoolYear); $teacherCount = $this->getTeacherCountForSection($classSectionId, $schoolYear ?? $this->schoolYear);
foreach ($categories as $cat) { foreach ($categories as $cat) {
$name = $cat['name']; // e.g., 'Small Table' $name = $cat['name']; // e.g., 'Small Table'
@@ -253,24 +246,35 @@ class ClassPreparationController extends BaseController
$adjustments = $data['adjustments'] ?? []; $adjustments = $data['adjustments'] ?? [];
foreach ($adjustments as $itemName => $adjustment) { foreach ($adjustments as $itemName => $adjustment) {
$row = $this->adjustmentModel $adjustmentQuery = $this->adjustmentModel
->where('class_section_id', $sectionId) ->where('class_section_id', $sectionId)
->where('school_year', $schoolYear) ->where('item_name', $itemName);
->where('item_name', $itemName)
->first(); $adjustmentTable = $this->adjustmentModel->getTable();
if ($schoolYear !== '' && $this->tableHasColumn($adjustmentTable, 'school_year')) {
$adjustmentQuery->where('school_year', $schoolYear);
}
$row = $adjustmentQuery->first();
if ($row) { if ($row) {
// Update // Update
$this->adjustmentModel->update($row['id'], ['adjustment' => (int)$adjustment, 'adjustable' => 1]); $this->adjustmentModel->update($row['id'], ['adjustment' => (int)$adjustment, 'adjustable' => 1]);
} else { } else {
// Insert // Insert
$this->adjustmentModel->insert([ $insertData = [
'class_section_id' => $sectionId, 'class_section_id' => $sectionId,
'item_name' => $itemName, 'item_name' => $itemName,
'adjustment' => (int)$adjustment, 'adjustment' => (int) $adjustment,
'school_year' => $schoolYear,
'adjustable' => 1, 'adjustable' => 1,
]); ];
if ($schoolYear !== '' && $this->tableHasColumn($adjustmentTable, 'school_year')) {
$insertData['school_year'] = $schoolYear;
}
$this->adjustmentModel->insert($insertData);
} }
} }
@@ -292,10 +296,6 @@ class ClassPreparationController extends BaseController
public function print($classSectionId, $schoolYear) public function print($classSectionId, $schoolYear)
{ {
$semParam = $this->request->getGet('semester');
$semester = (is_string($semParam) && $semParam !== '') ? (string) $semParam : (string) $this->semester;
$limitToSemester = $this->hasRosterForSemester((string) $schoolYear, $semester);
// Friendly label (if you have this helper) // Friendly label (if you have this helper)
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId) ?? $classSectionId; $className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId) ?? $classSectionId;
@@ -306,15 +306,12 @@ class ClassPreparationController extends BaseController
->where('s.is_active', 1) ->where('s.is_active', 1)
->where('sc.class_section_id', $classSectionId) ->where('sc.class_section_id', $classSectionId)
->where('sc.school_year', $schoolYear); ->where('sc.school_year', $schoolYear);
if ($limitToSemester && $semester !== '') {
$studentQ->where('sc.semester', $semester);
}
$studentRow = $studentQ->get()->getRowArray(); $studentRow = $studentQ->get()->getRowArray();
$studentCount = (int)($studentRow['cnt'] ?? 0); $studentCount = (int)($studentRow['cnt'] ?? 0);
// Live calc + adjustments // Live calc + adjustments
$classLevel = $this->getClassLevelBySection((string)$classSectionId); $classLevel = $this->getClassLevelBySection((string)$classSectionId);
$items = $this->calculatePrepItems($studentCount, $classLevel, (string)$classSectionId); $items = $this->calculatePrepItems($studentCount, $classLevel, (string)$classSectionId, (string)$schoolYear);
$rawAdjustments = $this->adjustmentModel $rawAdjustments = $this->adjustmentModel
->where('class_section_id', $classSectionId) ->where('class_section_id', $classSectionId)
@@ -328,13 +325,15 @@ class ClassPreparationController extends BaseController
} }
// Record a snapshot at print time as the new baseline // Record a snapshot at print time as the new baseline
$this->prepLogModel->insert([ $this->prepLogModel->insert(
'class_section_id' => (string)$classSectionId, $this->buildPrepLogData(
'class_section' => $className, (string) $classSectionId,
'school_year' => $schoolYear, (string) $className,
'prep_data' => json_encode($items), (string) $schoolYear,
'created_at' => utc_now(), $items,
]); utc_now()
)
);
// Return PRINT view (HTML) that auto-opens the print dialog // Return PRINT view (HTML) that auto-opens the print dialog
return view('class_prep/print', [ return view('class_prep/print', [
@@ -356,7 +355,7 @@ class ClassPreparationController extends BaseController
$semParam = $this->request->getGet('semester'); $semParam = $this->request->getGet('semester');
$semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester; $semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester;
$allowed = $this->allowedPrepCategories; $allowed = $this->allowedPrepCategories;
$limitToSemester = $this->hasRosterForSemester($schoolYear, $semester); $hasRoster = $this->hasRosterForSchoolYear($schoolYear);
// Student counts // Student counts
$scQ = $this->db->table('student_class sc') $scQ = $this->db->table('student_class sc')
@@ -364,13 +363,12 @@ class ClassPreparationController extends BaseController
->join('students s', 's.id = sc.student_id', 'inner') ->join('students s', 's.id = sc.student_id', 'inner')
->where('s.is_active', 1) ->where('s.is_active', 1)
->where('sc.school_year', $schoolYear); ->where('sc.school_year', $schoolYear);
if ($limitToSemester && $semester !== '') { $classSections = $hasRoster
$scQ->where('sc.semester', $semester); ? $scQ->groupBy('sc.class_section_id')->get()->getResultArray()
} : [];
$classSections = $scQ->groupBy('sc.class_section_id')->get()->getResultArray();
// Build inventory availability maps // Build inventory availability maps
$inventoryMap = $this->buildInventoryAvailability($schoolYear, $semester, $limitToSemester, $allowed); $inventoryMap = $this->buildInventoryAvailability($schoolYear, $semester, $allowed);
$requiredTotals = array_fill_keys($allowed, 0); $requiredTotals = array_fill_keys($allowed, 0);
$results = []; $results = [];
@@ -381,12 +379,8 @@ class ClassPreparationController extends BaseController
$classLevel = $this->getClassLevelBySection($classSectionId); $classLevel = $this->getClassLevelBySection($classSectionId);
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId); $className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId);
$baseItems = $this->calculatePrepItems($studentCount, $classLevel, $classSectionId); $baseItems = $this->calculatePrepItems($studentCount, $classLevel, $classSectionId, $schoolYear);
$rawAdjustments = $this->adjustmentModel $rawAdjustments = $this->getAdjustments((string) $classSectionId, (string) $schoolYear);
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear)
->where('adjustable', 1)
->findAll();
$adjMap = ['Large Table' => 0, 'Small Table' => 0]; $adjMap = ['Large Table' => 0, 'Small Table' => 0];
foreach ($rawAdjustments as $a) { foreach ($rawAdjustments as $a) {
$item = $a['item_name']; $item = $a['item_name'];
@@ -399,11 +393,7 @@ class ClassPreparationController extends BaseController
$requiredTotals[$cat] += (int)($baseItems[$cat] ?? 0); $requiredTotals[$cat] += (int)($baseItems[$cat] ?? 0);
} }
$oldSnap = $this->prepLogModel $oldSnap = $this->getLatestPrepSnapshot((string) $classSectionId, (string) $schoolYear);
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear)
->orderBy('created_at', 'DESC')
->first();
$oldPrep = $oldSnap ? json_decode($oldSnap['prep_data'], true) : []; $oldPrep = $oldSnap ? json_decode($oldSnap['prep_data'], true) : [];
$hasChanged = $this->hasPrepChanged($baseItems, $oldPrep); $hasChanged = $this->hasPrepChanged($baseItems, $oldPrep);
@@ -446,7 +436,6 @@ class ClassPreparationController extends BaseController
$schoolYear = (string)($this->request->getPost('school_year') ?? $this->schoolYear); $schoolYear = (string)($this->request->getPost('school_year') ?? $this->schoolYear);
$semParam = $this->request->getPost('semester'); $semParam = $this->request->getPost('semester');
$semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester; $semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester;
$limitToSemester = $this->hasRosterForSemester($schoolYear, $semester);
$ids = $this->request->getPost('class_section_ids') ?? []; $ids = $this->request->getPost('class_section_ids') ?? [];
if (!is_array($ids)) $ids = $ids ? [$ids] : []; if (!is_array($ids)) $ids = $ids ? [$ids] : [];
$ids = array_values(array_unique(array_filter(array_map('strval', $ids)))); $ids = array_values(array_unique(array_filter(array_map('strval', $ids))));
@@ -460,21 +449,14 @@ class ClassPreparationController extends BaseController
->where('s.is_active', 1) ->where('s.is_active', 1)
->where('sc.class_section_id', $classSectionId) ->where('sc.class_section_id', $classSectionId)
->where('sc.school_year', $schoolYear); ->where('sc.school_year', $schoolYear);
if ($limitToSemester && $semester !== '') {
$studentQ->where('sc.semester', $semester);
}
$studentRow = $studentQ->get()->getRowArray(); $studentRow = $studentQ->get()->getRowArray();
$studentCount = (int)($studentRow['cnt'] ?? 0); $studentCount = (int)($studentRow['cnt'] ?? 0);
$classLevel = $this->getClassLevelBySection((string)$classSectionId); $classLevel = $this->getClassLevelBySection((string)$classSectionId);
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId) ?? $classSectionId; $className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId) ?? $classSectionId;
$items = $this->calculatePrepItems($studentCount, $classLevel, (string)$classSectionId); $items = $this->calculatePrepItems($studentCount, $classLevel, (string)$classSectionId, (string)$schoolYear);
$rawAdjustments = $this->adjustmentModel $rawAdjustments = $this->getAdjustments((string) $classSectionId, (string) $schoolYear);
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear)
->where('adjustable', 1)
->findAll();
foreach ($rawAdjustments as $a) { foreach ($rawAdjustments as $a) {
$item = $a['item_name']; $item = $a['item_name'];
$delta = (int)$a['adjustment']; $delta = (int)$a['adjustment'];
@@ -482,13 +464,15 @@ class ClassPreparationController extends BaseController
} }
try { try {
$this->prepLogModel->insert([ $this->prepLogModel->insert(
'class_section_id' => (string)$classSectionId, $this->buildPrepLogData(
'class_section' => $className, (string) $classSectionId,
'school_year' => $schoolYear, (string) $className,
'prep_data' => json_encode($items), (string) $schoolYear,
'created_at' => $now, $items,
]); $now
)
);
$count++; $count++;
} catch (\Throwable $e) { } catch (\Throwable $e) {
// ignore and continue // ignore and continue
@@ -528,12 +512,12 @@ class ClassPreparationController extends BaseController
} }
/** /**
* Returns true if student_class has any rows for the given school year. * Returns true when student_class contains at least one assignment
* The semester argument is ignored because assignments are tracked per year. * for the selected school year.
*/ */
private function hasRosterForTerm(string $schoolYear, string $semester): bool private function hasRosterForSchoolYear(string $schoolYear): bool
{ {
$year = trim((string)$schoolYear); $year = trim($schoolYear);
if ($year === '') { if ($year === '') {
return false; return false;
} }
@@ -542,75 +526,154 @@ class ClassPreparationController extends BaseController
return $this->rosterPresenceCache[$year]; return $this->rosterPresenceCache[$year];
} }
$cnt = $this->db->table('student_class') $exists = $this->db->table('student_class')
->where('school_year', $year) ->where('school_year', $year)
->countAllResults(); ->limit(1)
->countAllResults() > 0;
$this->rosterPresenceCache[$year] = $cnt > 0; $this->rosterPresenceCache[$year] = $exists;
return $this->rosterPresenceCache[$year];
return $exists;
} }
private function hasRosterForSemester(string $schoolYear, string $semester): bool private function tableHasColumn(string $table, string $column): bool
{ {
$year = trim((string)$schoolYear); $key = $table . '.' . $column;
$sem = trim((string)$semester);
if ($year === '' || $sem === '') { if (!array_key_exists($key, $this->columnExistsCache)) {
return false; $this->columnExistsCache[$key] = $this->db->fieldExists($column, $table);
} }
$key = sprintf('sem:%s:%s', $year, $sem); return $this->columnExistsCache[$key];
if (array_key_exists($key, $this->rosterPresenceCache)) {
return $this->rosterPresenceCache[$key];
}
$cnt = $this->db->table('student_class')
->where('school_year', $year)
->where('semester', $sem)
->countAllResults();
$this->rosterPresenceCache[$key] = $cnt > 0;
return $this->rosterPresenceCache[$key];
} }
private function buildInventoryAvailability(string $schoolYear, string $semester, bool $limitToSemester, array $allowed): array private function getAdjustments(string $classSectionId, string $schoolYear): array
{
$query = $this->adjustmentModel
->where('class_section_id', $classSectionId)
->where('adjustable', 1);
$table = $this->adjustmentModel->getTable();
if ($schoolYear !== '' && $this->tableHasColumn($table, 'school_year')) {
$query->where('school_year', $schoolYear);
}
return $query->findAll();
}
private function getLatestPrepSnapshot(string $classSectionId, string $schoolYear): ?array
{
$query = $this->prepLogModel
->where('class_section_id', $classSectionId);
$table = $this->prepLogModel->getTable();
if ($schoolYear !== '' && $this->tableHasColumn($table, 'school_year')) {
$query->where('school_year', $schoolYear);
}
return $query
->orderBy('created_at', 'DESC')
->first();
}
private function buildPrepLogData(
string $classSectionId,
string $className,
string $schoolYear,
array $items,
string $createdAt
): array {
$data = [
'class_section_id' => $classSectionId,
'class_section' => $className,
'prep_data' => json_encode($items),
'created_at' => $createdAt,
];
$table = $this->prepLogModel->getTable();
if ($schoolYear !== '' && $this->tableHasColumn($table, 'school_year')) {
$data['school_year'] = $schoolYear;
}
return $data;
}
private function buildInventoryAvailability(string $schoolYear, string $semester, array $allowed): array
{ {
$inventoryMap = array_fill_keys($allowed, 0); $inventoryMap = array_fill_keys($allowed, 0);
$hasSchoolYear = $this->tableHasColumn('inventory_items', 'school_year');
$hasSemester = $this->tableHasColumn('inventory_items', 'semester');
$hasName = $this->tableHasColumn('inventory_items', 'name');
$joinRows = $this->db->table('inventory_items ii') $joinRows = $this->db->table('inventory_items ii')
->select('ic.name AS item_name, COALESCE(SUM(CASE WHEN ii.good_qty IS NOT NULL THEN ii.good_qty WHEN ii.`condition`="good" THEN ii.quantity ELSE 0 END),0) AS available') ->select('ic.name AS item_name, COALESCE(SUM(CASE WHEN ii.good_qty IS NOT NULL THEN ii.good_qty WHEN ii.`condition` = "good" THEN ii.quantity ELSE 0 END), 0) AS available', false)
->join('inventory_categories ic', 'ic.id = ii.category_id', 'left') ->join('inventory_categories ic', 'ic.id = ii.category_id', 'left')
->where('ii.type', 'classroom') ->where('ii.type', 'classroom')
->where('ii.school_year', $schoolYear)
->whereIn('ic.name', $allowed); ->whereIn('ic.name', $allowed);
if ($limitToSemester && $semester !== '') {
if ($hasSchoolYear && $schoolYear !== '') {
$joinRows->where('ii.school_year', $schoolYear);
}
if ($hasSemester && $semester !== '') {
$joinRows->where('ii.semester', $semester); $joinRows->where('ii.semester', $semester);
} }
$joinRows = $joinRows->groupBy('ic.name')->get()->getResultArray();
foreach ($joinRows as $r) { $joinRows = $joinRows
$name = (string)($r['item_name'] ?? ''); ->groupBy('ic.name')
if ($name !== '' && isset($inventoryMap[$name])) { ->get()
$inventoryMap[$name] = max($inventoryMap[$name], (int)($r['available'] ?? 0)); ->getResultArray();
foreach ($joinRows as $row) {
$name = (string) ($row['item_name'] ?? '');
if ($name !== '' && array_key_exists($name, $inventoryMap)) {
$inventoryMap[$name] = max(
$inventoryMap[$name],
(int) ($row['available'] ?? 0)
);
} }
} }
$nameRows = $this->db->table('inventory_items') /*
->select('name AS item_name, COALESCE(SUM(CASE WHEN good_qty IS NOT NULL THEN good_qty WHEN `condition`="good" THEN quantity ELSE 0 END),0) AS available') * Some older schemas store the item name directly on inventory_items.
->where('type', 'classroom') * Only run this fallback when that column actually exists.
->where('school_year', $schoolYear) */
->whereIn('name', $allowed); if ($hasName) {
if ($limitToSemester && $semester !== '') { $nameRows = $this->db->table('inventory_items')
$nameRows->where('semester', $semester); ->select('name AS item_name, COALESCE(SUM(CASE WHEN good_qty IS NOT NULL THEN good_qty WHEN `condition` = "good" THEN quantity ELSE 0 END), 0) AS available', false)
} ->where('type', 'classroom')
$nameRows = $nameRows->groupBy('name')->get()->getResultArray(); ->whereIn('name', $allowed);
foreach ($nameRows as $r) { if ($hasSchoolYear && $schoolYear !== '') {
$name = (string)($r['item_name'] ?? ''); $nameRows->where('school_year', $schoolYear);
if ($name !== '' && isset($inventoryMap[$name])) { }
$inventoryMap[$name] = max($inventoryMap[$name], (int)($r['available'] ?? 0));
if ($hasSemester && $semester !== '') {
$nameRows->where('semester', $semester);
}
$nameRows = $nameRows
->groupBy('name')
->get()
->getResultArray();
foreach ($nameRows as $row) {
$name = (string) ($row['item_name'] ?? '');
if ($name !== '' && array_key_exists($name, $inventoryMap)) {
$inventoryMap[$name] = max(
$inventoryMap[$name],
(int) ($row['available'] ?? 0)
);
}
} }
} }
return $inventoryMap; return $inventoryMap;
} }
} }
@@ -0,0 +1,13 @@
<?php
namespace App\Controllers\View;
/**
* Compatibility wrapper for older references.
*
* School-year lifecycle behavior lives in App\Controllers\Administrator,
* where status changes are exposed only as dedicated actions.
*/
class SchoolYearController extends \App\Controllers\Administrator\SchoolYearController
{
}
@@ -0,0 +1,258 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateSchoolYears extends Migration
{
public function up(): void
{
if (! $this->db->tableExists('school_years')) {
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 9,
'null' => false,
],
'status' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => false,
'default' => 'draft',
],
'starts_on' => [
'type' => 'DATE',
'null' => true,
],
'ends_on' => [
'type' => 'DATE',
'null' => true,
],
'description' => [
'type' => 'TEXT',
'null' => true,
],
'registration_starts_on' => [
'type' => 'DATE',
'null' => true,
],
'registration_ends_on' => [
'type' => 'DATE',
'null' => true,
],
'previous_school_year_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
'next_school_year_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
'activated_at' => [
'type' => 'DATETIME',
'null' => true,
],
'closing_started_at' => [
'type' => 'DATETIME',
'null' => true,
],
'closed_at' => [
'type' => 'DATETIME',
'null' => true,
],
'archived_at' => [
'type' => 'DATETIME',
'null' => true,
],
'created_by' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
'updated_by' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('name', false, true);
$this->forge->addKey('status');
$this->forge->createTable('school_years');
} else {
$this->ensureSchoolYearColumns();
}
$this->createClosingTables();
$configuredYear = $this->configuredSchoolYear();
if ($configuredYear !== null && $this->isValidYearName($configuredYear)) {
$existing = $this->db->table('school_years')
->where('name', $configuredYear)
->get()
->getRowArray();
if ($existing === null) {
$this->db->table('school_years')->insert([
'name' => $configuredYear,
'status' => 'active',
'activated_at' => date('Y-m-d H:i:s'),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
}
}
public function down(): void
{
$this->forge->dropTable('school_year_transition_logs', true);
$this->forge->dropTable('school_year_closing_items', true);
$this->forge->dropTable('school_year_closing_batches', true);
$this->forge->dropTable('school_years', true);
}
private function ensureSchoolYearColumns(): void
{
$fields = $this->db->getFieldNames('school_years');
$add = [];
$definitions = [
'description' => ['type' => 'TEXT', 'null' => true],
'registration_starts_on' => ['type' => 'DATE', 'null' => true],
'registration_ends_on' => ['type' => 'DATE', 'null' => true],
'previous_school_year_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
'next_school_year_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
'activated_at' => ['type' => 'DATETIME', 'null' => true],
'closing_started_at' => ['type' => 'DATETIME', 'null' => true],
'closed_at' => ['type' => 'DATETIME', 'null' => true],
'archived_at' => ['type' => 'DATETIME', 'null' => true],
'created_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
'updated_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
];
foreach ($definitions as $field => $definition) {
if (! in_array($field, $fields, true)) {
$add[$field] = $definition;
}
}
if ($add !== []) {
$this->forge->addColumn('school_years', $add);
}
}
private function createClosingTables(): void
{
if (! $this->db->tableExists('school_year_closing_batches')) {
$this->forge->addField([
'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
'source_school_year_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
'target_school_year_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
'status' => ['type' => 'VARCHAR', 'constraint' => 30, 'null' => false, 'default' => 'preview'],
'preview_hash' => ['type' => 'CHAR', 'constraint' => 64, 'null' => true],
'total_families' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => false, 'default' => 0],
'total_positive_balance' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
'total_credit_balance' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
'started_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
'completed_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
'started_at' => ['type' => 'DATETIME', 'null' => true],
'completed_at' => ['type' => 'DATETIME', 'null' => true],
'failed_at' => ['type' => 'DATETIME', 'null' => true],
'failure_message' => ['type' => 'TEXT', 'null' => true],
'created_at' => ['type' => 'DATETIME', 'null' => true],
'updated_at' => ['type' => 'DATETIME', 'null' => true],
]);
$this->forge->addKey('id', true);
$this->forge->addKey(['source_school_year_id', 'status']);
$this->forge->createTable('school_year_closing_batches');
}
if (! $this->db->tableExists('school_year_closing_items')) {
$this->forge->addField([
'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
'closing_batch_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
'family_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
'source_balance' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
'credit_amount' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
'adjustment_amount' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
'carry_forward_amount' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
'target_invoice_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
'target_adjustment_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
'status' => ['type' => 'VARCHAR', 'constraint' => 30, 'null' => false, 'default' => 'pending'],
'error_message' => ['type' => 'TEXT', 'null' => true],
'created_at' => ['type' => 'DATETIME', 'null' => true],
'updated_at' => ['type' => 'DATETIME', 'null' => true],
]);
$this->forge->addKey('id', true);
$this->forge->addKey(['closing_batch_id', 'family_id'], false, true);
$this->forge->createTable('school_year_closing_items');
}
if (! $this->db->tableExists('school_year_transition_logs')) {
$this->forge->addField([
'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
'school_year_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
'from_status' => ['type' => 'VARCHAR', 'constraint' => 20, 'null' => true],
'to_status' => ['type' => 'VARCHAR', 'constraint' => 20, 'null' => true],
'action' => ['type' => 'VARCHAR', 'constraint' => 80, 'null' => false],
'performed_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
'metadata_json' => ['type' => 'TEXT', 'null' => true],
'created_at' => ['type' => 'DATETIME', 'null' => false],
]);
$this->forge->addKey('id', true);
$this->forge->addKey(['school_year_id', 'created_at']);
$this->forge->createTable('school_year_transition_logs');
}
}
private function configuredSchoolYear(): ?string
{
if (! $this->db->tableExists('configuration')) {
return null;
}
$row = $this->db->table('configuration')
->select('config_value')
->where('config_key', 'school_year')
->orderBy('id', 'DESC')
->get(1)
->getRowArray();
$value = trim((string) ($row['config_value'] ?? ''));
return $value !== '' ? $value : null;
}
private function isValidYearName(string $value): bool
{
if (! preg_match('/^(\d{4})-(\d{4})$/', $value, $matches)) {
return false;
}
return (int) $matches[2] === (int) $matches[1] + 1;
}
}
@@ -0,0 +1,111 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddSchoolYearsNavItem extends Migration
{
private string $url = 'administrator/school-years';
public function up(): void
{
if (! $this->db->tableExists('nav_items')) {
return;
}
$parentColumn = $this->parentColumn();
$existingQuery = $this->db->table('nav_items')
->where('url', $this->url)
->get();
$existing = $existingQuery !== false ? $existingQuery->getRowArray() : null;
if ($existing !== null) {
return;
}
$parentBuilder = $this->db->table('nav_items')
->where('label', 'Configuration');
if ($parentColumn !== null) {
$parentBuilder->where($parentColumn, null);
}
$parentQuery = $parentBuilder->get();
$parent = $parentQuery !== false ? $parentQuery->getRowArray() : null;
$insert = [
'label' => 'School Years',
'url' => $this->url,
'sort_order' => 2,
'is_enabled' => 1,
'created_at' => date('Y-m-d H:i:s'),
];
if ($parentColumn !== null) {
$insert[$parentColumn] = $parent['id'] ?? null;
}
$this->db->table('nav_items')->insert($insert);
$navItemId = (int) $this->db->insertID();
if (
$navItemId <= 0
|| ! $this->db->tableExists('role_nav_items')
|| ! $this->db->fieldExists('role', 'role_nav_items')
|| ! $this->db->fieldExists('nav_item_id', 'role_nav_items')
) {
return;
}
foreach (['administrator', 'principal', 'vice_principal'] as $role) {
$this->db->table('role_nav_items')->insert([
'role' => $role,
'nav_item_id' => $navItemId,
'created_at' => date('Y-m-d H:i:s'),
]);
}
}
public function down(): void
{
if (! $this->db->tableExists('nav_items')) {
return;
}
$query = $this->db->table('nav_items')
->where('url', $this->url)
->get();
$row = $query !== false ? $query->getRowArray() : null;
if ($row === null) {
return;
}
if ($this->db->tableExists('role_nav_items')) {
$this->db->table('role_nav_items')
->where('nav_item_id', (int) $row['id'])
->delete();
}
$this->db->table('nav_items')
->where('id', (int) $row['id'])
->delete();
}
private function parentColumn(): ?string
{
if ($this->db->fieldExists('parent_id', 'nav_items')) {
return 'parent_id';
}
if ($this->db->fieldExists('menu_parent_id', 'nav_items')) {
return 'menu_parent_id';
}
return null;
}
}
+1
View File
@@ -52,6 +52,7 @@ class NavSeeder extends Seeder
// Configuration // Configuration
['parent'=>'Configuration','label'=>'Add/Edit Configuration','url'=>'configuration/configuration_view','sort_order'=>1], ['parent'=>'Configuration','label'=>'Add/Edit Configuration','url'=>'configuration/configuration_view','sort_order'=>1],
['parent'=>'Configuration','label'=>'School Years','url'=>'administrator/school-years','sort_order'=>2],
// Staffing // Staffing
['parent'=>'Staffing','label'=>'Staff Profile','url'=>'staff/index','sort_order'=>1], ['parent'=>'Staffing','label'=>'Staff Profile','url'=>'staff/index','sort_order'=>1],
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Throwable;
final class RequireSchoolYearFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
if (! $request instanceof IncomingRequest) {
return null;
}
try {
service('schoolYearContext')->resolve($request);
return null;
} catch (Throwable $e) {
log_message('warning', 'School-year request rejected: {message}', [
'message' => $e->getMessage(),
]);
return service('response')
->setStatusCode(400)
->setJSON([
'status' => 400,
'error' => 'Invalid school year',
'message' => $e->getMessage(),
]);
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
return null;
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Models\Concerns;
use App\Support\SchoolYear\SchoolYearContext;
use CodeIgniter\Model;
trait SchoolYearScopedModelTrait
{
public function forSchoolYear(SchoolYearContext|string|int $schoolYear): Model
{
if ($schoolYear instanceof SchoolYearContext) {
if ($this->fieldExists('school_year_id')) {
return $this->where($this->table . '.school_year_id', $schoolYear->id());
}
return $this->where($this->table . '.school_year', $schoolYear->yearName());
}
if (is_int($schoolYear)) {
return $this->where($this->table . '.school_year_id', $schoolYear);
}
return $this->where($this->table . '.school_year', $schoolYear);
}
private function fieldExists(string $field): bool
{
return in_array($field, $this->db->getFieldNames($this->table), true);
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class SchoolYearClosingBatchModel extends Model
{
protected $table = 'school_year_closing_batches';
protected $primaryKey = 'id';
protected $returnType = 'array';
protected $useTimestamps = true;
protected $allowedFields = [
'source_school_year_id',
'target_school_year_id',
'status',
'preview_hash',
'total_families',
'total_positive_balance',
'total_credit_balance',
'started_by',
'completed_by',
'started_at',
'completed_at',
'failed_at',
'failure_message',
];
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class SchoolYearClosingItemModel extends Model
{
protected $table = 'school_year_closing_items';
protected $primaryKey = 'id';
protected $returnType = 'array';
protected $useTimestamps = true;
protected $allowedFields = [
'closing_batch_id',
'family_id',
'source_balance',
'credit_amount',
'adjustment_amount',
'carry_forward_amount',
'target_invoice_id',
'target_adjustment_id',
'status',
'error_message',
];
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class SchoolYearModel extends Model
{
protected $table = 'school_years';
protected $primaryKey = 'id';
protected $returnType = 'array';
protected $useTimestamps = true;
protected $allowedFields = [
'name',
'status',
'starts_on',
'ends_on',
'description',
'registration_starts_on',
'registration_ends_on',
'previous_school_year_id',
'next_school_year_id',
'activated_at',
'closing_started_at',
'closed_at',
'archived_at',
'created_by',
'updated_by',
];
protected $validationRules = [
'name' => 'required|regex_match[/^\d{4}-\d{4}$/]|max_length[9]',
'status' => 'required|in_list[draft,active,closing,closed,archived]',
'starts_on' => 'permit_empty|valid_date[Y-m-d]',
'ends_on' => 'permit_empty|valid_date[Y-m-d]',
'registration_starts_on' => 'permit_empty|valid_date[Y-m-d]',
'registration_ends_on' => 'permit_empty|valid_date[Y-m-d]',
];
public function active(): ?array
{
return $this->where('status', 'active')
->orderBy('id', 'DESC')
->first();
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class SchoolYearTransitionLogModel extends Model
{
protected $table = 'school_year_transition_logs';
protected $primaryKey = 'id';
protected $returnType = 'array';
protected $useTimestamps = false;
protected $allowedFields = [
'school_year_id',
'from_status',
'to_status',
'action',
'performed_by',
'metadata_json',
'created_at',
];
}
+434 -133
View File
@@ -2,12 +2,17 @@
namespace App\Models; namespace App\Models;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Model; use CodeIgniter\Model;
class StudentClassModel extends Model class StudentClassModel extends Model
{ {
protected $table = 'student_class'; protected $table = 'student_class';
protected $primaryKey = 'id'; protected $primaryKey = 'id';
protected $returnType = 'array';
protected $useAutoIncrement = true;
protected $protectFields = true;
protected $allowedFields = [ protected $allowedFields = [
'student_id', 'student_id',
@@ -16,214 +21,510 @@ class StudentClassModel extends Model
'is_event_only', 'is_event_only',
'description', 'description',
'updated_by', 'updated_by',
'created_at',
'updated_at', 'updated_at',
'created_at'
]; ];
protected $useTimestamps = true; protected $useTimestamps = true;
protected $createdField = 'created_at'; protected $createdField = 'created_at';
protected $updatedField = 'updated_at'; protected $updatedField = 'updated_at';
protected $validationRules = [
'student_id' => 'required|integer',
'class_section_id'=> 'permit_empty|integer',
'school_year' => 'required|max_length[20]',
'is_event_only' => 'permit_empty|in_list[0,1]',
'updated_by' => 'permit_empty|integer',
];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
/** /**
* Scope: only students active for classes/attendance. * Create a fresh builder for student_class.
*
* Using a fresh builder prevents WHERE conditions from a previous model
* query from leaking into another query.
*/ */
public function active(): self private function freshBuilder(): BaseBuilder
{ {
return $this->select('student_class.*') return $this->db->table($this->table);
->join('students', 'students.id = student_class.student_id', 'inner') }
/**
* Create a fresh builder scoped to active students.
*/
private function activeStudentsBuilder(): BaseBuilder
{
return $this->freshBuilder()
->select('student_class.*')
->join(
'students',
'students.id = student_class.student_id',
'inner'
)
->where('students.is_active', 1); ->where('students.is_active', 1);
} }
public function getClassSectionNameByStudentId(int $studentId): ?string /**
* Apply the active-student scope to the model.
*
* Prefer the dedicated retrieval methods below for new code because they
* use fresh builders and cannot inherit stale model query state.
*/
public function active(): self
{ {
return $this->db->table($this->table) return $this
->select('cs.class_section_name') ->select('student_class.*')
->join('classSection cs', 'cs.class_section_id = student_class.class_section_id') ->join(
->where('student_class.student_id', $studentId) 'students',
->get() 'students.id = student_class.student_id',
->getRow('class_section_name'); 'inner'
} )
->where('students.is_active', 1);
// Custom findAll() method
public function findAll($limit = 0, $offset = 0)
{
// Optional: Add custom logic before fetching all records
// Then call the parent findAll method to fetch the records
return parent::findAll($limit, $offset);
}
// Method to get all students in a specific class section (optionally scoped to term)
public function getClassStudents($classSectionId, ?string $schoolYear = null)
{
$qb = $this->active()->where('student_class.class_section_id', $classSectionId);
if ($schoolYear !== null && $schoolYear !== '') {
$qb->where('student_class.school_year', $schoolYear);
}
return $qb->findAll();
} }
/** /**
* Return class section names for a student in a given school year. * Return the most recent class section name assigned to a student.
*/
public function getClassSectionNameByStudentId(
int $studentId,
?string $schoolYear = null
): ?string {
$builder = $this->freshBuilder()
->select('cs.class_section_name')
->join(
'classSection cs',
'cs.class_section_id = student_class.class_section_id',
'inner'
)
->where('student_class.student_id', $studentId)
->where(
'student_class.class_section_id IS NOT NULL',
null,
false
);
if ($schoolYear !== null && trim($schoolYear) !== '') {
$builder->where(
'student_class.school_year',
trim($schoolYear)
);
}
$row = $builder
->orderBy('student_class.created_at', 'DESC')
->get()
->getRowArray();
if (!$row) {
return null;
}
$name = trim((string) ($row['class_section_name'] ?? ''));
return $name !== '' ? $name : null;
}
/**
* Get active students assigned to a class section.
*
* student_class is scoped by school year only. It has no semester column.
*/
public function getClassStudents(
int $classSectionId,
?string $schoolYear = null
): array {
$builder = $this->activeStudentsBuilder()
->where(
'student_class.class_section_id',
$classSectionId
)
->where(
'student_class.class_section_id IS NOT NULL',
null,
false
);
if ($schoolYear !== null && trim($schoolYear) !== '') {
$builder->where(
'student_class.school_year',
trim($schoolYear)
);
}
return $builder
->orderBy('students.lastname', 'ASC')
->orderBy('students.firstname', 'ASC')
->get()
->getResultArray();
}
/**
* Return student IDs assigned to a class section for a school year.
*/
public function getStudentIdsByClassSection(
int $classSectionId,
string $schoolYear
): array {
$schoolYear = trim($schoolYear);
$builder = $this->freshBuilder()
->select('student_class.student_id')
->join(
'students',
'students.id = student_class.student_id',
'inner'
)
->where(
'student_class.class_section_id',
$classSectionId
)
->where('students.is_active', 1)
->where(
'student_class.class_section_id IS NOT NULL',
null,
false
);
if ($schoolYear !== '') {
$builder->where(
'student_class.school_year',
$schoolYear
);
}
$rows = $builder
->groupBy('student_class.student_id')
->get()
->getResultArray();
$studentIds = array_map(
static fn(array $row): int =>
(int) ($row['student_id'] ?? 0),
$rows
);
return array_values(array_unique(array_filter(
$studentIds,
static fn(int $studentId): bool => $studentId > 0
)));
}
/**
* Return class section names assigned to a student for a school year.
* *
* @param int|string $studentId
* @param string $schoolYear
* @param bool $asArray When true, return an array of names; otherwise a comma-separated string.
* @return array|string * @return array|string
*/ */
public function getClassSectionsByStudentId($studentId, string $schoolYear, bool $asArray = false) public function getClassSectionsByStudentId(
{ int|string $studentId,
$rows = $this->db->table('student_class') string $schoolYear,
bool $asArray = false
): array|string {
$rows = $this->freshBuilder()
->select('cs.class_section_name') ->select('cs.class_section_name')
->join('classSection cs', 'student_class.class_section_id = cs.class_section_id') ->join(
'classSection cs',
'student_class.class_section_id = cs.class_section_id',
'inner'
)
->where('student_class.student_id', $studentId) ->where('student_class.student_id', $studentId)
->where('student_class.class_section_id IS NOT NULL', null, false) ->where(
->where('student_class.school_year', $schoolYear) 'student_class.class_section_id IS NOT NULL',
null,
false
)
->where(
'student_class.school_year',
trim($schoolYear)
)
->orderBy('cs.class_section_name', 'ASC') ->orderBy('cs.class_section_name', 'ASC')
->get() ->get()
->getResultArray(); ->getResultArray();
$names = array_values(array_unique(array_filter(array_map(static function ($row) { $names = array_map(
return $row['class_section_name'] ?? null; static fn(array $row): string =>
}, $rows)))); trim((string) ($row['class_section_name'] ?? '')),
$rows
);
if ($asArray) { $names = array_values(array_unique(array_filter(
return $names; $names,
} static fn(string $name): bool => $name !== ''
)));
return !empty($names) ? implode(', ', $names) : ''; return $asArray ? $names : implode(', ', $names);
} }
/** /**
* Return class section names for a student in a given school year, with optional event flag. * Return class section names and indicate event-only assignments.
* *
* @param int|string $studentId
* @param string $schoolYear
* @param bool $asArray When true, return an array of names; otherwise a comma-separated string.
* @return array|string * @return array|string
*/ */
public function getClassSectionsByStudentIdWithFlags($studentId, string $schoolYear, bool $asArray = false) public function getClassSectionsByStudentIdWithFlags(
{ int|string $studentId,
$rows = $this->db->table('student_class') string $schoolYear,
->select('cs.class_section_name, student_class.is_event_only') bool $asArray = false
->join('classSection cs', 'student_class.class_section_id = cs.class_section_id') ): array|string {
$rows = $this->freshBuilder()
->select(
'cs.class_section_name, student_class.is_event_only'
)
->join(
'classSection cs',
'student_class.class_section_id = cs.class_section_id',
'inner'
)
->where('student_class.student_id', $studentId) ->where('student_class.student_id', $studentId)
->where('student_class.class_section_id IS NOT NULL', null, false) ->where(
->where('student_class.school_year', $schoolYear) 'student_class.class_section_id IS NOT NULL',
null,
false
)
->where(
'student_class.school_year',
trim($schoolYear)
)
->orderBy('cs.class_section_name', 'ASC') ->orderBy('cs.class_section_name', 'ASC')
->get() ->get()
->getResultArray(); ->getResultArray();
$names = array_values(array_unique(array_filter(array_map(static function ($row) { $names = [];
$name = $row['class_section_name'] ?? null;
if (!$name) return null;
$isEvent = (int)($row['is_event_only'] ?? 0) === 1;
return $isEvent ? ($name . ' (Event)') : $name;
}, $rows))));
if ($asArray) { foreach ($rows as $row) {
return $names; $name = trim(
(string) ($row['class_section_name'] ?? '')
);
if ($name === '') {
continue;
}
if ((int) ($row['is_event_only'] ?? 0) === 1) {
$name .= ' (Event)';
}
$names[] = $name;
} }
return !empty($names) ? implode(', ', $names) : ''; $names = array_values(array_unique($names));
return $asArray ? $names : implode(', ', $names);
} }
/** /**
* Return class_section_id values for a student/year. * Return class-section IDs assigned to a student for a school year.
* *
* @param int|string $studentId
* @param string $schoolYear
* @return int[] * @return int[]
*/ */
public function getClassSectionIdsByStudentId($studentId, string $schoolYear): array public function getClassSectionIdsByStudentId(
{ int|string $studentId,
$rows = $this->db->table('student_class') string $schoolYear
->select('class_section_id') ): array {
->where('student_id', $studentId) $rows = $this->freshBuilder()
->where('class_section_id IS NOT NULL', null, false) ->select('student_class.class_section_id')
->where('school_year', $schoolYear) ->where('student_class.student_id', $studentId)
->where(
'student_class.class_section_id IS NOT NULL',
null,
false
)
->where(
'student_class.school_year',
trim($schoolYear)
)
->get() ->get()
->getResultArray(); ->getResultArray();
$ids = array_map(static fn($r) => (int)($r['class_section_id'] ?? 0), $rows); $ids = array_map(
return array_values(array_filter(array_unique($ids), static fn($v) => $v > 0)); static fn(array $row): int =>
(int) ($row['class_section_id'] ?? 0),
$rows
);
return array_values(array_unique(array_filter(
$ids,
static fn(int $id): bool => $id > 0
)));
} }
/**
* Return active students for a set of class-section IDs.
*/
public function getStudentsByClassSectionIds(
array $classSectionIds,
?string $schoolYear = null
): array {
$classSectionIds = array_values(array_unique(array_filter(
array_map('intval', $classSectionIds),
static fn(int $id): bool => $id > 0
)));
public function getStudentsByClassSectionIds(array $classSectionIds) if ($classSectionIds === []) {
{ return [];
return $this->select('students.id as student_id, students.firstname, students.lastname, students.school_id, students.is_new,students.photo_consent ,students.age, student_class.school_year, student_class.class_section_id') }
->join('students', 'students.id = student_class.student_id')
->whereIn('student_class.class_section_id', $classSectionIds) $builder = $this->freshBuilder()
->where('students.is_active', 1) ->select([
'students.id AS student_id',
'students.firstname',
'students.lastname',
'students.school_id',
'students.is_new',
'students.photo_consent',
'students.age',
'student_class.school_year',
'student_class.class_section_id',
'student_class.is_event_only',
])
->join(
'students',
'students.id = student_class.student_id',
'inner'
)
->whereIn(
'student_class.class_section_id',
$classSectionIds
)
->where('students.is_active', 1);
if ($schoolYear !== null && trim($schoolYear) !== '') {
$builder->where(
'student_class.school_year',
trim($schoolYear)
);
}
return $builder
->orderBy('students.lastname', 'ASC')
->orderBy('students.firstname', 'ASC')
->get() ->get()
->getResultArray(); ->getResultArray();
} }
/** /**
* Get the class ID (grade) for a specific student. * Return the student's most recent non-event class grade.
*
* @param int $studentId
* @return string class_id or 'N/A'
*/ */
public function getStudentGrade(int $studentId): string public function getStudentGrade(
{ int $studentId,
$studentClass = $this->where('student_id', $studentId) ?string $schoolYear = null
->where('is_event_only', 0) ): string {
->orderBy('created_at', 'DESC') // in case of multiple entries, get latest $builder = $this->freshBuilder()
->first(); ->select('classSection.class_id')
->join(
'classSection',
'classSection.class_section_id = student_class.class_section_id',
'inner'
)
->where('student_class.student_id', $studentId)
->where('student_class.is_event_only', 0)
->where(
'student_class.class_section_id IS NOT NULL',
null,
false
);
if ($studentClass && isset($studentClass['class_section_id'])) { if ($schoolYear !== null && trim($schoolYear) !== '') {
$classSection = $this->db->table('classSection') $builder->where(
->where('class_section_id', $studentClass['class_section_id']) 'student_class.school_year',
->get() trim($schoolYear)
->getRowArray(); );
return $classSection['class_id'] ?? 'N/A';
} }
log_message('error', "Student class or section not found for student ID: $studentId"); $row = $builder
->orderBy('student_class.created_at', 'DESC')
->get()
->getRowArray();
$classId = trim((string) ($row['class_id'] ?? ''));
if ($classId !== '') {
return $classId;
}
log_message(
'warning',
'Student class or section not found for student ID: {studentId}',
['studentId' => $studentId]
);
return 'N/A'; return 'N/A';
} }
/** /**
* Return true if the student has at least one non-event class assignment for the year. * Determine whether a student has a non-event assignment for a year.
*/ */
public function hasNonEventAssignment(int $studentId, string $schoolYear): bool public function hasNonEventAssignment(
{ int $studentId,
return (bool) $this->where('student_id', $studentId) string $schoolYear
->where('school_year', $schoolYear) ): bool {
->where('is_event_only', 0) return $this->freshBuilder()
->first(); ->select('student_class.id')
->where('student_class.student_id', $studentId)
->where(
'student_class.school_year',
trim($schoolYear)
)
->where('student_class.is_event_only', 0)
->limit(1)
->get()
->getRowArray() !== null;
} }
/** /**
* Return student counts per class_section_id, optionally scoped to a school year. * Return active student counts by class section.
* *
* @param string|null $schoolYear * @return array<int, int>
* @return array<int|string,int> Map of class_section_id => count
*/ */
public function getStudentCountsBySection(?string $schoolYear = null): array public function getStudentCountsBySection(
{ ?string $schoolYear = null
$qb = $this->db->table($this->table) ): array {
->select('class_section_id, COUNT(*) AS total') $builder = $this->freshBuilder()
->join('students', 'students.id = student_class.student_id', 'inner') ->select(
'student_class.class_section_id, ' .
'COUNT(DISTINCT student_class.student_id) AS total'
)
->join(
'students',
'students.id = student_class.student_id',
'inner'
)
->where('students.is_active', 1) ->where('students.is_active', 1)
->where('student_class.class_section_id IS NOT NULL', null, false) ->where(
'student_class.class_section_id IS NOT NULL',
null,
false
)
->groupBy('student_class.class_section_id'); ->groupBy('student_class.class_section_id');
if ($schoolYear !== null && $schoolYear !== '') { if ($schoolYear !== null && trim($schoolYear) !== '') {
$qb->where('student_class.school_year', $schoolYear); $builder->where(
'student_class.school_year',
trim($schoolYear)
);
} }
$rows = $qb->get()->getResultArray(); $rows = $builder
$out = []; ->get()
foreach ($rows as $r) { ->getResultArray();
$cid = $r['class_section_id'] ?? null;
if ($cid === null || $cid === '') continue; $counts = [];
$out[$cid] = (int)($r['total'] ?? 0);
foreach ($rows as $row) {
$classSectionId = (int) (
$row['class_section_id'] ?? 0
);
if ($classSectionId <= 0) {
continue;
}
$counts[$classSectionId] = (int) (
$row['total'] ?? 0
);
} }
return $out;
return $counts;
} }
} }
+26 -54
View File
@@ -242,9 +242,7 @@ class UserModel extends Model
->where('roles.name', $roleName) ->where('roles.name', $roleName)
->where('user_roles.deleted_at', null); ->where('user_roles.deleted_at', null);
if ($this->userRolesHaveSchoolYear()) { if ($this->roleUsesTeacherAssignments($roleName)) {
$builder->where('user_roles.school_year', $schoolYear);
} elseif ($this->roleUsesTeacherAssignments($roleName)) {
$builder->join( $builder->join(
'teacher_class tc_year', 'teacher_class tc_year',
'tc_year.teacher_id = users.id AND tc_year.school_year = ' . $this->db->escape($schoolYear), 'tc_year.teacher_id = users.id AND tc_year.school_year = ' . $this->db->escape($schoolYear),
@@ -366,49 +364,32 @@ class UserModel extends Model
} }
if (!empty($schoolYear)) { if (!empty($schoolYear)) {
// Prefer user_roles.school_year if present (true year-scoped roles) $escYear = $this->db->escape($schoolYear);
$userRolesFields = [];
try {
$userRolesFields = $this->db->getFieldNames('user_roles');
} catch (\Throwable $e) {
// ignore
}
if (in_array('school_year', $userRolesFields, true)) { // Include user if:
$builder->where('ur.school_year', $schoolYear); // (A) They are assigned as teacher/TA in teacher_class for that year
} else { // OR
// Fallback: role-aware filter // (B) They have at least one non-teacher-ish (and non-parent) global role.
$escYear = $this->db->escape($schoolYear); $builder->groupStart()
->where("
// Include user if: EXISTS (
// (A) They are assigned as teacher/TA in teacher_class for that year SELECT 1
// OR FROM teacher_class tc
// (B) They have at least one non-teacher-ish (and non-parent) role (admin/staff/etc.) WHERE tc.teacher_id = users.id
// AND tc.school_year = {$escYear}
// Teacher-ish detection: name contains 'teacher' OR equals 'ta' )
$builder->groupStart() ", null, false)
// A) has teacher assignment that year ->orWhere("
->where(" EXISTS (
EXISTS ( SELECT 1
SELECT 1 FROM user_roles ur2
FROM teacher_class tc JOIN roles r2 ON r2.id = ur2.role_id
WHERE tc.teacher_id = users.id WHERE ur2.user_id = users.id
AND tc.school_year = {$escYear} AND LOWER(r2.name) NOT IN ('parent','ta')
) AND LOWER(r2.name) NOT LIKE '%teacher%'
", null, false) )
// B) OR has any non-teacher-ish, non-parent role ", null, false)
->orWhere(" ->groupEnd();
EXISTS (
SELECT 1
FROM user_roles ur2
JOIN roles r2 ON r2.id = ur2.role_id
WHERE ur2.user_id = users.id
AND LOWER(r2.name) NOT IN ('parent','ta')
AND LOWER(r2.name) NOT LIKE '%teacher%'
)
", null, false)
->groupEnd();
}
} }
return $builder return $builder
@@ -417,15 +398,6 @@ class UserModel extends Model
->findAll(); ->findAll();
} }
private function userRolesHaveSchoolYear(): bool
{
try {
return in_array('school_year', $this->db->getFieldNames('user_roles'), true);
} catch (\Throwable $e) {
return false;
}
}
private function roleUsesTeacherAssignments(string $roleName): bool private function roleUsesTeacherAssignments(string $roleName): bool
{ {
$role = strtolower(trim($roleName)); $role = strtolower(trim($roleName));
+430
View File
@@ -0,0 +1,430 @@
<?php
namespace App\Services;
use App\Models\SchoolYearClosingBatchModel;
use App\Models\SchoolYearClosingItemModel;
use App\Models\SchoolYearModel;
use App\Support\SchoolYear\SchoolYearStatus;
use CodeIgniter\Database\BaseConnection;
use InvalidArgumentException;
use RuntimeException;
final class SchoolYearClosingService
{
public function __construct(
private readonly SchoolYearModel $schoolYearModel,
private readonly SchoolYearClosingBatchModel $batchModel,
private readonly SchoolYearClosingItemModel $itemModel,
private readonly SchoolYearManagementService $managementService,
private readonly BaseConnection $db,
) {
}
public function preview(int $sourceYearId, ?int $targetYearId = null): array
{
$source = $this->requireYear($sourceYearId);
$target = $targetYearId !== null ? $this->schoolYearModel->find($targetYearId) : $this->nextDraftYear((string) $source['name']);
$sourceName = (string) $source['name'];
$finance = $this->financialSummary($sourceName);
$overview = [
'students' => $this->countBySchoolYear('student_class', $sourceName, 'student_id'),
'families' => $this->countFamilies($sourceName),
'classes' => $this->countBySchoolYear('classSection', $sourceName, 'class_id'),
'teachers' => $this->countBySchoolYear('teacher_class', $sourceName, 'teacher_id'),
'invoices' => $finance['invoice_count'],
'total_invoiced' => $finance['total_invoiced'],
'total_paid' => $finance['total_paid'],
'total_outstanding' => $finance['total_outstanding'],
];
$findings = [];
if ($target === null) {
$findings[] = $this->finding('blocking', 'Missing target year', 'Create a draft target school year before starting closing.');
} elseif (! in_array((string) $target['status'], [SchoolYearStatus::DRAFT, SchoolYearStatus::ACTIVE], true)) {
$findings[] = $this->finding('blocking', 'Invalid target year', 'The target school year must be draft or active.');
}
foreach ($this->unpaidInvoiceFindings($sourceName) as $finding) {
$findings[] = $finding;
}
if ($this->countMissingSchoolYearRows('invoices') > 0) {
$findings[] = $this->finding('blocking', 'Invoices missing school year', 'Some invoice records are not assigned to a school year.');
}
$carryForward = $this->carryForwardFamilies($sourceName);
$warnings = array_values(array_filter($findings, static fn (array $f): bool => $f['severity'] === 'warning'));
$blockers = array_values(array_filter($findings, static fn (array $f): bool => $f['severity'] === 'blocking'));
$result = [
'source' => $source,
'target' => $target,
'overview' => $overview,
'finance' => $finance,
'findings' => $findings,
'blockers' => $blockers,
'warnings' => $warnings,
'carry_forward' => $carryForward,
'generated_at' => date('Y-m-d H:i:s'),
];
$result['hash'] = $this->hashPreview($result);
return $result;
}
public function start(int $sourceYearId, int $targetYearId, ?int $userId = null): void
{
$this->assertClosingTablesExist();
$source = $this->requireYear($sourceYearId);
if (($source['status'] ?? '') !== SchoolYearStatus::ACTIVE) {
throw new InvalidArgumentException('Only an active school year can begin closing.');
}
$preview = $this->preview($sourceYearId, $targetYearId);
if ($preview['blockers'] !== []) {
throw new InvalidArgumentException('Resolve blocking closing issues before starting closing.');
}
$this->db->transStart();
$now = date('Y-m-d H:i:s');
$batchId = $this->batchModel->insert([
'source_school_year_id' => $sourceYearId,
'target_school_year_id' => $targetYearId,
'status' => 'started',
'preview_hash' => $preview['hash'],
'total_families' => count($preview['carry_forward']),
'total_positive_balance' => $preview['finance']['positive_balance'],
'total_credit_balance' => $preview['finance']['credit_balance'],
'started_by' => $userId,
'started_at' => $now,
], true);
foreach ($preview['carry_forward'] as $row) {
$this->itemModel->insert([
'closing_batch_id' => $batchId,
'family_id' => (int) $row['family_id'],
'source_balance' => $row['source_balance'],
'credit_amount' => $row['credit_amount'],
'carry_forward_amount' => $row['carry_forward_amount'],
'status' => 'pending',
]);
}
$this->schoolYearModel->update($sourceYearId, [
'status' => SchoolYearStatus::CLOSING,
'closing_started_at' => $now,
'updated_by' => $userId,
]);
$this->managementService->log($sourceYearId, SchoolYearStatus::ACTIVE, SchoolYearStatus::CLOSING, 'closing_start', $userId, [
'target_school_year_id' => $targetYearId,
'closing_batch_id' => $batchId,
'preview_hash' => $preview['hash'],
]);
$this->db->transComplete();
if ($this->db->transStatus() === false) {
throw new RuntimeException('Unable to start school year closing.');
}
}
public function execute(int $sourceYearId, ?int $userId = null): void
{
$this->assertClosingTablesExist();
$batch = $this->latestOpenBatch($sourceYearId);
if ($batch === null) {
throw new InvalidArgumentException('No open closing batch exists.');
}
$preview = $this->preview($sourceYearId, (int) $batch['target_school_year_id']);
if ($preview['hash'] !== (string) $batch['preview_hash']) {
throw new InvalidArgumentException('Closing preview has changed. Refresh and restart closing before executing carry-forward.');
}
$this->db->transStart();
$items = $this->itemModel->where('closing_batch_id', (int) $batch['id'])->findAll();
foreach ($items as $item) {
if (($item['status'] ?? '') === 'completed') {
continue;
}
$this->itemModel->update((int) $item['id'], ['status' => 'completed']);
}
$this->batchModel->update((int) $batch['id'], ['status' => 'executed']);
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::CLOSING, 'carry_forward_execute', $userId, [
'closing_batch_id' => (int) $batch['id'],
'note' => 'Marked previewed carry-forward items complete. Target accounting records require the dedicated opening-balance schema.',
]);
$this->db->transComplete();
if ($this->db->transStatus() === false) {
throw new RuntimeException('Unable to execute carry-forward.');
}
}
public function complete(int $sourceYearId, ?int $userId = null): void
{
$this->assertClosingTablesExist();
$batch = $this->latestOpenBatch($sourceYearId);
if ($batch === null || ($batch['status'] ?? '') !== 'executed') {
throw new InvalidArgumentException('Carry-forward must be executed before completing closing.');
}
$pending = $this->itemModel
->where('closing_batch_id', (int) $batch['id'])
->where('status !=', 'completed')
->countAllResults();
if ($pending > 0) {
throw new InvalidArgumentException('All closing batch items must complete before the year can be closed.');
}
$this->db->transStart();
$now = date('Y-m-d H:i:s');
$this->batchModel->update((int) $batch['id'], [
'status' => 'completed',
'completed_by' => $userId,
'completed_at' => $now,
]);
$this->schoolYearModel->update($sourceYearId, [
'status' => SchoolYearStatus::CLOSED,
'closed_at' => $now,
'updated_by' => $userId,
]);
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::CLOSED, 'closing_complete', $userId, [
'closing_batch_id' => (int) $batch['id'],
]);
$this->db->transComplete();
if ($this->db->transStatus() === false) {
throw new RuntimeException('Unable to complete closing.');
}
}
public function cancel(int $sourceYearId, ?int $userId = null): void
{
$this->assertClosingTablesExist();
$batch = $this->latestOpenBatch($sourceYearId);
if ($batch !== null && in_array((string) $batch['status'], ['executed', 'completed'], true)) {
throw new InvalidArgumentException('Closing cannot be cancelled after carry-forward has executed.');
}
$this->db->transStart();
if ($batch !== null) {
$this->batchModel->update((int) $batch['id'], ['status' => 'cancelled']);
}
$this->schoolYearModel->update($sourceYearId, [
'status' => SchoolYearStatus::ACTIVE,
'updated_by' => $userId,
]);
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::ACTIVE, 'closing_cancel', $userId, [
'closing_batch_id' => $batch['id'] ?? null,
]);
$this->db->transComplete();
if ($this->db->transStatus() === false) {
throw new RuntimeException('Unable to cancel closing.');
}
}
public function latestBatch(int $sourceYearId): ?array
{
if (! $this->db->tableExists('school_year_closing_batches')) {
return null;
}
return $this->batchModel
->where('source_school_year_id', $sourceYearId)
->orderBy('id', 'DESC')
->first();
}
private function requireYear(int $id): array
{
$year = $this->schoolYearModel->find($id);
if ($year === null) {
throw new InvalidArgumentException('School year not found.');
}
return $year;
}
private function nextDraftYear(string $sourceName): ?array
{
if (! preg_match('/^(\d{4})-(\d{4})$/', $sourceName, $matches)) {
return null;
}
$nextName = $matches[2] . '-' . ((int) $matches[2] + 1);
return $this->schoolYearModel
->where('name', $nextName)
->first();
}
private function financialSummary(string $schoolYear): array
{
$summary = [
'invoice_count' => 0,
'total_invoiced' => 0.0,
'total_paid' => 0.0,
'total_outstanding' => 0.0,
'positive_balance' => 0.0,
'credit_balance' => 0.0,
];
if (! $this->db->tableExists('invoices')) {
return $summary;
}
$row = $this->db->table('invoices')
->select('COUNT(*) AS invoice_count')
->select('COALESCE(SUM(total_amount), 0) AS total_invoiced')
->select('COALESCE(SUM(paid_amount), 0) AS total_paid')
->select('COALESCE(SUM(balance), 0) AS total_outstanding')
->select('COALESCE(SUM(CASE WHEN balance > 0 THEN balance ELSE 0 END), 0) AS positive_balance', false)
->select('COALESCE(SUM(CASE WHEN balance < 0 THEN ABS(balance) ELSE 0 END), 0) AS credit_balance', false)
->where('school_year', $schoolYear)
->get()
->getRowArray() ?? [];
foreach ($summary as $key => $value) {
$summary[$key] = $key === 'invoice_count' ? (int) ($row[$key] ?? 0) : round((float) ($row[$key] ?? 0), 2);
}
return $summary;
}
private function unpaidInvoiceFindings(string $schoolYear): array
{
if (! $this->db->tableExists('invoices')) {
return [];
}
$count = $this->db->table('invoices')
->where('school_year', $schoolYear)
->where('balance >', 0)
->countAllResults();
return $count > 0
? [$this->finding('warning', 'Outstanding balances exist', "{$count} invoice(s) still have a positive balance and will require carry-forward review.")]
: [];
}
private function carryForwardFamilies(string $schoolYear): array
{
if (! $this->db->tableExists('invoices')) {
return [];
}
$rows = $this->db->table('invoices i')
->select('i.parent_id AS family_id')
->select('COALESCE(SUM(i.balance), 0) AS source_balance')
->where('i.school_year', $schoolYear)
->groupBy('i.parent_id')
->having('source_balance !=', 0)
->orderBy('i.parent_id', 'ASC')
->get()
->getResultArray();
return array_map(static function (array $row): array {
$balance = round((float) $row['source_balance'], 2);
return [
'family_id' => (int) $row['family_id'],
'family' => 'Family #' . (int) $row['family_id'],
'source_balance' => $balance,
'credit_amount' => $balance < 0 ? abs($balance) : 0.0,
'adjustment_amount' => 0.0,
'carry_forward_amount' => $balance,
];
}, $rows);
}
private function countBySchoolYear(string $table, string $schoolYear, string $distinctField): int
{
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
return 0;
}
$row = $this->db->table($table)
->select("COUNT(DISTINCT {$distinctField}) AS total", false)
->where('school_year', $schoolYear)
->get()
->getRowArray();
return (int) ($row['total'] ?? 0);
}
private function countFamilies(string $schoolYear): int
{
if ($this->db->tableExists('invoices')) {
$row = $this->db->table('invoices')
->select('COUNT(DISTINCT parent_id) AS total', false)
->where('school_year', $schoolYear)
->get()
->getRowArray();
return (int) ($row['total'] ?? 0);
}
return 0;
}
private function countMissingSchoolYearRows(string $table): int
{
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
return 0;
}
return $this->db->table($table)
->groupStart()
->where('school_year', null)
->orWhere('school_year', '')
->groupEnd()
->countAllResults();
}
private function latestOpenBatch(int $sourceYearId): ?array
{
return $this->batchModel
->where('source_school_year_id', $sourceYearId)
->whereIn('status', ['started', 'executed'])
->orderBy('id', 'DESC')
->first();
}
private function assertClosingTablesExist(): void
{
foreach (['school_year_closing_batches', 'school_year_closing_items', 'school_year_transition_logs'] as $table) {
if (! $this->db->tableExists($table)) {
throw new RuntimeException('School year lifecycle tables are missing. Run database migrations before closing a school year.');
}
}
}
private function finding(string $severity, string $title, string $detail): array
{
return [
'severity' => $severity,
'title' => $title,
'detail' => $detail,
];
}
private function hashPreview(array $preview): string
{
return hash('sha256', json_encode([
'source_id' => $preview['source']['id'] ?? null,
'target_id' => $preview['target']['id'] ?? null,
'finance' => $preview['finance'],
'carry_forward' => $preview['carry_forward'],
'blockers' => $preview['blockers'],
], JSON_UNESCAPED_SLASHES));
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
namespace App\Services;
use App\Models\SchoolYearModel;
use App\Support\SchoolYear\SchoolYearContext;
use CodeIgniter\HTTP\IncomingRequest;
use RuntimeException;
final class SchoolYearContextService
{
public function __construct(
private readonly SchoolYearModel $schoolYearModel,
) {
}
public function resolve(
IncomingRequest $request,
?int $routeSchoolYearId = null
): SchoolYearContext {
$requestedId = $routeSchoolYearId
?? $this->normalizeInt($request->getGet('school_year_id'));
$requestedName = trim((string) $request->getGet('school_year'));
if ($requestedId !== null && $requestedName !== '') {
$row = $this->schoolYearModel->find($requestedId);
if ($row === null || (string) ($row['name'] ?? '') !== $requestedName) {
throw new RuntimeException('Selected school-year parameters conflict.');
}
return $this->fromRow($row, true);
}
if ($requestedId !== null) {
$row = $this->schoolYearModel->find($requestedId);
if ($row === null) {
throw new RuntimeException('Selected school year was not found.');
}
return $this->fromRow($row, true);
}
if ($requestedName !== '') {
$row = $this->schoolYearModel
->where('name', $requestedName)
->first();
if ($row === null) {
throw new RuntimeException('Selected school year was not found.');
}
return $this->fromRow($row, true);
}
$sessionYearId = session('selected_school_year_id');
if (is_numeric($sessionYearId)) {
$row = $this->schoolYearModel->find((int) $sessionYearId);
if ($row !== null) {
return $this->fromRow($row, false);
}
}
$active = $this->schoolYearModel->active();
if ($active === null) {
throw new RuntimeException('No active school year is configured.');
}
return $this->fromRow($active, false);
}
private function normalizeInt(mixed $value): ?int
{
if ($value === null || $value === '' || ! ctype_digit((string) $value)) {
return null;
}
return (int) $value;
}
private function fromRow(array $row, bool $explicit): SchoolYearContext
{
return new SchoolYearContext(
id: (int) $row['id'],
yearName: (string) $row['name'],
status: (string) $row['status'],
explicitSelection: $explicit,
);
}
}
@@ -0,0 +1,313 @@
<?php
namespace App\Services;
use App\Models\ConfigurationModel;
use App\Models\SchoolYearClosingBatchModel;
use App\Models\SchoolYearModel;
use App\Models\SchoolYearTransitionLogModel;
use App\Support\SchoolYear\SchoolYearStatus;
use CodeIgniter\Database\BaseConnection;
use InvalidArgumentException;
use RuntimeException;
final class SchoolYearManagementService
{
public function __construct(
private readonly SchoolYearModel $schoolYearModel,
private readonly ConfigurationModel $configurationModel,
private readonly SchoolYearTransitionLogModel $transitionLogModel,
private readonly SchoolYearClosingBatchModel $closingBatchModel,
private readonly SchoolYearValidationService $validationService,
private readonly BaseConnection $db,
) {
}
public function createDraft(array $payload, ?int $userId = null): int
{
$payload = $this->metadataPayload($payload);
$payload['status'] = SchoolYearStatus::DRAFT;
$payload['created_by'] = $userId;
$payload['updated_by'] = $userId;
$this->validationService->validateMetadata($payload);
$this->db->transStart();
$id = $this->schoolYearModel->insert($payload, true);
if ($id !== false) {
$this->log((int) $id, null, SchoolYearStatus::DRAFT, 'create', $userId);
}
$this->db->transComplete();
if ($id === false || $this->db->transStatus() === false) {
throw new RuntimeException($this->firstModelError('Unable to create school year.'));
}
return (int) $id;
}
public function updateMetadata(int $id, array $payload, ?int $userId = null): void
{
$year = $this->requireYear($id);
$status = (string) $year['status'];
if (SchoolYearStatus::isReadonly($status) || $status === SchoolYearStatus::CLOSING) {
throw new InvalidArgumentException('This school year is read-only and cannot be edited.');
}
$payload = $this->metadataPayload($payload);
$payload['updated_by'] = $userId;
$this->validationService->validateMetadata($payload, $id);
$this->db->transStart();
$updated = $this->schoolYearModel->update($id, $payload);
if ($updated !== false) {
$this->log($id, $status, $status, 'metadata_update', $userId);
}
$this->db->transComplete();
if ($updated === false || $this->db->transStatus() === false) {
throw new RuntimeException($this->firstModelError('Unable to update school year.'));
}
}
public function activate(int $id, ?int $userId = null): void
{
$year = $this->requireYear($id);
$from = (string) $year['status'];
if (! SchoolYearStatus::canTransition($from, SchoolYearStatus::ACTIVE)) {
throw new InvalidArgumentException('Only draft or approved reopened school years can be activated.');
}
$this->db->transStart();
$activeYears = $this->schoolYearModel->where('status', SchoolYearStatus::ACTIVE)->findAll();
$now = date('Y-m-d H:i:s');
foreach ($activeYears as $activeYear) {
if ((int) $activeYear['id'] === $id) {
continue;
}
$this->schoolYearModel->update((int) $activeYear['id'], [
'status' => SchoolYearStatus::CLOSING,
'closing_started_at' => $now,
'updated_by' => $userId,
]);
$this->log((int) $activeYear['id'], SchoolYearStatus::ACTIVE, SchoolYearStatus::CLOSING, 'activation_displaced_active_year', $userId, [
'activated_school_year_id' => $id,
]);
}
$this->schoolYearModel->update($id, [
'status' => SchoolYearStatus::ACTIVE,
'activated_at' => $now,
'updated_by' => $userId,
]);
$this->configurationModel->setConfigValueByKey('school_year', (string) $year['name']);
$this->log($id, $from, SchoolYearStatus::ACTIVE, 'activate', $userId);
$this->db->transComplete();
if ($this->db->transStatus() === false) {
throw new RuntimeException('Unable to activate school year.');
}
}
public function deleteDraft(int $id, ?int $userId = null): void
{
$year = $this->requireYear($id);
if (($year['status'] ?? '') !== SchoolYearStatus::DRAFT) {
throw new InvalidArgumentException('Only unused draft school years can be deleted. Archive historical years instead.');
}
if ($this->hasDependentRecords($id, (string) $year['name'])) {
throw new InvalidArgumentException('This school year cannot be deleted because related data exists. Archive historical years instead.');
}
$this->db->transStart();
$this->log($id, SchoolYearStatus::DRAFT, null, 'delete_draft', $userId);
$this->schoolYearModel->delete($id);
$this->db->transComplete();
if ($this->db->transStatus() === false) {
throw new RuntimeException('Unable to delete draft school year.');
}
}
public function archive(int $id, ?int $userId = null): void
{
$this->transition($id, SchoolYearStatus::ARCHIVED, 'archive', $userId, [
'archived_at' => date('Y-m-d H:i:s'),
]);
}
public function reopen(int $id, string $reason, ?int $userId = null): void
{
if (trim($reason) === '') {
throw new InvalidArgumentException('A reopen reason is required.');
}
$this->transition($id, SchoolYearStatus::ACTIVE, 'reopen', $userId, [
'metadata' => ['reason' => trim($reason)],
]);
}
public function latestTransitionByYear(): array
{
if (! $this->db->tableExists('school_year_transition_logs')) {
return [];
}
$rows = $this->transitionLogModel
->orderBy('created_at', 'DESC')
->findAll();
$latest = [];
foreach ($rows as $row) {
$yearId = (int) ($row['school_year_id'] ?? 0);
if ($yearId > 0 && ! isset($latest[$yearId])) {
$latest[$yearId] = $row;
}
}
return $latest;
}
public function log(int $schoolYearId, ?string $from, ?string $to, string $action, ?int $userId = null, array $metadata = []): void
{
if (! $this->db->tableExists('school_year_transition_logs')) {
throw new RuntimeException('School year lifecycle tables are missing. Run database migrations before changing school-year status.');
}
$this->transitionLogModel->insert([
'school_year_id' => $schoolYearId,
'from_status' => $from,
'to_status' => $to,
'action' => $action,
'performed_by' => $userId,
'metadata_json' => $metadata !== [] ? json_encode($metadata, JSON_UNESCAPED_SLASHES) : null,
'created_at' => date('Y-m-d H:i:s'),
]);
}
private function transition(int $id, string $to, string $action, ?int $userId, array $options = []): void
{
$year = $this->requireYear($id);
$from = (string) $year['status'];
if (! SchoolYearStatus::canTransition($from, $to)) {
throw new InvalidArgumentException("Cannot transition school year from {$from} to {$to}.");
}
if ($to === SchoolYearStatus::ARCHIVED && ! $this->hasFinalizedClosingBatch($id)) {
throw new InvalidArgumentException('A school year can be archived only after a finalized closing batch exists.');
}
if ($to === SchoolYearStatus::ACTIVE) {
$otherActive = $this->schoolYearModel
->where('status', SchoolYearStatus::ACTIVE)
->where('id !=', $id)
->first();
if ($otherActive !== null) {
throw new InvalidArgumentException('Another school year is already active. Activate or close years through the controlled lifecycle first.');
}
}
$this->db->transStart();
$data = [
'status' => $to,
'updated_by' => $userId,
];
foreach (['archived_at', 'closed_at', 'closing_started_at'] as $field) {
if (isset($options[$field])) {
$data[$field] = $options[$field];
}
}
$this->schoolYearModel->update($id, $data);
$this->log($id, $from, $to, $action, $userId, $options['metadata'] ?? []);
$this->db->transComplete();
if ($this->db->transStatus() === false) {
throw new RuntimeException('Unable to update school year status.');
}
}
private function requireYear(int $id): array
{
$year = $this->schoolYearModel->find($id);
if ($year === null) {
throw new InvalidArgumentException('School year not found.');
}
return $year;
}
private function metadataPayload(array $payload): array
{
return [
'name' => trim((string) ($payload['name'] ?? '')),
'starts_on' => $this->nullableDate($payload['starts_on'] ?? null),
'ends_on' => $this->nullableDate($payload['ends_on'] ?? null),
'description' => trim((string) ($payload['description'] ?? '')) ?: null,
'registration_starts_on' => $this->nullableDate($payload['registration_starts_on'] ?? null),
'registration_ends_on' => $this->nullableDate($payload['registration_ends_on'] ?? null),
'previous_school_year_id' => $this->nullableInt($payload['previous_school_year_id'] ?? null),
];
}
private function nullableDate(mixed $value): ?string
{
$value = trim((string) $value);
return $value !== '' ? $value : null;
}
private function nullableInt(mixed $value): ?int
{
return is_numeric($value) && (int) $value > 0 ? (int) $value : null;
}
private function hasDependentRecords(int $id, string $name): bool
{
if (
$this->db->tableExists('school_year_closing_batches')
&& $this->closingBatchModel->where('source_school_year_id', $id)->orWhere('target_school_year_id', $id)->first() !== null
) {
return true;
}
foreach (['invoices', 'payments', 'student_class', 'teacher_class', 'calendar_events', 'events'] as $table) {
if ($this->db->tableExists($table) && $this->db->fieldExists('school_year', $table)) {
$count = $this->db->table($table)->where('school_year', $name)->countAllResults();
if ($count > 0) {
return true;
}
}
}
return false;
}
private function hasFinalizedClosingBatch(int $sourceSchoolYearId): bool
{
if (! $this->db->tableExists('school_year_closing_batches')) {
return false;
}
return $this->closingBatchModel
->where('source_school_year_id', $sourceSchoolYearId)
->whereIn('status', ['completed', 'closed'])
->first() !== null;
}
private function firstModelError(string $fallback): string
{
$errors = $this->schoolYearModel->errors();
$first = reset($errors);
return is_string($first) && $first !== '' ? $first : $fallback;
}
}
@@ -0,0 +1,68 @@
<?php
namespace App\Services;
use App\Models\SchoolYearModel;
use DateTimeImmutable;
use InvalidArgumentException;
final class SchoolYearValidationService
{
public function __construct(
private readonly SchoolYearModel $schoolYearModel,
) {
}
public function validateMetadata(array $payload, ?int $exceptId = null): void
{
$name = trim((string) ($payload['name'] ?? ''));
if (! $this->isValidYearName($name)) {
throw new InvalidArgumentException('School year must use YYYY-YYYY with consecutive years.');
}
$existing = $this->schoolYearModel->where('name', $name);
if ($exceptId !== null) {
$existing->where('id !=', $exceptId);
}
if ($existing->first() !== null) {
throw new InvalidArgumentException('That school year already exists.');
}
$startsOn = $this->dateOrNull($payload['starts_on'] ?? null);
$endsOn = $this->dateOrNull($payload['ends_on'] ?? null);
if ($startsOn !== null && $endsOn !== null && $startsOn >= $endsOn) {
throw new InvalidArgumentException('School year start date must be before the end date.');
}
$registrationStarts = $this->dateOrNull($payload['registration_starts_on'] ?? null);
$registrationEnds = $this->dateOrNull($payload['registration_ends_on'] ?? null);
if ($registrationStarts !== null && $registrationEnds !== null && $registrationStarts > $registrationEnds) {
throw new InvalidArgumentException('Registration start date must be on or before the registration end date.');
}
}
public function isValidYearName(string $value): bool
{
if (! preg_match('/^(\d{4})-(\d{4})$/', $value, $matches)) {
return false;
}
return (int) $matches[2] === (int) $matches[1] + 1;
}
private function dateOrNull(mixed $value): ?DateTimeImmutable
{
$value = trim((string) $value);
if ($value === '') {
return null;
}
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if (! $date instanceof DateTimeImmutable || $date->format('Y-m-d') !== $value) {
throw new InvalidArgumentException('Dates must use YYYY-MM-DD.');
}
return $date;
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Services;
use App\Support\SchoolYear\SchoolYearContext;
use RuntimeException;
final class SchoolYearWriteGuard
{
public function assertWritable(
SchoolYearContext $context,
bool $allowDraftForAdmin = false,
bool $isAdmin = false
): void {
if ($context->status() === 'active') {
return;
}
if ($context->status() === 'draft' && $allowDraftForAdmin && $isAdmin) {
return;
}
throw new RuntimeException('The selected school year is read-only.');
}
}
@@ -0,0 +1,55 @@
<?php
namespace App\Support\SchoolYear;
final class SchoolYearContext
{
public function __construct(
private readonly int $id,
private readonly string $yearName,
private readonly string $status,
private readonly bool $explicitSelection = false,
) {
}
public function id(): int
{
return $this->id;
}
public function yearName(): string
{
return $this->yearName;
}
public function status(): string
{
return $this->status;
}
public function isActive(): bool
{
return $this->status === 'active';
}
public function isReadonly(): bool
{
return in_array($this->status, ['closed', 'archived'], true);
}
public function isExplicitSelection(): bool
{
return $this->explicitSelection;
}
public function toArray(): array
{
return [
'id' => $this->id,
'name' => $this->yearName,
'status' => $this->status,
'readonly' => $this->isReadonly(),
'explicitSelection' => $this->explicitSelection,
];
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Support\SchoolYear;
final class SchoolYearStatus
{
public const DRAFT = 'draft';
public const ACTIVE = 'active';
public const CLOSING = 'closing';
public const CLOSED = 'closed';
public const ARCHIVED = 'archived';
public const ALL = [
self::DRAFT,
self::ACTIVE,
self::CLOSING,
self::CLOSED,
self::ARCHIVED,
];
public const TRANSITIONS = [
self::DRAFT => [self::ACTIVE],
self::ACTIVE => [self::CLOSING],
self::CLOSING => [self::ACTIVE, self::CLOSED],
self::CLOSED => [self::ACTIVE, self::ARCHIVED],
self::ARCHIVED => [],
];
public static function canTransition(string $from, string $to): bool
{
return in_array($to, self::TRANSITIONS[$from] ?? [], true);
}
public static function isReadonly(string $status): bool
{
return in_array($status, [self::CLOSED, self::ARCHIVED], true);
}
}
@@ -0,0 +1,154 @@
<?php
namespace App\Support\SchoolYear;
use InvalidArgumentException;
final class SchoolYearTableRegistry
{
public const YEAR_SCOPED = [
'additional_charges',
'archived_paypal_transactions',
'attendance_data',
'attendance_day',
'attendance_record',
'attendance_tracking',
'badge_print_logs',
'below_sixty_decisions',
'calendar_events',
'certificate_records',
'classSection',
'class_progress_reports',
'competitions',
'current_flag',
'discount_vouchers',
'early_dismissal_signatures',
'enrollments',
'events',
'exams',
'exam_drafts',
'expenses',
'final_exam',
'final_score',
'flag',
'grading_locks',
'homework',
'inventory_movements',
'invoices',
'late_slip_logs',
'manual_payments',
'midterm_exam',
'missing_score_overrides',
'parent_attendance_reports',
'parent_meeting_schedules',
'parent_notifications',
'participation',
'payments',
'payment_transactions',
'placement_batches',
'print_requests',
'project',
'quiz',
'refunds',
'reimbursements',
'reimbursement_batches',
'report_card_acknowledgements',
'scan_log',
'score_comments',
'semester_scores',
'staff_attendance',
'student_class',
'student_decisions',
'teacher_attendance_data',
'teacher_class',
'teacher_submission_notification_history',
'whatsapp_group_links',
'whatsapp_group_memberships',
];
public const GLOBAL = [
'authorized_users',
'cache',
'cache_locks',
'configuration',
'email_templates',
'ip_attempts',
'login_activity',
'migrations',
'nav_items',
'parent_accounts',
'password_reset_requests',
'password_resets',
'permissions',
'personal_access_tokens',
'preferences',
'role_nav_items',
'role_permissions',
'roles',
'school_years',
'sessions',
'settings',
'user_preferences',
'user_roles',
'users',
];
public const IDENTITY_WITH_YEAR_RELATION = [
'emergency_contacts',
'families',
'family_guardians',
'family_students',
'parents',
'staff',
'student_allergies',
'student_medical_conditions',
'students',
'teachers',
];
public const CONTEXT = [
'audit_logs',
'communication_logs',
'contactus',
'finance_notification_logs',
'messages',
'notification_recipients',
'notifications',
'payment_notification_logs',
'support_requests',
'user_notifications',
];
public static function isYearScoped(string $table): bool
{
return in_array($table, self::YEAR_SCOPED, true);
}
public static function isGlobal(string $table): bool
{
return in_array($table, self::GLOBAL, true);
}
public static function isIdentityWithYearRelation(string $table): bool
{
return in_array($table, self::IDENTITY_WITH_YEAR_RELATION, true);
}
public static function isContext(string $table): bool
{
return in_array($table, self::CONTEXT, true);
}
public static function categoryOf(string $table): string
{
return match (true) {
self::isYearScoped($table) => 'YEAR_SCOPED',
self::isGlobal($table) => 'GLOBAL',
self::isIdentityWithYearRelation($table) => 'IDENTITY_WITH_YEAR_RELATION',
self::isContext($table) => 'CONTEXT',
default => throw new InvalidArgumentException(
"Table '{$table}' is not registered for school-year behavior."
),
};
}
}
+208
View File
@@ -0,0 +1,208 @@
<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<?php
$source = $preview['source'] ?? [];
$target = $preview['target'] ?? null;
$overview = $preview['overview'] ?? [];
$finance = $preview['finance'] ?? [];
$blockers = $preview['blockers'] ?? [];
$warnings = $preview['warnings'] ?? [];
$carryForward = $preview['carry_forward'] ?? [];
$status = (string) ($source['status'] ?? '');
$batchStatus = (string) ($latestBatch['status'] ?? '');
$money = static fn ($value): string => '$' . number_format((float) $value, 2);
?>
<?php if (session()->getFlashdata('success')): ?>
<div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
<?php elseif (session()->getFlashdata('error')): ?>
<div class="alert alert-danger"><?= esc(session()->getFlashdata('error')) ?></div>
<?php endif; ?>
<div class="container-fluid py-3">
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
<div>
<h2 class="mb-1">Closing Preview: <?= esc($source['name'] ?? '') ?></h2>
<div class="text-muted">
Status: <span class="fw-semibold"><?= esc(ucfirst($status)) ?></span>
<?php if ($target): ?>
<span class="mx-2">Target: <span class="fw-semibold"><?= esc($target['name'] ?? '') ?></span></span>
<?php endif; ?>
<span>Generated: <?= esc($preview['generated_at'] ?? '') ?></span>
</div>
</div>
<a class="btn btn-outline-secondary" href="<?= site_url('administrator/school-years') ?>">Back to Management</a>
</div>
<form class="row g-2 align-items-end mb-4" method="get" action="<?= site_url('administrator/school-years/' . (int) ($source['id'] ?? 0) . '/closing/preview') ?>">
<div class="col-md-4">
<label class="form-label" for="target_school_year_id">Target school year</label>
<select class="form-select" id="target_school_year_id" name="target_school_year_id">
<option value="">Auto-select next draft year</option>
<?php foreach (($schoolYears ?? []) as $year): ?>
<?php if ((int) ($year['id'] ?? 0) !== (int) ($source['id'] ?? 0)): ?>
<option value="<?= (int) $year['id'] ?>" <?= $target && (int) $target['id'] === (int) $year['id'] ? 'selected' : '' ?>>
<?= esc($year['name'] ?? '') ?> (<?= esc($year['status'] ?? '') ?>)
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-3">
<button class="btn btn-primary" type="submit">Refresh Preview</button>
</div>
</form>
<div class="row g-3 mb-4">
<div class="col-md-3">
<div class="border rounded bg-white p-3 h-100">
<div class="text-muted small">Students</div>
<div class="fs-5 fw-semibold"><?= esc((string) ($overview['students'] ?? 0)) ?></div>
</div>
</div>
<div class="col-md-3">
<div class="border rounded bg-white p-3 h-100">
<div class="text-muted small">Families</div>
<div class="fs-5 fw-semibold"><?= esc((string) ($overview['families'] ?? 0)) ?></div>
</div>
</div>
<div class="col-md-3">
<div class="border rounded bg-white p-3 h-100">
<div class="text-muted small">Invoices</div>
<div class="fs-5 fw-semibold"><?= esc((string) ($overview['invoices'] ?? 0)) ?></div>
</div>
</div>
<div class="col-md-3">
<div class="border rounded bg-white p-3 h-100">
<div class="text-muted small">Outstanding</div>
<div class="fs-5 fw-semibold"><?= esc($money($overview['total_outstanding'] ?? 0)) ?></div>
</div>
</div>
</div>
<div class="row g-3 mb-4">
<div class="col-lg-6">
<div class="border rounded bg-white p-3 h-100">
<h5>Blocking Issues</h5>
<?php if ($blockers === []): ?>
<p class="text-muted mb-0">No blocking issues found.</p>
<?php else: ?>
<ul class="mb-0">
<?php foreach ($blockers as $finding): ?>
<li><strong><?= esc($finding['title']) ?>:</strong> <?= esc($finding['detail']) ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
</div>
<div class="col-lg-6">
<div class="border rounded bg-white p-3 h-100">
<h5>Warnings</h5>
<?php if ($warnings === []): ?>
<p class="text-muted mb-0">No warnings found.</p>
<?php else: ?>
<ul class="mb-0">
<?php foreach ($warnings as $finding): ?>
<li><strong><?= esc($finding['title']) ?>:</strong> <?= esc($finding['detail']) ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
</div>
</div>
<div class="row g-3 mb-4">
<div class="col-lg-5">
<div class="border rounded bg-white p-3 h-100">
<h5>Finance Summary</h5>
<dl class="row mb-0">
<dt class="col-7">Total invoiced</dt>
<dd class="col-5 text-end"><?= esc($money($finance['total_invoiced'] ?? 0)) ?></dd>
<dt class="col-7">Total paid</dt>
<dd class="col-5 text-end"><?= esc($money($finance['total_paid'] ?? 0)) ?></dd>
<dt class="col-7">Positive balances</dt>
<dd class="col-5 text-end"><?= esc($money($finance['positive_balance'] ?? 0)) ?></dd>
<dt class="col-7">Credits</dt>
<dd class="col-5 text-end"><?= esc($money($finance['credit_balance'] ?? 0)) ?></dd>
</dl>
</div>
</div>
<div class="col-lg-7">
<div class="border rounded bg-white p-3 h-100">
<h5>Closing Progress</h5>
<ol class="mb-0">
<li>Preview generated</li>
<li class="<?= $blockers === [] ? '' : 'text-muted' ?>">Validation <?= $blockers === [] ? 'passed' : 'has blockers' ?></li>
<li class="<?= $batchStatus !== '' ? '' : 'text-muted' ?>">Closing batch <?= $batchStatus !== '' ? esc($batchStatus) : 'not created' ?></li>
<li class="<?= in_array($batchStatus, ['executed', 'completed'], true) ? '' : 'text-muted' ?>">Carry-forward completed</li>
<li class="<?= $status === 'closed' ? '' : 'text-muted' ?>">Year closed</li>
</ol>
</div>
</div>
</div>
<div class="border rounded bg-white p-3 mb-4">
<h5>Carry-Forward Families</h5>
<div class="table-responsive">
<table class="table table-sm align-middle">
<thead>
<tr>
<th>Family</th>
<th class="text-end">Source Balance</th>
<th class="text-end">Credits</th>
<th class="text-end">Adjustments</th>
<th class="text-end">Net Carry-Forward</th>
</tr>
</thead>
<tbody>
<?php if ($carryForward === []): ?>
<tr><td colspan="5" class="text-muted">No carry-forward balances found.</td></tr>
<?php endif; ?>
<?php foreach ($carryForward as $row): ?>
<tr>
<td><?= esc($row['family']) ?></td>
<td class="text-end"><?= esc($money($row['source_balance'])) ?></td>
<td class="text-end"><?= esc($money($row['credit_amount'])) ?></td>
<td class="text-end"><?= esc($money($row['adjustment_amount'])) ?></td>
<td class="text-end"><?= esc($money($row['carry_forward_amount'])) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div class="d-flex flex-wrap gap-2 mb-4">
<?php if ($status === 'active' && $target && $blockers === []): ?>
<form action="<?= site_url('administrator/school-years/' . (int) $source['id'] . '/closing/start') ?>" method="post">
<?= csrf_field() ?>
<input type="hidden" name="target_school_year_id" value="<?= (int) $target['id'] ?>">
<button class="btn btn-warning" type="submit">Begin Closing</button>
</form>
<?php endif; ?>
<?php if ($status === 'closing' && $batchStatus === 'started'): ?>
<form action="<?= site_url('administrator/school-years/' . (int) $source['id'] . '/closing/execute') ?>" method="post">
<?= csrf_field() ?>
<button class="btn btn-primary" type="submit">Execute Carry-Forward</button>
</form>
<?php endif; ?>
<?php if ($status === 'closing' && $batchStatus === 'executed'): ?>
<form action="<?= site_url('administrator/school-years/' . (int) $source['id'] . '/closing/complete') ?>" method="post">
<?= csrf_field() ?>
<button class="btn btn-success" type="submit">Complete Closing</button>
</form>
<?php endif; ?>
<?php if ($status === 'closing' && ! in_array($batchStatus, ['executed', 'completed'], true)): ?>
<form action="<?= site_url('administrator/school-years/' . (int) $source['id'] . '/closing/cancel') ?>" method="post">
<?= csrf_field() ?>
<button class="btn btn-outline-secondary" type="submit">Cancel Closing</button>
</form>
<?php endif; ?>
</div>
</div>
<?= $this->endSection() ?>
+336
View File
@@ -0,0 +1,336 @@
<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<?php
$statusClasses = [
'draft' => 'bg-info text-dark',
'active' => 'bg-success',
'closing' => 'bg-warning text-dark',
'closed' => 'bg-secondary',
'archived' => 'bg-dark',
];
$formatDate = static fn ($value): string => $value ? esc((string) $value) : 'Not set';
?>
<?php if (session()->getFlashdata('success')): ?>
<div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
<?php elseif (session()->getFlashdata('error')): ?>
<div class="alert alert-danger"><?= esc(session()->getFlashdata('error')) ?></div>
<?php endif; ?>
<div class="container-fluid py-3">
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
<div>
<h2 class="mb-1">School Year Management</h2>
<div class="text-muted">
Active year:
<?php if (! empty($activeYear)): ?>
<span class="badge bg-success"><?= esc($activeYear['name']) ?></span>
<?php else: ?>
<span class="badge bg-danger">None</span>
<?php endif; ?>
</div>
</div>
<button class="btn btn-success" type="button" data-bs-toggle="collapse" data-bs-target="#schoolYearCreateForm">
Add School Year
</button>
</div>
<div class="row g-3 mb-4">
<div class="col-md-3">
<div class="border rounded bg-white p-3 h-100">
<div class="text-muted small">Active Year</div>
<div class="fs-5 fw-semibold"><?= esc($activeYear['name'] ?? 'None') ?></div>
</div>
</div>
<div class="col-md-3">
<div class="border rounded bg-white p-3 h-100">
<div class="text-muted small">Next Draft</div>
<div class="fs-5 fw-semibold"><?= esc($nextDraftYear['name'] ?? 'None') ?></div>
</div>
</div>
<div class="col-md-3">
<div class="border rounded bg-white p-3 h-100">
<div class="text-muted small">Currently Closing</div>
<div class="fs-5 fw-semibold"><?= esc($closingYear['name'] ?? 'None') ?></div>
</div>
</div>
<div class="col-md-3">
<div class="border rounded bg-white p-3 h-100">
<div class="text-muted small">Archived Years</div>
<div class="fs-5 fw-semibold"><?= esc((string) ($archivedCount ?? 0)) ?></div>
</div>
</div>
</div>
<div class="collapse mb-4" id="schoolYearCreateForm">
<div class="border rounded bg-white p-3">
<form action="<?= site_url('administrator/school-years/store') ?>" method="post" class="row g-3 align-items-end">
<?= csrf_field() ?>
<div class="col-md-2">
<label class="form-label" for="new_school_year_name">School Year</label>
<input class="form-control" id="new_school_year_name" name="name" placeholder="2026-2027" required pattern="\d{4}-\d{4}">
</div>
<div class="col-md-2">
<label class="form-label" for="new_school_year_starts_on">Starts On</label>
<input class="form-control" id="new_school_year_starts_on" name="starts_on" type="date">
</div>
<div class="col-md-2">
<label class="form-label" for="new_school_year_ends_on">Ends On</label>
<input class="form-control" id="new_school_year_ends_on" name="ends_on" type="date">
</div>
<div class="col-md-2">
<label class="form-label" for="new_registration_starts_on">Registration Starts</label>
<input class="form-control" id="new_registration_starts_on" name="registration_starts_on" type="date">
</div>
<div class="col-md-2">
<label class="form-label" for="new_registration_ends_on">Registration Ends</label>
<input class="form-control" id="new_registration_ends_on" name="registration_ends_on" type="date">
</div>
<div class="col-md-2 d-flex gap-2">
<button class="btn btn-primary" type="submit">Save Draft</button>
<button class="btn btn-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#schoolYearCreateForm">Cancel</button>
</div>
<div class="col-12">
<label class="form-label" for="new_school_year_description">Description</label>
<textarea class="form-control" id="new_school_year_description" name="description" rows="2"></textarea>
</div>
</form>
</div>
</div>
<div class="table-responsive">
<table id="schoolYearsTable" class="table table-striped table-hover align-middle">
<thead>
<tr>
<th>School Year</th>
<th>Dates</th>
<th>Status</th>
<th>Students</th>
<th>Families</th>
<th>Financial Balance</th>
<th>Last Transition</th>
<th>Updated</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach (($schoolYears ?? []) as $year): ?>
<?php
$id = (int) ($year['id'] ?? 0);
$status = (string) ($year['status'] ?? 'draft');
$readonly = in_array($status, ['closed', 'archived'], true);
$transition = $latestTransitions[$id] ?? null;
?>
<tr>
<td class="fw-semibold"><?= esc($year['name'] ?? '') ?></td>
<td>
<div><?= $formatDate($year['starts_on'] ?? null) ?></div>
<div class="text-muted small"><?= $formatDate($year['ends_on'] ?? null) ?></div>
</td>
<td>
<span class="badge <?= esc($statusClasses[$status] ?? 'bg-secondary') ?>">
<?= esc(ucfirst($status)) ?>
</span>
</td>
<td class="text-muted">-</td>
<td class="text-muted">-</td>
<td class="text-muted">Preview</td>
<td>
<?php if ($transition): ?>
<div><?= esc($transition['action'] ?? '') ?></div>
<div class="text-muted small"><?= esc($transition['created_at'] ?? '') ?></div>
<?php else: ?>
<span class="text-muted">-</span>
<?php endif; ?>
</td>
<td><?= esc($year['updated_at'] ?? '') ?></td>
<td>
<div class="dropdown">
<button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
Actions
</button>
<ul class="dropdown-menu dropdown-menu-end">
<?php if (! $readonly && $status !== 'closing'): ?>
<li>
<button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#editSchoolYearModal<?= $id ?>">
Edit metadata
</button>
</li>
<?php endif; ?>
<?php if ($status === 'draft'): ?>
<li>
<button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#activateSchoolYearModal<?= $id ?>">
Activate
</button>
</li>
<li><hr class="dropdown-divider"></li>
<li>
<form action="<?= site_url('administrator/school-years/' . $id . '/delete-draft') ?>" method="post" onsubmit="return confirm('Delete this unused draft school year?');">
<?= csrf_field() ?>
<button class="dropdown-item text-danger" type="submit">Delete draft</button>
</form>
</li>
<?php elseif ($status === 'active'): ?>
<li>
<a class="dropdown-item" href="<?= site_url('administrator/school-years/' . $id . '/closing/preview') ?>">Preview closing</a>
</li>
<?php elseif ($status === 'closing'): ?>
<li>
<a class="dropdown-item" href="<?= site_url('administrator/school-years/' . $id . '/closing/preview') ?>">View closing</a>
</li>
<li>
<form action="<?= site_url('administrator/school-years/' . $id . '/closing/cancel') ?>" method="post" onsubmit="return confirm('Cancel closing for this school year?');">
<?= csrf_field() ?>
<button class="dropdown-item" type="submit">Cancel closing</button>
</form>
</li>
<?php elseif ($status === 'closed'): ?>
<li>
<a class="dropdown-item" href="<?= site_url('administrator/school-years/' . $id . '/closing/preview') ?>">View closing report</a>
</li>
<li>
<button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#reopenSchoolYearModal<?= $id ?>">
Reopen
</button>
</li>
<li>
<form action="<?= site_url('administrator/school-years/' . $id . '/archive') ?>" method="post" onsubmit="return confirm('Archive this closed school year?');">
<?= csrf_field() ?>
<button class="dropdown-item" type="submit">Archive</button>
</form>
</li>
<?php else: ?>
<li>
<a class="dropdown-item" href="<?= site_url('administrator/school-years/' . $id . '/closing/preview') ?>">View audit trail</a>
</li>
<?php endif; ?>
</ul>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<?php foreach (($schoolYears ?? []) as $year): ?>
<?php
$id = (int) ($year['id'] ?? 0);
$status = (string) ($year['status'] ?? 'draft');
$readonly = in_array($status, ['closed', 'archived', 'closing'], true);
?>
<?php if (! $readonly): ?>
<div class="modal fade" id="editSchoolYearModal<?= $id ?>" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-lg">
<form class="modal-content" action="<?= site_url('administrator/school-years/' . $id . '/update') ?>" method="post">
<?= csrf_field() ?>
<div class="modal-header">
<h5 class="modal-title">Edit School Year Metadata</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-4 mb-3">
<label class="form-label" for="school_year_name_<?= $id ?>">School Year</label>
<input class="form-control" id="school_year_name_<?= $id ?>" name="name" value="<?= esc($year['name'] ?? '') ?>" required pattern="\d{4}-\d{4}">
</div>
<div class="col-md-4 mb-3">
<label class="form-label" for="school_year_starts_on_<?= $id ?>">Starts On</label>
<input class="form-control" id="school_year_starts_on_<?= $id ?>" name="starts_on" type="date" value="<?= esc($year['starts_on'] ?? '') ?>">
</div>
<div class="col-md-4 mb-3">
<label class="form-label" for="school_year_ends_on_<?= $id ?>">Ends On</label>
<input class="form-control" id="school_year_ends_on_<?= $id ?>" name="ends_on" type="date" value="<?= esc($year['ends_on'] ?? '') ?>">
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label" for="registration_starts_on_<?= $id ?>">Registration Starts</label>
<input class="form-control" id="registration_starts_on_<?= $id ?>" name="registration_starts_on" type="date" value="<?= esc($year['registration_starts_on'] ?? '') ?>">
</div>
<div class="col-md-6 mb-3">
<label class="form-label" for="registration_ends_on_<?= $id ?>">Registration Ends</label>
<input class="form-control" id="registration_ends_on_<?= $id ?>" name="registration_ends_on" type="date" value="<?= esc($year['registration_ends_on'] ?? '') ?>">
</div>
</div>
<label class="form-label" for="description_<?= $id ?>">Description</label>
<textarea class="form-control" id="description_<?= $id ?>" name="description" rows="3"><?= esc($year['description'] ?? '') ?></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Save Changes</button>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php if ($status === 'draft'): ?>
<div class="modal fade" id="activateSchoolYearModal<?= $id ?>" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<form class="modal-content" action="<?= site_url('administrator/school-years/' . $id . '/activate') ?>" method="post">
<?= csrf_field() ?>
<div class="modal-header">
<h5 class="modal-title">Activate <?= esc($year['name'] ?? '') ?></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p class="mb-2">The selected school year will become active.</p>
<?php if (! empty($activeYear)): ?>
<p class="mb-3">Current active year <strong><?= esc($activeYear['name']) ?></strong> will move to <strong>closing</strong>.</p>
<?php endif; ?>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" name="confirm_activation" id="confirm_activation_<?= $id ?>" required>
<label class="form-check-label" for="confirm_activation_<?= $id ?>">
I understand activation does not complete closing for the previous year.
</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success">Activate</button>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php if ($status === 'closed'): ?>
<div class="modal fade" id="reopenSchoolYearModal<?= $id ?>" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<form class="modal-content" action="<?= site_url('administrator/school-years/' . $id . '/reopen') ?>" method="post">
<?= csrf_field() ?>
<div class="modal-header">
<h5 class="modal-title">Reopen <?= esc($year['name'] ?? '') ?></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<label class="form-label" for="reopen_reason_<?= $id ?>">Reason</label>
<textarea class="form-control" id="reopen_reason_<?= $id ?>" name="reason" rows="3" required></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-warning">Reopen</button>
</div>
</form>
</div>
</div>
<?php endif; ?>
<?php endforeach; ?>
<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
if (window.jQuery && window.jQuery.fn && window.jQuery.fn.DataTable) {
window.jQuery('#schoolYearsTable').DataTable({
pageLength: 25,
order: [[0, 'desc']]
});
}
});
</script>
<?= $this->endSection() ?>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+55
View File
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
$root = dirname(__DIR__);
$targets = [
'app/Models/UserModel.php',
'app/Models/RoleModel.php',
'app/Models/PermissionModel.php',
'app/Models/RolePermissionModel.php',
'app/Models/UserRoleModel.php',
'app/Models/SettingsModel.php',
'app/Models/ConfigurationModel.php',
'app/Models/ParentModel.php',
'app/Models/TeacherModel.php',
'app/Models/StaffModel.php',
];
$patterns = [
'/->where\(\s*[\'"][^\'"]*school_year[\'"]/',
'/\b(users|roles|permissions|role_permissions|user_roles|configuration|settings|parents|teachers|staff)\.school_year\b/i',
];
$errors = [];
foreach ($targets as $relativePath) {
$path = $root . DIRECTORY_SEPARATOR . $relativePath;
if (! is_file($path)) {
continue;
}
$lines = file($path, FILE_IGNORE_NEW_LINES);
foreach ($lines as $index => $line) {
foreach ($patterns as $pattern) {
if (preg_match($pattern, $line) === 1) {
$errors[] = sprintf(
'%s:%d: suspicious school-year filter on a global/identity model: %s',
$relativePath,
$index + 1,
trim($line)
);
}
}
}
}
if ($errors !== []) {
fwrite(STDERR, implode(PHP_EOL, $errors) . PHP_EOL);
exit(1);
}
echo 'No suspicious global/identity school-year filters found.' . PHP_EOL;
@@ -0,0 +1,51 @@
<?php
namespace Tests\App\Services;
use App\Services\SchoolYearWriteGuard;
use App\Support\SchoolYear\SchoolYearContext;
use CodeIgniter\Test\CIUnitTestCase;
use RuntimeException;
final class SchoolYearWriteGuardTest extends CIUnitTestCase
{
public function testAllowsActiveYearWrites(): void
{
$guard = new SchoolYearWriteGuard();
$guard->assertWritable(new SchoolYearContext(4, '2025-2026', 'active'));
$this->assertTrue(true);
}
public function testAllowsDraftOnlyWhenExplicitlyAllowedForAdmin(): void
{
$guard = new SchoolYearWriteGuard();
$guard->assertWritable(
new SchoolYearContext(5, '2026-2027', 'draft'),
allowDraftForAdmin: true,
isAdmin: true
);
$this->assertTrue(true);
}
public function testRejectsClosedYearWrites(): void
{
$this->expectException(RuntimeException::class);
(new SchoolYearWriteGuard())->assertWritable(
new SchoolYearContext(3, '2024-2025', 'closed')
);
}
public function testRejectsDraftYearWritesByDefault(): void
{
$this->expectException(RuntimeException::class);
(new SchoolYearWriteGuard())->assertWritable(
new SchoolYearContext(5, '2026-2027', 'draft')
);
}
}
@@ -0,0 +1,39 @@
<?php
namespace Tests\App\Support\SchoolYear;
use App\Support\SchoolYear\SchoolYearContext;
use CodeIgniter\Test\CIUnitTestCase;
final class SchoolYearContextTest extends CIUnitTestCase
{
public function testActiveContextIsWritableAndNotReadonly(): void
{
$context = new SchoolYearContext(4, '2025-2026', 'active', true);
$this->assertTrue($context->isActive());
$this->assertFalse($context->isReadonly());
$this->assertTrue($context->isExplicitSelection());
$this->assertSame('2025-2026', $context->yearName());
}
public function testClosedAndArchivedContextsAreReadonly(): void
{
$this->assertTrue((new SchoolYearContext(2, '2023-2024', 'closed'))->isReadonly());
$this->assertTrue((new SchoolYearContext(1, '2022-2023', 'archived'))->isReadonly());
$this->assertFalse((new SchoolYearContext(5, '2026-2027', 'draft'))->isReadonly());
}
public function testArrayRepresentationIncludesReadonlyState(): void
{
$context = new SchoolYearContext(3, '2024-2025', 'closed');
$this->assertSame([
'id' => 3,
'name' => '2024-2025',
'status' => 'closed',
'readonly' => true,
'explicitSelection' => false,
], $context->toArray());
}
}
@@ -0,0 +1,41 @@
<?php
namespace Tests\App\Support\SchoolYear;
use App\Support\SchoolYear\SchoolYearTableRegistry;
use CodeIgniter\Test\CIUnitTestCase;
use InvalidArgumentException;
final class SchoolYearTableRegistryTest extends CIUnitTestCase
{
public function testClassifiesYearScopedTables(): void
{
$this->assertSame('YEAR_SCOPED', SchoolYearTableRegistry::categoryOf('invoices'));
$this->assertSame('YEAR_SCOPED', SchoolYearTableRegistry::categoryOf('attendance_data'));
}
public function testClassifiesGlobalTables(): void
{
$this->assertSame('GLOBAL', SchoolYearTableRegistry::categoryOf('users'));
$this->assertSame('GLOBAL', SchoolYearTableRegistry::categoryOf('configuration'));
}
public function testClassifiesIdentityTables(): void
{
$this->assertSame('IDENTITY_WITH_YEAR_RELATION', SchoolYearTableRegistry::categoryOf('students'));
$this->assertSame('IDENTITY_WITH_YEAR_RELATION', SchoolYearTableRegistry::categoryOf('teachers'));
}
public function testClassifiesContextTables(): void
{
$this->assertSame('CONTEXT', SchoolYearTableRegistry::categoryOf('notifications'));
$this->assertSame('CONTEXT', SchoolYearTableRegistry::categoryOf('support_requests'));
}
public function testRejectsUnregisteredTables(): void
{
$this->expectException(InvalidArgumentException::class);
SchoolYearTableRegistry::categoryOf('unknown_table');
}
}