Compare commits

...

14 Commits

Author SHA1 Message Date
root feb1b29a32 apply the school year concept
Tests / PHPUnit (push) Failing after 1m19s
2026-07-14 00:59:00 -04:00
root 504c3bc9f9 fix db delete data issue
Tests / PHPUnit (push) Failing after 1m24s
2026-07-13 01:43:32 -04:00
root f3ac521d7c tests fixes
Tests / PHPUnit (push) Failing after 1m18s
2026-07-13 01:02:03 -04:00
root a56aca4342 fix tests issues
Tests / PHPUnit (push) Failing after 1m16s
2026-07-13 00:24:00 -04:00
root 439a695727 fix test issues
Tests / PHPUnit (push) Failing after 53s
2026-07-12 23:39:11 -04:00
root f83ebe66b9 fix tests issues
Tests / PHPUnit (push) Failing after 43s
2026-07-12 20:36:40 -04:00
root 62492a5644 fix test issues
Tests / PHPUnit (push) Failing after 51s
2026-07-12 19:37:19 -04:00
root 84337e8a50 fix test issues
Tests / PHPUnit (push) Failing after 42s
2026-07-12 19:16:49 -04:00
root 55f8027550 fix missing school year pages
Tests / PHPUnit (push) Failing after 42s
2026-07-12 19:09:38 -04:00
root e06ccc9cc0 ADD SCHOOL YEAR MANAGEMENT
Tests / PHPUnit (push) Failing after 40s
2026-07-12 02:21:39 -04:00
root c7f67da9bf fix gitea checkout ssl
Tests / PHPUnit (push) Failing after 40s
2026-07-12 01:16:28 -04:00
root ed95286050 add gitea test workflow
Tests / PHPUnit (push) Failing after 1m19s
2026-07-12 01:06:56 -04:00
root ec9fca8c45 fix db tables to have school year 2026-07-12 01:02:04 -04:00
root ed11cccecc fix payments 2026-07-08 23:30:16 -04:00
222 changed files with 14375 additions and 2383 deletions
+171
View File
@@ -0,0 +1,171 @@
name: Tests
on:
push:
branches:
- develop
pull_request:
workflow_dispatch:
jobs:
phpunit:
name: PHPUnit
runs-on: ubuntu-latest
services:
mysql:
image: mariadb:10.11
env:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: alrahma_test
MYSQL_USER: alrahma
MYSQL_PASSWORD: alrahma
ports:
- 3306:3306
options: >-
--health-cmd="mariadb-admin ping -h 127.0.0.1 -uroot -proot"
--health-interval=10s
--health-timeout=5s
--health-retries=10
env:
GIT_SSL_NO_VERIFY: 'true'
CI_ENVIRONMENT: testing
TEST_DB_HOST: mysql
TEST_DB_PORT: 3306
TEST_DB_NAME: alrahma_test
TEST_DB_USER: alrahma
TEST_DB_PASSWORD: alrahma
database.tests.hostname: mysql
database.tests.database: alrahma_test
database.tests.username: alrahma
database.tests.password: alrahma
database.tests.DBDriver: MySQLi
database.tests.DBPrefix: ''
database.tests.port: 3306
JWT_SECRET: test-secret-for-ci
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.2'
extensions: dom, gd, intl, mbstring, mysqli, zip
coverage: xdebug
- name: Validate Composer config
run: composer validate --no-check-publish --strict
- name: Install dependencies
run: composer install --no-interaction --prefer-dist --no-progress
- name: Prepare writable directories
run: |
mkdir -p \
writable/cache/testing \
writable/logs \
writable/session \
writable/uploads \
writable/debugbar
chown -R "$(id -u):$(id -g)" writable || true
chmod -R u+rwX,g+rwX writable
- name: Verify writable cache
run: |
test -d writable/cache/testing
test -w writable/cache/testing
touch writable/cache/testing/.ci-write-test
rm writable/cache/testing/.ci-write-test
- name: Verify database configuration
run: |
php -d variables_order=EGPCS -r '
define("FCPATH", __DIR__ . "/public/");
define("ENVIRONMENT", getenv("CI_ENVIRONMENT") ?: "production");
require "app/Config/Paths.php";
$paths = new Config\Paths();
require $paths->systemDirectory . "/Boot.php";
CodeIgniter\Boot::bootConsole($paths);
$database = config("Database");
$dbConfig = $database->{$database->defaultGroup};
echo "Environment: " . ENVIRONMENT . PHP_EOL;
echo "DB group: " . $database->defaultGroup . PHP_EOL;
echo "DB host: " . $dbConfig["hostname"] . PHP_EOL;
echo "DB port: " . $dbConfig["port"] . PHP_EOL;
echo "DB name: " . $dbConfig["database"] . PHP_EOL;
'
- name: Wait for MariaDB
run: |
for attempt in $(seq 1 30); do
php -r '
mysqli_report(MYSQLI_REPORT_OFF);
$db = @new mysqli(
getenv("TEST_DB_HOST"),
getenv("TEST_DB_USER"),
getenv("TEST_DB_PASSWORD"),
getenv("TEST_DB_NAME"),
(int) getenv("TEST_DB_PORT")
);
exit($db->connect_errno === 0 ? 0 : 1);
' && break
echo "Waiting for MariaDB, attempt ${attempt}/30"
sleep 2
done
php -r '
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
new mysqli(
getenv("TEST_DB_HOST"),
getenv("TEST_DB_USER"),
getenv("TEST_DB_PASSWORD"),
getenv("TEST_DB_NAME"),
(int) getenv("TEST_DB_PORT")
);
echo "MariaDB connection successful\n";
'
- name: Import baseline schema
run: php tests/_support/import_baseline.php Database_Dump/u280815660_school_12072025
- name: Run database migrations
run: |
php -d variables_order=EGPCS spark migrate --all --no-interaction
php -r '
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli(
getenv("TEST_DB_HOST"),
getenv("TEST_DB_USER"),
getenv("TEST_DB_PASSWORD"),
getenv("TEST_DB_NAME"),
(int) getenv("TEST_DB_PORT")
);
$tables = [];
$result = $db->query("SHOW TABLES");
while ($row = $result->fetch_array(MYSQLI_NUM)) {
$tables[$row[0]] = true;
}
foreach (["users", "students", "attendance_data"] as $table) {
if (!isset($tables[$table])) {
fwrite(STDERR, "Migration schema missing required table: {$table}\n");
exit(1);
}
}
echo "Migration schema verified\n";
'
- name: Run tests
run: composer test
File diff suppressed because it is too large Load Diff
+8
View File
@@ -168,4 +168,12 @@ class Cache extends BaseConfig
'redis' => RedisHandler::class,
'wincache' => WincacheHandler::class,
];
public function __construct()
{
if (ENVIRONMENT === 'testing') {
$this->storePath = WRITEPATH . 'cache/testing/';
$this->file['storePath'] = WRITEPATH . 'cache/testing/';
}
}
}
+13
View File
@@ -25,6 +25,19 @@ defined('APP_NAMESPACE') || define('APP_NAMESPACE', 'App');
*/
defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload.php');
/*
| --------------------------------------------------------------------------
| Test Support Path
| --------------------------------------------------------------------------
|
| Spark may be run with CI_ENVIRONMENT=testing before CodeIgniter's PHPUnit
| bootstrap has had a chance to define SUPPORTPATH. The framework autoloader
| expects this constant when that environment flag is present.
*/
if (! defined('SUPPORTPATH') && defined('TESTPATH') && is_dir(TESTPATH . '_support')) {
define('SUPPORTPATH', realpath(TESTPATH . '_support') . DIRECTORY_SEPARATOR);
}
/*
|--------------------------------------------------------------------------
| Timing Constants
+12 -8
View File
@@ -16,6 +16,10 @@ class Database extends Config
{
parent::__construct();
if (ENVIRONMENT === 'testing') {
$this->defaultGroup = 'tests';
}
$this->default = [
'DSN' => '',
'hostname' => env('database.default.hostname'),
@@ -38,22 +42,22 @@ class Database extends Config
$this->tests = [
'DSN' => '',
'hostname' => env('database.tests.hostname', env('database.default.hostname')),
'username' => env('database.tests.username', env('database.default.username')),
'password' => env('database.tests.password', env('database.default.password')),
'database' => env('database.tests.database', env('database.default.database')),
'hostname' => env('TEST_DB_HOST', env('database.tests.hostname', env('database.default.hostname'))),
'username' => env('TEST_DB_USER', env('database.tests.username', env('database.default.username'))),
'password' => env('TEST_DB_PASSWORD', env('database.tests.password', env('database.default.password'))),
'database' => env('TEST_DB_NAME', env('database.tests.database', 'alrahma_test')),
'DBDriver' => env('database.tests.DBDriver', env('database.default.DBDriver', 'MySQLi')),
'DBPrefix' => env('database.tests.DBPrefix', 'db_'),
'DBPrefix' => env('database.tests.DBPrefix', ''),
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => (int) env('database.tests.port', env('database.default.port', 3306)),
'port' => (int) env('TEST_DB_PORT', env('database.tests.port', env('database.default.port', 3306))),
];
}
}
+5
View File
@@ -27,4 +27,9 @@ class Feature extends BaseConfig
* Use improved new auto routing instead of the default legacy version.
*/
public bool $autoRoutesImproved = false;
/**
* Show the global school-year selector in authenticated admin layouts.
*/
public bool $globalSchoolYearSelector = true;
}
+2
View File
@@ -31,6 +31,8 @@ class Filters extends BaseConfig
'cleanupScheduler' => \App\Filters\CleanupScheduler::class,
'permission' => \App\Filters\PermissionFilter::class,
'timezone' => \App\Filters\TimezoneFilter::class,
'schoolYear' => \App\Filters\RequireSchoolYearFilter::class,
'schoolYearWritable'=> \App\Filters\SchoolYearWritableFilter::class,
];
+19 -5
View File
@@ -47,6 +47,8 @@ $routes->setAutoRoute(false);
* --------------------------------------------------------------------
*/
$routes->post('api/proofread', 'ProofreadController::check', ['filter' => 'auth']);
$routes->post('school-year/select', 'View\SchoolYearSelectionController::select', ['filter' => 'auth']);
$routes->post('school-year/reset', 'View\SchoolYearSelectionController::reset', ['filter' => 'auth']);
/*
* --------------------------------------------------------------------
@@ -743,11 +745,6 @@ $routes->get('payments/getByParent/(:num)', 'View\PaymentController::getByParent
$routes->get('payments/create', 'View\PaymentController::create');
$routes->post('payments/updateBalance/(:num)', 'View\PaymentController::updateBalance/$1');
// Web View Routes for Payment Transactions
$routes->get('payment_transactions/getByPayment/(:num)', 'View\PaymentTransactionController::getByPayment/$1');
$routes->get('payment_transactions/create', 'View\PaymentTransactionController::create');
$routes->post('payment_transactions/updateStatus/(:num)', 'View\PaymentTransactionController::updateStatus/$1');
// Routes for payment pages
$routes->get('payments/view/(:num)', 'View\PaymentController::viewPayment/$1');
$routes->get('payment/get_enrolled_students/(:num)', 'View\PaymentController::getEnrolledStudents/$1', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
@@ -1037,6 +1034,7 @@ $routes->match(['get', 'post'], 'families/import-legacy', 'FamilyController::imp
// Admin page (protect with your auth/permission)
$routes->group('family', static function ($routes) {
$routes->get('', 'View\FamilyAdminController::index');
$routes->get('index', 'View\FamilyAdminController::index');
$routes->get('search', 'View\FamilyAdminController::search');
$routes->get('card', 'View\FamilyAdminController::card');
@@ -1137,6 +1135,22 @@ $routes->post('/configuration/addConfig', 'View\ConfigurationController::addConf
$routes->match(['get', 'post'], '/configuration/editConfig/(:num)', 'View\ConfigurationController::editConfig/$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
$routes->get('/administrator/attendance-templates', 'View\AttendanceCommentTemplateController::index');
$routes->get('/api/attendance-templates', 'View\AttendanceCommentTemplateController::listData');
+85
View File
@@ -180,4 +180,89 @@ class Services extends BaseService
$http = static::curlrequest($options);
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),
static::schoolYearAccessPolicy()
);
}
public static function schoolYearAccessPolicy(bool $getShared = true): \App\Services\SchoolYearAccessPolicy
{
if ($getShared) {
return static::getSharedInstance('schoolYearAccessPolicy');
}
return new \App\Services\SchoolYearAccessPolicy();
}
public static function schoolYearViewData(bool $getShared = true): \App\Services\SchoolYearViewDataService
{
if ($getShared) {
return static::getSharedInstance('schoolYearViewData');
}
return new \App\Services\SchoolYearViewDataService(
static::schoolYearContext(),
static::schoolYearAccessPolicy()
);
}
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),
model(\App\Models\ConfigurationModel::class),
static::schoolYearManagement(),
\Config\Database::connect()
);
}
}
@@ -54,6 +54,11 @@ class CompetitionWinnersController extends BaseController
public function index()
{
$competitionModel = new CompetitionModel();
$schoolYear = $this->currentCompetitionSchoolYear();
if ($schoolYear !== '') {
$competitionModel->where('school_year', $schoolYear);
}
$competitions = $competitionModel
->orderBy('id', 'DESC')
@@ -62,12 +67,13 @@ class CompetitionWinnersController extends BaseController
return view('admin/competition_winners/index', [
'competitions' => $competitions,
'sectionMap' => $this->getClassSectionMap(),
'schoolYear' => $schoolYear,
]);
}
public function create()
{
$schoolYear = $this->configModel->getConfig('school_year');
$schoolYear = $this->currentCompetitionSchoolYear();
$classCounts = $this->getClassStudentCounts($schoolYear);
$classSections = $this->classSectionModel
->orderBy('class_section_name', 'ASC')
@@ -1088,6 +1094,11 @@ class CompetitionWinnersController extends BaseController
return $questionCounts;
}
private function currentCompetitionSchoolYear(): string
{
return $this->currentSchoolYearName((string) ($this->configModel->getConfig('school_year') ?? ''));
}
private function getClassSectionMap(): array
{
$sections = $this->classSectionModel
+179 -8
View File
@@ -39,7 +39,13 @@ class AdminProgressController extends BaseController
public function index()
{
$schoolYear = trim((string) ($this->request->getGet('school_year') ?? ''));
if ($schoolYear === '') {
$schoolYear = $this->currentSchoolYearName((string) ($this->configModel->getConfig('school_year') ?? ''));
}
$filters = [
'school_year' => $schoolYear,
'from' => (string) $this->request->getGet('from'),
'to' => (string) $this->request->getGet('to'),
'class_section_id' => (string) $this->request->getGet('class_section_id'),
@@ -51,6 +57,8 @@ class AdminProgressController extends BaseController
->join('classSection cs', 'cs.class_section_id = class_progress_reports.class_section_id', 'left')
->join('users u', 'u.id = class_progress_reports.teacher_id', 'left');
$this->applyProgressSchoolYearScope($builder, $schoolYear);
if ($filters['from']) {
$builder->where('week_start >=', $filters['from']);
}
@@ -91,16 +99,17 @@ class AdminProgressController extends BaseController
$reportGroupsBySection[$sectionId] = $groups;
}
$classSections = $this->classSectionModel->getClassSections();
$studentCounts = $this->studentClassModel->getStudentCountsBySection();
$filteredSections = array_values(array_filter($classSections, function ($section) use ($studentCounts) {
$classSections = $this->classSectionsForYear($schoolYear, $rows);
$studentCounts = $this->studentClassModel->getStudentCountsBySection($schoolYear !== '' ? $schoolYear : null);
$filteredSections = array_values(array_filter($classSections, function ($section) use ($studentCounts, $reportGroupsBySection) {
$sectionId = (int) ($section['class_section_id'] ?? 0);
return isset($studentCounts[$sectionId]) && $studentCounts[$sectionId] > 0;
return (isset($studentCounts[$sectionId]) && $studentCounts[$sectionId] > 0)
|| isset($reportGroupsBySection[$sectionId]);
}));
$filterStart = $this->normalizeDate($filters['from'] ?? '');
$filterEnd = $this->normalizeDate($filters['to'] ?? '');
[$dateList, $noSchoolDays, $totalPassedDays, $passedDatesSet] = $this->buildSemesterDates();
[$dateList, $noSchoolDays, $totalPassedDays, $passedDatesSet] = $this->buildSemesterDates($schoolYear);
[$expectedDays, $activeDatesSet] = $this->resolveExpectedDays(
$dateList,
$noSchoolDays,
@@ -132,6 +141,8 @@ class AdminProgressController extends BaseController
return view('admin/class_progress_list', [
'reportGroupsBySection' => $reportGroupsBySection,
'filters' => $filters,
'schoolYear' => $schoolYear,
'schoolYears' => $this->availableSchoolYears($schoolYear),
'classSections' => $filteredSections,
'statusOptions' => ClassProgressController::STATUS_OPTIONS,
'subjectSections' => ClassProgressController::SUBJECT_SECTIONS,
@@ -142,6 +153,162 @@ class AdminProgressController extends BaseController
]);
}
private function classSectionsForYear(string $schoolYear, array $reportRows = []): array
{
$db = db_connect();
if ($schoolYear !== '' && $db->fieldExists('school_year', 'classSection')) {
$sections = $db->table('classSection')
->select('classSection.class_section_id, classSection.class_section_name, classes.class_name')
->join('classes', 'classSection.class_id = classes.id', 'left')
->where('classSection.school_year', $schoolYear)
->orderBy('classSection.class_section_name', 'ASC')
->get()
->getResultArray();
} else {
$sections = $this->classSectionModel->getClassSections();
}
$sectionsById = [];
foreach ($sections as $section) {
$sectionId = (int) ($section['class_section_id'] ?? 0);
if ($sectionId > 0) {
$sectionsById[$sectionId] = $section;
}
}
foreach ($reportRows as $row) {
$sectionId = (int) ($row['class_section_id'] ?? 0);
if ($sectionId <= 0 || isset($sectionsById[$sectionId])) {
continue;
}
$sectionsById[$sectionId] = [
'class_section_id' => $sectionId,
'class_section_name' => (string) ($row['class_section_name'] ?? ('Section #' . $sectionId)),
'class_name' => '',
];
}
uasort($sectionsById, static function (array $a, array $b): int {
return strnatcasecmp((string) ($a['class_section_name'] ?? ''), (string) ($b['class_section_name'] ?? ''));
});
return array_values($sectionsById);
}
private function applyProgressSchoolYearScope($builder, string $schoolYear): void
{
if ($schoolYear === '') {
return;
}
$db = db_connect();
$hasReportYear = $db->fieldExists('school_year', 'class_progress_reports');
$hasSectionYear = $db->fieldExists('school_year', 'classSection');
[$rangeStart, $rangeEnd] = $this->semesterRangeService->getSchoolYearRange($schoolYear);
if ($hasReportYear) {
if ($this->hasAnyExplicitProgressSchoolYearRows()) {
$builder->where('class_progress_reports.school_year', $schoolYear);
return;
}
if ($rangeStart !== '' && $rangeEnd !== '') {
$builder
->groupStart()
->groupStart()
->where('class_progress_reports.school_year IS NULL', null, false)
->orWhere('class_progress_reports.school_year', '')
->groupEnd()
->where('class_progress_reports.week_start >=', $rangeStart)
->where('class_progress_reports.week_start <=', $rangeEnd)
->groupEnd();
return;
}
$builder->where('class_progress_reports.school_year', $schoolYear);
return;
}
if ($hasSectionYear) {
$builder->where('cs.school_year', $schoolYear);
return;
}
if ($rangeStart !== '' && $rangeEnd !== '') {
$builder
->where('class_progress_reports.week_start >=', $rangeStart)
->where('class_progress_reports.week_start <=', $rangeEnd);
}
}
private function hasAnyExplicitProgressSchoolYearRows(): bool
{
try {
return db_connect()
->table('class_progress_reports')
->where('school_year IS NOT NULL', null, false)
->where('school_year !=', '')
->limit(1)
->get()
->getRowArray() !== null;
} catch (\Throwable $e) {
log_message('warning', 'Unable to check explicit progress school-year rows: {message}', [
'message' => $e->getMessage(),
]);
return true;
}
}
private function availableSchoolYears(string $selectedYear): array
{
$years = [];
$addYear = static function (mixed $value) use (&$years): void {
$year = trim((string) $value);
if ($year !== '' && ! in_array($year, $years, true)) {
$years[] = $year;
}
};
$addYear($selectedYear);
$addYear($this->currentSchoolYearName((string) ($this->configModel->getConfig('school_year') ?? '')));
$db = db_connect();
foreach ([
['table' => 'school_years', 'column' => 'name'],
['table' => 'class_progress_reports', 'column' => 'school_year'],
['table' => 'classSection', 'column' => 'school_year'],
['table' => 'student_class', 'column' => 'school_year'],
] as $source) {
try {
if (! $db->tableExists($source['table']) || ! $db->fieldExists($source['column'], $source['table'])) {
continue;
}
$rows = $db->table($source['table'])
->select($source['column'])
->distinct()
->where($source['column'] . ' IS NOT NULL', null, false)
->orderBy($source['column'], 'DESC')
->get()
->getResultArray();
foreach ($rows as $row) {
$addYear($row[$source['column']] ?? '');
}
} catch (\Throwable $e) {
log_message('warning', 'Unable to load school-year options for admin progress: {message}', [
'message' => $e->getMessage(),
]);
}
}
rsort($years, SORT_NATURAL);
return $years;
}
public function view($id)
{
$row = $this->reportModel
@@ -277,11 +444,15 @@ class AdminProgressController extends BaseController
return checkdate($m, $d, $y) ? $value : '';
}
protected function buildSemesterDates(): array
protected function buildSemesterDates(?string $schoolYear = null): array
{
$schoolYear = (string) ($this->configModel->getConfig('school_year') ?? '');
$schoolYear = trim((string) ($schoolYear ?? ''));
if ($schoolYear === '') {
$schoolYear = $this->currentSchoolYearName((string) ($this->configModel->getConfig('school_year') ?? ''));
}
$semester = (string) ($this->configModel->getConfig('semester') ?? '');
$schoolYearForRange = $schoolYear !== '' ? $schoolYear : (string) ($this->configModel->getConfig('school_year') ?? '');
$schoolYearForRange = $schoolYear !== '' ? $schoolYear : $this->currentSchoolYearName((string) ($this->configModel->getConfig('school_year') ?? ''));
[$rangeStart, $rangeEnd] = $this->semesterRangeService->getSchoolYearRange($schoolYearForRange);
$semesterNorm = $this->semesterRangeService->normalizeSemester($semester);
if ($semesterNorm !== '' && $schoolYearForRange !== '') {
@@ -0,0 +1,168 @@
<?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'));
$preview = service('schoolYearClosing')->preview($id, $targetId);
$promotionTable = $this->promotionTablePayload($preview['promotion']['rows'] ?? []);
return view('school_years/closing_preview', [
'preview' => $preview,
'promotionTable' => $promotionTable,
'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', 'End-year process 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 confirmed.');
} 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 ended and 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', 'End-year process 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 promotionTablePayload(array $rows): array
{
$allowedSorts = ['student', 'school_id', 'class', 'year_score', 'decision', 'source', 'queue', 'target', 'status'];
$sort = (string) ($this->request->getGet('sort') ?? 'class');
$sort = in_array($sort, $allowedSorts, true) ? $sort : 'class';
$order = strtolower((string) ($this->request->getGet('order') ?? 'asc')) === 'desc' ? 'desc' : 'asc';
$page = max(1, (int) ($this->request->getGet('page') ?? 1));
$perPage = (int) ($this->request->getGet('per_page') ?? 25);
$allowedPerPage = [10, 25, 50, 100];
$perPage = in_array($perPage, $allowedPerPage, true) ? $perPage : 25;
usort($rows, function (array $a, array $b) use ($sort, $order): int {
$comparison = $this->comparePromotionRows($a, $b, $sort);
if ($comparison === 0 && $sort !== 'class') {
$comparison = $this->comparePromotionRows($a, $b, 'class');
}
if ($comparison === 0 && $sort !== 'student') {
$comparison = $this->comparePromotionRows($a, $b, 'student');
}
if ($comparison === 0) {
$comparison = ((int) ($a['student_id'] ?? 0)) <=> ((int) ($b['student_id'] ?? 0));
}
return $order === 'desc' ? -$comparison : $comparison;
});
$total = count($rows);
$pageCount = max(1, (int) ceil($total / $perPage));
$page = min($page, $pageCount);
$offset = ($page - 1) * $perPage;
return [
'rows' => array_slice($rows, $offset, $perPage),
'sort' => $sort,
'order' => $order,
'page' => $page,
'perPage' => $perPage,
'total' => $total,
'pageCount' => $pageCount,
'allowedPerPage' => $allowedPerPage,
'from' => $total === 0 ? 0 : $offset + 1,
'to' => min($offset + $perPage, $total),
];
}
private function comparePromotionRows(array $a, array $b, string $sort): int
{
$aValue = $this->promotionSortValue($a, $sort);
$bValue = $this->promotionSortValue($b, $sort);
if ($sort === 'year_score') {
if ($aValue === null && $bValue === null) {
return 0;
}
if ($aValue === null) {
return 1;
}
if ($bValue === null) {
return -1;
}
return $aValue <=> $bValue;
}
return strnatcasecmp((string) $aValue, (string) $bValue);
}
private function promotionSortValue(array $row, string $sort): mixed
{
return match ($sort) {
'student' => (string) ($row['student_name'] ?? ''),
'school_id' => (string) ($row['school_id'] ?? ''),
'class' => (string) ($row['class_section_name'] ?? ''),
'year_score' => is_numeric($row['year_score'] ?? null) ? (float) $row['year_score'] : null,
'decision' => (string) ($row['decision'] ?? ''),
'source' => (string) ($row['source'] ?? ''),
'queue' => (string) ($row['queue_status'] ?? ''),
'target' => trim((string) ($row['target_section'] ?? '') . ' ' . (string) ($row['target_class'] ?? '')),
'status' => (string) ($row['status'] ?? ''),
default => '',
};
}
private function userId(): ?int
{
$id = session('user_id') ?? session('id');
return is_numeric($id) ? (int) $id : null;
}
}
@@ -0,0 +1,216 @@
<?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(),
'yearVerification' => $this->verificationByYear($schoolYears),
'schoolYearNamesById' => array_column($schoolYears, 'name', 'id'),
]);
}
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;
}
private function verificationByYear(array $schoolYears): array
{
$db = db_connect();
$verification = [];
$hasStudentClass = $db->tableExists('student_class');
$hasStudentDecisions = $db->tableExists('student_decisions');
$hasPromotionQueue = $db->tableExists('promotion_queue');
$hasInvoices = $db->tableExists('invoices');
$hasClosingBatches = $db->tableExists('school_year_closing_batches');
foreach ($schoolYears as $year) {
$id = (int) ($year['id'] ?? 0);
$name = (string) ($year['name'] ?? '');
if ($id <= 0 || $name === '') {
continue;
}
$summary = [
'students' => 0,
'decisions' => 0,
'promoted' => 0,
'queued' => 0,
'carry_forward_balance' => 0.0,
'positive_balance' => 0.0,
'credit_balance' => 0.0,
'closing_status' => '',
];
if ($hasStudentClass && $db->fieldExists('school_year', 'student_class')) {
$row = $db->table('student_class')
->select('COUNT(DISTINCT student_id) AS total', false)
->where('school_year', $name)
->get()
->getRowArray();
$summary['students'] = (int) ($row['total'] ?? 0);
}
if ($hasStudentDecisions && $db->fieldExists('school_year', 'student_decisions')) {
$row = $db->table('student_decisions')
->select('COUNT(DISTINCT student_id) AS decisions', false)
->select("COUNT(DISTINCT CASE WHEN LOWER(decision) = 'pass' THEN student_id END) AS promoted", false)
->where('school_year', $name)
->get()
->getRowArray();
$summary['decisions'] = (int) ($row['decisions'] ?? 0);
$summary['promoted'] = (int) ($row['promoted'] ?? 0);
}
if ($hasPromotionQueue && $db->fieldExists('school_year_from', 'promotion_queue')) {
$row = $db->table('promotion_queue')
->select('COUNT(DISTINCT student_id) AS total', false)
->where('school_year_from', $name)
->get()
->getRowArray();
$summary['queued'] = (int) ($row['total'] ?? 0);
}
if ($hasInvoices && $db->fieldExists('school_year', 'invoices')) {
$row = $db->table('invoices')
->select('COALESCE(SUM(balance), 0) AS carry_forward_balance')
->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', $name)
->get()
->getRowArray();
$summary['carry_forward_balance'] = round((float) ($row['carry_forward_balance'] ?? 0), 2);
$summary['positive_balance'] = round((float) ($row['positive_balance'] ?? 0), 2);
$summary['credit_balance'] = round((float) ($row['credit_balance'] ?? 0), 2);
}
if ($hasClosingBatches) {
$batch = $db->table('school_year_closing_batches')
->select('status')
->where('source_school_year_id', $id)
->orderBy('id', 'DESC')
->get(1)
->getRowArray();
$summary['closing_status'] = (string) ($batch['status'] ?? '');
}
$verification[$id] = $summary;
}
return $verification;
}
}
+13 -7
View File
@@ -211,13 +211,7 @@ class AuthController extends BaseController
$this->logLoginAttempt($user['id'], $user['email'], $ip, $this->request->getUserAgent());
// Fetch roles
$userRoleModel = new UserRoleModel();
$rolesRows = $userRoleModel->select('roles.name')
->join('roles', 'roles.id = user_roles.role_id')
->where('user_roles.user_id', $user['id'])
->get()
->getResultArray();
$roleNames = array_column($rolesRows, 'name');
$roleNames = $this->getUserRoleNames((int) $user['id']);
// Build roles map (object with keys per example)
$rolesMap = [];
@@ -454,6 +448,18 @@ class AuthController extends BaseController
$this->userModel->update($userId, ['failed_attempts' => 0, 'last_failed_at' => null]);
}
protected function getUserRoleNames(int $userId): array
{
$userRoleModel = new UserRoleModel();
$rolesRows = $userRoleModel->select('roles.name')
->join('roles', 'roles.id = user_roles.role_id')
->where('user_roles.user_id', $userId)
->get()
->getResultArray();
return array_column($rolesRows, 'name');
}
public function logout()
{
// Get user ID and email from session
+122
View File
@@ -9,6 +9,9 @@ use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Services\ApiClient;
use App\Exceptions\SchoolYear\SchoolYearConfigurationException;
use App\Support\SchoolYear\SchoolYearContext;
use Throwable;
/**
* Class BaseController
@@ -58,6 +61,8 @@ abstract class BaseController extends Controller
// Preload any models, libraries, etc, here.
// E.g.: $this->session = \Config\Services::session();
session();
$this->syncSchoolYearPropertyFromContext();
$this->injectSchoolYearViewData();
// Shared API client available to all controllers
$this->api = service('apiClient');
@@ -88,6 +93,123 @@ abstract class BaseController extends Controller
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 currentSchoolYearName(?string $fallback = null): string
{
try {
return $this->resolveSchoolYearContext()->yearName();
} catch (Throwable $e) {
if ($fallback !== null && $fallback !== '') {
return $fallback;
}
try {
return (string) ((new \App\Models\ConfigurationModel())->getConfig('school_year') ?? '');
} catch (Throwable) {
return '';
}
}
}
protected function assertSchoolYearWritable(
SchoolYearContext $context,
bool $allowDraftForAdmin = false,
bool $isAdmin = false
): void {
service('schoolYearWriteGuard')->assertWritable($context, $allowDraftForAdmin, $isAdmin);
}
private function syncSchoolYearPropertyFromContext(): void
{
if (! property_exists($this, 'schoolYear')) {
return;
}
if (! $this->request instanceof IncomingRequest || is_cli()) {
return;
}
if (! session()->get('user_id')) {
return;
}
try {
$this->schoolYear = $this->currentSchoolYearName((string) ($this->schoolYear ?? ''));
} catch (Throwable $e) {
log_message('warning', 'Unable to sync controller school-year property: {message}', [
'message' => $e->getMessage(),
]);
}
}
private function injectSchoolYearViewData(): void
{
if (! config('Feature')->globalSchoolYearSelector) {
return;
}
if (! $this->request instanceof IncomingRequest || is_cli()) {
return;
}
if (! session()->get('user_id')) {
return;
}
if (! $this->shouldShowSchoolYearSelector()) {
return;
}
$accept = strtolower($this->request->getHeaderLine('Accept'));
if ($this->request->isAJAX() || str_contains($accept, 'application/json')) {
return;
}
try {
service('renderer')->setData(service('schoolYearViewData')->forCurrentRequest($this->request));
} catch (SchoolYearConfigurationException $e) {
throw $e;
} catch (Throwable $e) {
log_message('warning', 'Unable to inject school-year view data: {message}', [
'message' => $e->getMessage(),
]);
}
}
private function shouldShowSchoolYearSelector(): bool
{
$roles = (array) session()->get('roles');
$singleRole = session()->get('role');
if ($singleRole !== null && $singleRole !== '') {
$roles[] = $singleRole;
}
$roles = array_map(
static fn ($role): string => strtolower(trim((string) $role)),
$roles
);
return (bool) array_intersect($roles, [
'admin',
'administrator',
'administrative staff',
'principal',
'vice principal',
]);
}
}
?>
@@ -115,9 +115,10 @@ class InitializeRolesPermissions extends Controller
// Associating permissions with roles
$rolePermissions = [
'administrator' => ['manage_users', 'view_reports', 'manage_settings', 'access_student_records', 'communicate_parents'],
'principal' => ['manage_users', 'view_reports', 'access_student_records', 'communicate_parents'],
'vice principal' => ['view_reports', 'access_student_records', 'communicate_parents'],
'administrator' => ['manage_users', 'view_reports', 'manage_settings', 'access_student_records', 'communicate_parents', 'update_curriculum'],
'principal' => ['manage_users', 'view_reports', 'access_student_records', 'communicate_parents', 'update_curriculum'],
'vice principal' => ['view_reports', 'access_student_records', 'communicate_parents', 'update_curriculum'],
'admin' => ['manage_users', 'view_reports', 'manage_settings', 'access_student_records', 'communicate_parents', 'update_curriculum'],
'teacher' => ['access_student_records', 'communicate_parents', 'enter_grades', 'access_assignments'],
'student' => ['view_own_records', 'access_assignments'],
'parent' => ['view_own_records', 'communicate_parents'],
@@ -31,7 +31,7 @@ class ParentReportCardController extends BaseController
return redirect()->back()->with('error', 'Unable to retrieve student data. Please contact support.');
}
$schoolYear = trim((string) ($this->request->getGet('school_year') ?? $this->configModel->getConfig('school_year') ?? ''));
$schoolYear = trim((string) ($this->request->getGet('school_year') ?? $this->currentSchoolYearName()));
$semester = trim((string) ($this->request->getGet('semester') ?? $this->configModel->getConfig('semester') ?? ''));
$builder = $this->db->table('students s')
@@ -45,9 +45,6 @@ class ParentReportCardController extends BaseController
if ($schoolYear !== '') {
$builder->where('sc.school_year', $schoolYear);
}
if ($semester !== '') {
$builder->where('sc.semester', $semester);
}
$students = $builder->get()->getResultArray();
$studentIds = array_values(array_filter(array_map(static fn ($s) => (int) ($s['id'] ?? 0), $students)));
@@ -85,7 +82,7 @@ class ParentReportCardController extends BaseController
throw new PageNotFoundException('Student not found.');
}
$schoolYear = trim((string) ($this->request->getGet('school_year') ?? $this->configModel->getConfig('school_year') ?? ''));
$schoolYear = trim((string) ($this->request->getGet('school_year') ?? $this->currentSchoolYearName()));
$semester = trim((string) ($this->request->getGet('semester') ?? $this->configModel->getConfig('semester') ?? ''));
$this->touchAcknowledgement($parentId, (int) $studentId, $schoolYear, $semester, [
@@ -124,7 +121,7 @@ class ParentReportCardController extends BaseController
return redirect()->back()->with('error', 'Please type your full name to sign.');
}
$schoolYear = trim((string) ($this->configModel->getConfig('school_year') ?? ''));
$schoolYear = trim((string) $this->currentSchoolYearName());
$semester = trim((string) ($this->configModel->getConfig('semester') ?? ''));
$now = date('Y-m-d H:i:s');
$this->touchAcknowledgement($parentId, (int) $studentId, $schoolYear, $semester, [
+174 -81
View File
@@ -570,21 +570,21 @@ class AdministratorController extends BaseController
// USERS (phone col: cellphone)
$uCols = ['firstname', 'lastname', 'email', 'cellphone', 'school_id', 'city', 'state'];
$uQB = $db->table('users')
->select('id, firstname, lastname, email, cellphone, school_id, city, state, school_year, semester');
->select('id, firstname, lastname, email, cellphone, school_id, city, state, semester');
$applyMultiTokenLike($uQB, $uCols, $tokens, ['cellphone']);
$users = $uQB->limit(150)->get()->getResultArray();
// STUDENTS (no phone column to search)
$sCols = ['firstname', 'lastname', 'school_id', 'rfid_tag', 'dob', 'gender'];
$sQB = $db->table('students')
->select('id, parent_id, school_id, firstname, lastname, dob, gender, school_year, semester, rfid_tag');
->select('id, parent_id, school_id, firstname, lastname, dob, gender, semester, rfid_tag');
$applyMultiTokenLike($sQB, $sCols, $tokens, []);
$students = $sQB->limit(150)->get()->getResultArray();
// PARENTS (phone col: secondparent_phone)
$pCols = ['secondparent_firstname', 'secondparent_lastname', 'secondparent_email', 'secondparent_phone'];
$pQB = $db->table('parents')
->select('id, firstparent_id, secondparent_firstname, secondparent_lastname, secondparent_email, secondparent_phone, school_year, semester');
->select('id, firstparent_id, secondparent_firstname, secondparent_lastname, secondparent_email, secondparent_phone');
$applyMultiTokenLike($pQB, $pCols, $tokens, ['secondparent_phone']);
foreach ($tokens as $t) {
if (ctype_digit($t)) {
@@ -596,14 +596,14 @@ class AdministratorController extends BaseController
// STAFF (phone col: phone)
$stCols = ['firstname', 'lastname', 'email', 'role_name', 'phone'];
$stQB = $db->table('staff')
->select('id, user_id, firstname, lastname, email, phone, role_name, school_year, active_role');
->select('id, user_id, firstname, lastname, email, phone, role_name, active_role');
$applyMultiTokenLike($stQB, $stCols, $tokens, ['phone']);
$staff = $stQB->limit(150)->get()->getResultArray();
// EMERGENCY CONTACTS (phone col: cellphone)
$ecCols = ['emergency_contact_name', 'relation', 'email', 'cellphone'];
$ecQB = $db->table('emergency_contacts')
->select('id, parent_id, emergency_contact_name, relation, cellphone, email, school_year, semester');
->select('id, parent_id, emergency_contact_name, relation, cellphone, email');
$applyMultiTokenLike($ecQB, $ecCols, $tokens, ['cellphone']);
$emergency = $ecQB->limit(150)->get()->getResultArray();
@@ -699,7 +699,10 @@ class AdministratorController extends BaseController
public function teacherSubmissionsReport()
{
$semester = (string)($this->configModel->getConfig('semester') ?? $this->semester ?? '');
$schoolYear = (string)($this->configModel->getConfig('school_year') ?? $this->schoolYear ?? '');
$schoolYear = trim((string) ($this->request->getGet('school_year') ?? ''));
if ($schoolYear === '') {
$schoolYear = $this->currentSchoolYearName((string) ($this->schoolYear ?? ''));
}
$semesterResolver = new SemesterRangeService($this->configModel);
$semesterNorm = $semesterResolver->normalizeSemester($semester);
$semesterFilter = $semesterNorm !== '' ? $semesterNorm : $semester;
@@ -730,18 +733,15 @@ class AdministratorController extends BaseController
->join('users u', 'u.id = tc.teacher_id', 'left')
->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 !== '') {
$filteredQuery = $filteredQuery->where('tc.school_year', $schoolYear);
}
if (!empty($semesterCandidates)) {
$filteredQuery = $filteredQuery->whereIn('tc.semester', $semesterCandidates);
$assignmentQuery->where('tc.school_year', $schoolYear);
}
$assignmentRows = $filteredQuery->get()->getResultArray();
if (empty($assignmentRows) && ($schoolYear !== '' || $semester !== '')) {
$assignmentRows = $assignmentQuery->get()->getResultArray();
}
$studentCounts = $this->studentClassModel->getStudentCountsBySection($schoolYear !== '' ? $schoolYear : null);
$sectionRows = $this->classSectionModel
@@ -873,14 +873,12 @@ class AdministratorController extends BaseController
continue;
}
$studentQuery = $this->studentClassModel
$studentEntries = $this->db->table('student_class')
->select('student_id')
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear);
if (!empty($semesterCandidates)) {
$studentQuery->whereIn('semester', $semesterCandidates);
}
$studentEntries = $studentQuery->findAll();
->where('school_year', $schoolYear)
->get()
->getResultArray();
if (empty($studentEntries)) {
$studentEntries = $this->studentClassModel
->select('student_id')
@@ -1104,9 +1102,9 @@ class AdministratorController extends BaseController
}
$semesterResolver = new SemesterRangeService($this->configModel);
$schoolYear = (string)($this->configModel->getConfig('school_year') ?? '');
$schoolYear = $this->currentSchoolYearName((string) ($this->schoolYear ?? ''));
$semester = (string)($this->configModel->getConfig('semester') ?? '');
$schoolYearForRange = $schoolYear !== '' ? $schoolYear : (string)($this->configModel->getConfig('school_year') ?? '');
$schoolYearForRange = $schoolYear !== '' ? $schoolYear : $this->currentSchoolYearName((string) ($this->schoolYear ?? ''));
[$rangeStart, $rangeEnd] = $semesterResolver->getSchoolYearRange($schoolYearForRange);
$semesterNorm = $semesterResolver->normalizeSemester($semester);
if ($semesterNorm !== '' && $schoolYearForRange !== '') {
@@ -2207,7 +2205,6 @@ class AdministratorController extends BaseController
'cellphone' => $user['cellphone'],
'gender' => $user['gender'],
'created_at' => $user['created_at'],
'school_year' => $user['school_year'],
'paid_amount' => $paidAmount,
'balance' => $balance,
'students' => $students,
@@ -2301,22 +2298,10 @@ class AdministratorController extends BaseController
public function showEnrollmentWithdrawalPage()
{
try {
$selectedYear = trim((string)($this->request->getGet('schoolYear') ?? ''));
if ($selectedYear === '') {
$selectedYear = (string)$this->schoolYear;
}
$schoolYears = $this->availableSchoolYears();
$selectedYear = $this->selectedEnrollmentSchoolYear($schoolYears);
// Distinct school years from enrollments (for selector)
$yearsRows = $this->db->table('enrollments')
->distinct()
->select('school_year')
->orderBy('school_year', 'DESC')
->get()->getResultArray();
$schoolYears = array_values(array_filter(array_map(static function ($r) {
return isset($r['school_year']) ? (string)$r['school_year'] : null;
}, $yearsRows)));
$students = $this->studentModel->getStudentsWithClassAndEnrollment();
$students = $this->studentModel->getStudentsWithClassAndEnrollment($selectedYear);
$selectedStartYear = $this->getSchoolYearStartYear((string)$selectedYear);
$removedPriorIds = [];
@@ -2332,6 +2317,7 @@ class AdministratorController extends BaseController
}
}
}
$returningStudentIds = $this->priorYearStudentIds($selectedYear);
foreach ($students as &$s) {
// ===== Ensure IDs needed by the modal =====
@@ -2366,6 +2352,9 @@ class AdministratorController extends BaseController
// ===== New-student flags =====
$s['is_new'] = (int) ($s['is_new'] ?? 0);
if (isset($returningStudentIds[$s['student_id']])) {
$s['is_new'] = 0;
}
$s['new_student'] = $s['is_new'] === 1 ? 'Yes' : 'No';
// ===== Admission override =====
@@ -2375,6 +2364,9 @@ class AdministratorController extends BaseController
$s['enrollment_status'] = $statusForYear;
} elseif (($s['admission_status'] ?? null) === 'denied') {
$s['enrollment_status'] = 'denied';
} else {
$s['enrollment_status'] = 'admission under review';
$s['admission_status'] = 'pending';
}
// ===== Class section name for the selected year =====
@@ -2402,22 +2394,7 @@ class AdministratorController extends BaseController
return strcasecmp($pa, $pb);
});
// ===== Provide classes for the modal select (like studentClassAssignment) =====
// Filter to current term; loosen if your table doesnt store these fields.
$classes = $this->classSectionModel
->select('id, class_section_id, class_section_name, school_year, semester')
->where('school_year', (string)$selectedYear)
->where('semester', (string)$this->semester)
->orderBy('class_section_name', 'ASC')
->findAll();
// Fallback so the dropdown never shows empty if filters are too strict
if (empty($classes)) {
$classes = $this->classSectionModel
->select('id, class_section_id, class_section_name')
->orderBy('class_section_name', 'ASC')
->findAll();
}
$classes = $this->enrollmentClassOptions((string)$selectedYear);
return view('enroll_withdraw/enrollment_withdrawal', [
'students' => $students,
@@ -2438,22 +2415,10 @@ class AdministratorController extends BaseController
public function enrollmentWithdrawalData()
{
try {
$selectedYear = trim((string)($this->request->getGet('schoolYear') ?? ''));
if ($selectedYear === '') {
$selectedYear = (string)$this->schoolYear;
}
$schoolYears = $this->availableSchoolYears();
$selectedYear = $this->selectedEnrollmentSchoolYear($schoolYears);
// Distinct school years
$yearsRows = $this->db->table('enrollments')
->distinct()
->select('school_year')
->orderBy('school_year', 'DESC')
->get()->getResultArray();
$schoolYears = array_values(array_filter(array_map(static function ($r) {
return isset($r['school_year']) ? (string)$r['school_year'] : null;
}, $yearsRows)));
$students = $this->studentModel->getStudentsWithClassAndEnrollment();
$students = $this->studentModel->getStudentsWithClassAndEnrollment($selectedYear);
$selectedStartYear = $this->getSchoolYearStartYear((string)$selectedYear);
$removedPriorIds = [];
@@ -2469,6 +2434,7 @@ class AdministratorController extends BaseController
}
}
}
$returningStudentIds = $this->priorYearStudentIds($selectedYear);
foreach ($students as &$s) {
$s['student_id'] = (int)($s['id'] ?? 0);
@@ -2491,6 +2457,9 @@ class AdministratorController extends BaseController
$s['parent_sort'] = trim(($pl !== '' ? $pl : $pf) . ' ' . $pf) ?: 'ZZZ Unknown Parent';
$s['is_new'] = (int) ($s['is_new'] ?? 0);
if (isset($returningStudentIds[$s['student_id']])) {
$s['is_new'] = 0;
}
$s['new_student'] = $s['is_new'] === 1 ? 'Yes' : 'No';
$statusForYear = $this->enrollmentModel->getEnrollmentStatus((int)$s['student_id'], $selectedYear);
@@ -2498,6 +2467,9 @@ class AdministratorController extends BaseController
$s['enrollment_status'] = $statusForYear;
} elseif (($s['admission_status'] ?? null) === 'denied') {
$s['enrollment_status'] = 'denied';
} else {
$s['enrollment_status'] = 'admission under review';
$s['admission_status'] = 'pending';
}
$className = $this->studentClassModel->getClassSectionsByStudentId((int)$s['student_id'], $selectedYear);
@@ -2522,18 +2494,7 @@ class AdministratorController extends BaseController
return strcasecmp($pa, $pb);
});
$classes = $this->classSectionModel
->select('id, class_section_id, class_section_name, school_year, semester')
->where('school_year', (string)$selectedYear)
->where('semester', (string)$this->semester)
->orderBy('class_section_name', 'ASC')
->findAll();
if (empty($classes)) {
$classes = $this->classSectionModel
->select('id, class_section_id, class_section_name')
->orderBy('class_section_name', 'ASC')
->findAll();
}
$classes = $this->enrollmentClassOptions((string)$selectedYear);
return $this->response->setJSON([
'students' => $students,
@@ -2549,6 +2510,138 @@ class AdministratorController extends BaseController
}
}
private function availableSchoolYears(): array
{
$years = [];
$addYear = static function (mixed $value) use (&$years): void {
$year = trim((string) $value);
if ($year !== '' && !in_array($year, $years, true)) {
$years[] = $year;
}
};
$addYear($this->schoolYear ?? null);
if ($this->db->tableExists('school_years')) {
$rows = $this->db->table('school_years')
->select('name')
->orderBy('name', 'DESC')
->get()
->getResultArray();
foreach ($rows as $row) {
$addYear($row['name'] ?? null);
}
}
if ($this->db->tableExists('enrollments')) {
$rows = $this->db->table('enrollments')
->distinct()
->select('school_year')
->where('school_year IS NOT NULL', null, false)
->orderBy('school_year', 'DESC')
->get()
->getResultArray();
foreach ($rows as $row) {
$addYear($row['school_year'] ?? null);
}
}
usort($years, static fn(string $a, string $b): int => strnatcasecmp($b, $a));
$activeYear = trim((string) ($this->schoolYear ?? ''));
if ($activeYear !== '') {
$years = array_values(array_filter($years, static fn(string $year): bool => $year !== $activeYear));
array_unshift($years, $activeYear);
}
return $years;
}
private function selectedEnrollmentSchoolYear(array $schoolYears): string
{
$requestedYear = trim((string) ($this->request->getGet('schoolYear') ?? ''));
if ($requestedYear !== '' && in_array($requestedYear, $schoolYears, true)) {
return $requestedYear;
}
$activeYear = trim((string) ($this->schoolYear ?? ''));
if ($activeYear !== '') {
return $activeYear;
}
return (string) ($schoolYears[0] ?? '');
}
private function enrollmentClassOptions(string $selectedYear): array
{
$select = ['id', 'class_section_id', 'class_section_name'];
$hasSchoolYear = $this->db->fieldExists('school_year', 'classSection');
$hasSemester = $this->db->fieldExists('semester', 'classSection');
if ($hasSchoolYear) {
$select[] = 'school_year';
}
if ($hasSemester) {
$select[] = 'semester';
}
$query = $this->classSectionModel
->select(implode(', ', $select))
->orderBy('class_section_name', 'ASC');
if ($hasSchoolYear && $selectedYear !== '') {
$query->where('school_year', $selectedYear);
}
if ($hasSemester) {
$query->where('semester', (string)$this->semester);
}
$classes = $query->findAll();
if (! empty($classes) || (! $hasSchoolYear && ! $hasSemester)) {
return $classes;
}
return $this->classSectionModel
->select('id, class_section_id, class_section_name')
->orderBy('class_section_name', 'ASC')
->findAll();
}
private function priorYearStudentIds(string $selectedYear): array
{
$selectedStartYear = $this->getSchoolYearStartYear($selectedYear);
if ($selectedStartYear === null) {
return [];
}
$studentIds = [];
foreach (['enrollments', 'student_class'] as $table) {
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
continue;
}
$rows = $this->db->table($table)
->select('student_id, school_year')
->where('student_id IS NOT NULL', null, false)
->where('school_year IS NOT NULL', null, false)
->get()
->getResultArray();
foreach ($rows as $row) {
$rowStartYear = $this->getSchoolYearStartYear((string) ($row['school_year'] ?? ''));
$studentId = (int) ($row['student_id'] ?? 0);
if ($studentId > 0 && $rowStartYear !== null && $rowStartYear < $selectedStartYear) {
$studentIds[$studentId] = true;
}
}
}
return $studentIds;
}
/**
* Show only newly registered students, with contact modal support.
*
@@ -46,7 +46,7 @@ class AssignmentController extends BaseController
// Apply school year filter (default to current config) but avoid semester filtering so the full year is visible
$selectedSemester = (string)($this->request->getGet('semester') ?? $this->semester ?? '');
$year = (string)($this->request->getGet('school_year') ?? $this->schoolYear ?? '');
$year = (string)($this->schoolYear ?? '');
$tcQ = $this->teacherClassModel;
if ($year !== '') {
@@ -189,8 +189,8 @@ class AssignmentController extends BaseController
} catch (\Throwable $e) {
// ignore fallback below
}
if (empty($schoolYearsList) && $this->schoolYear !== null && $this->schoolYear !== '') {
$schoolYearsList[] = (string)$this->schoolYear;
if ($this->schoolYear !== null && $this->schoolYear !== '' && !in_array((string)$this->schoolYear, $schoolYearsList, true)) {
array_unshift($schoolYearsList, (string)$this->schoolYear);
}
// Sort sections
+10 -1
View File
@@ -64,11 +64,20 @@ class AttendanceController extends Controller
$this->userRoleModel = new UserRoleModel();
$this->semesterScoreService = service('semesterScoreService');
$this->semester = $this->configModel->getConfig('semester');
$this->schoolYear = $this->configModel->getConfig('school_year');
$this->schoolYear = $this->currentSchoolYearName();
$this->enableAttendance = $this->configModel->getConfig('enable_attendance');
$this->semesterRangeService = new SemesterRangeService($this->configModel);
}
private function currentSchoolYearName(): string
{
try {
return service('schoolYearContext')->resolve(service('request'))->yearName();
} catch (\Throwable $e) {
return (string) ($this->configModel->getConfig('school_year') ?? '');
}
}
/**
* GET: filter + grid for a single date/section.
@@ -70,28 +70,6 @@ class AttendanceTrackingController extends BaseController
->findAll();
$debugInfo['class_students'] = count($classStudents);
// Fallback: if the configured school_year has no class assignments, look up the latest term
if (empty($classStudents)) {
$latestTerm = $this->db->table('student_class')
->select('school_year, semester')
->orderBy('id', 'DESC')
->limit(1)
->get()
->getRowArray();
if ($latestTerm && !empty($latestTerm['school_year'])) {
$schoolYear = (string)$latestTerm['school_year'];
if (!empty($latestTerm['semester'])) {
$semester = (string)$latestTerm['semester'];
}
$classStudents = $this->studentClassModel
->active()
->where('student_class.school_year', $schoolYear)
->findAll();
}
}
// Gather candidate student identifiers (numeric IDs and code-like IDs)
$studentIds = [];
$studentCodes = [];
@@ -21,8 +21,10 @@ class ClassPreparationController extends BaseController
protected $schoolYear;
protected $semester;
protected $adjustmentModel;
/** cache for roster presence per term */
/** Cache for roster presence per school year. */
private array $rosterPresenceCache = [];
/** Cache table-column checks to avoid repeated schema queries. */
private array $columnExistsCache = [];
// Inside ClassPreparationController (class scope, not inside a method)
private array $allowedPrepCategories = [
'Grade Box',
@@ -57,7 +59,7 @@ class ClassPreparationController extends BaseController
$semParam = $this->request->getGet('semester');
$semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester;
$allowed = $this->allowedPrepCategories;
$limitToSemester = $this->hasRosterForSemester($schoolYear, $semester);
$hasRoster = $this->hasRosterForSchoolYear($schoolYear);
// 1) Get student count per class-section (distinct students, correct semester)
$scQ = $this->db->table('student_class sc')
@@ -65,13 +67,12 @@ class ClassPreparationController extends BaseController
->join('students s', 's.id = sc.student_id', 'inner')
->where('s.is_active', 1)
->where('sc.school_year', $schoolYear);
if ($limitToSemester && $semester !== '') {
$scQ->where('sc.semester', $semester);
}
$classSections = $scQ->groupBy('sc.class_section_id')->get()->getResultArray();
$classSections = $hasRoster
? $scQ->groupBy('sc.class_section_id')->get()->getResultArray()
: [];
// 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
$requiredTotals = array_fill_keys($allowed, 0);
@@ -85,14 +86,10 @@ class ClassPreparationController extends BaseController
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId);
// 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 ---
$rawAdjustments = $this->adjustmentModel
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear)
->where('adjustable', 1)
->findAll();
$rawAdjustments = $this->getAdjustments((string) $classSectionId, (string) $schoolYear);
$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
$oldSnap = $this->prepLogModel
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear)
->orderBy('created_at', 'DESC')
->first();
$oldSnap = $this->getLatestPrepSnapshot((string) $classSectionId, (string) $schoolYear);
$oldPrep = $oldSnap ? json_decode($oldSnap['prep_data'], true) : [];
$hasChanged = $this->hasPrepChanged($baseItems, $oldPrep);
@@ -175,7 +168,7 @@ class ClassPreparationController extends BaseController
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
$allowed = $this->allowedPrepCategories;
@@ -192,7 +185,7 @@ class ClassPreparationController extends BaseController
// 3) Rules
$isLowerGrades = in_array($classLevel, [1, 2], true);
$teacherCount = $this->getTeacherCountForSection($classSectionId, $this->schoolYear);
$teacherCount = $this->getTeacherCountForSection($classSectionId, $schoolYear ?? $this->schoolYear);
foreach ($categories as $cat) {
$name = $cat['name']; // e.g., 'Small Table'
@@ -253,24 +246,35 @@ class ClassPreparationController extends BaseController
$adjustments = $data['adjustments'] ?? [];
foreach ($adjustments as $itemName => $adjustment) {
$row = $this->adjustmentModel
$adjustmentQuery = $this->adjustmentModel
->where('class_section_id', $sectionId)
->where('school_year', $schoolYear)
->where('item_name', $itemName)
->first();
->where('item_name', $itemName);
$adjustmentTable = $this->adjustmentModel->getTable();
if ($schoolYear !== '' && $this->tableHasColumn($adjustmentTable, 'school_year')) {
$adjustmentQuery->where('school_year', $schoolYear);
}
$row = $adjustmentQuery->first();
if ($row) {
// Update
$this->adjustmentModel->update($row['id'], ['adjustment' => (int)$adjustment, 'adjustable' => 1]);
} else {
// Insert
$this->adjustmentModel->insert([
$insertData = [
'class_section_id' => $sectionId,
'item_name' => $itemName,
'adjustment' => (int)$adjustment,
'school_year' => $schoolYear,
'adjustment' => (int) $adjustment,
'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)
{
$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)
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId) ?? $classSectionId;
@@ -306,15 +306,12 @@ class ClassPreparationController extends BaseController
->where('s.is_active', 1)
->where('sc.class_section_id', $classSectionId)
->where('sc.school_year', $schoolYear);
if ($limitToSemester && $semester !== '') {
$studentQ->where('sc.semester', $semester);
}
$studentRow = $studentQ->get()->getRowArray();
$studentCount = (int)($studentRow['cnt'] ?? 0);
// Live calc + adjustments
$classLevel = $this->getClassLevelBySection((string)$classSectionId);
$items = $this->calculatePrepItems($studentCount, $classLevel, (string)$classSectionId);
$items = $this->calculatePrepItems($studentCount, $classLevel, (string)$classSectionId, (string)$schoolYear);
$rawAdjustments = $this->adjustmentModel
->where('class_section_id', $classSectionId)
@@ -328,13 +325,15 @@ class ClassPreparationController extends BaseController
}
// Record a snapshot at print time as the new baseline
$this->prepLogModel->insert([
'class_section_id' => (string)$classSectionId,
'class_section' => $className,
'school_year' => $schoolYear,
'prep_data' => json_encode($items),
'created_at' => utc_now(),
]);
$this->prepLogModel->insert(
$this->buildPrepLogData(
(string) $classSectionId,
(string) $className,
(string) $schoolYear,
$items,
utc_now()
)
);
// Return PRINT view (HTML) that auto-opens the print dialog
return view('class_prep/print', [
@@ -356,7 +355,7 @@ class ClassPreparationController extends BaseController
$semParam = $this->request->getGet('semester');
$semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester;
$allowed = $this->allowedPrepCategories;
$limitToSemester = $this->hasRosterForSemester($schoolYear, $semester);
$hasRoster = $this->hasRosterForSchoolYear($schoolYear);
// Student counts
$scQ = $this->db->table('student_class sc')
@@ -364,13 +363,12 @@ class ClassPreparationController extends BaseController
->join('students s', 's.id = sc.student_id', 'inner')
->where('s.is_active', 1)
->where('sc.school_year', $schoolYear);
if ($limitToSemester && $semester !== '') {
$scQ->where('sc.semester', $semester);
}
$classSections = $scQ->groupBy('sc.class_section_id')->get()->getResultArray();
$classSections = $hasRoster
? $scQ->groupBy('sc.class_section_id')->get()->getResultArray()
: [];
// Build inventory availability maps
$inventoryMap = $this->buildInventoryAvailability($schoolYear, $semester, $limitToSemester, $allowed);
$inventoryMap = $this->buildInventoryAvailability($schoolYear, $semester, $allowed);
$requiredTotals = array_fill_keys($allowed, 0);
$results = [];
@@ -381,12 +379,8 @@ class ClassPreparationController extends BaseController
$classLevel = $this->getClassLevelBySection($classSectionId);
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId);
$baseItems = $this->calculatePrepItems($studentCount, $classLevel, $classSectionId);
$rawAdjustments = $this->adjustmentModel
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear)
->where('adjustable', 1)
->findAll();
$baseItems = $this->calculatePrepItems($studentCount, $classLevel, $classSectionId, $schoolYear);
$rawAdjustments = $this->getAdjustments((string) $classSectionId, (string) $schoolYear);
$adjMap = ['Large Table' => 0, 'Small Table' => 0];
foreach ($rawAdjustments as $a) {
$item = $a['item_name'];
@@ -399,11 +393,7 @@ class ClassPreparationController extends BaseController
$requiredTotals[$cat] += (int)($baseItems[$cat] ?? 0);
}
$oldSnap = $this->prepLogModel
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear)
->orderBy('created_at', 'DESC')
->first();
$oldSnap = $this->getLatestPrepSnapshot((string) $classSectionId, (string) $schoolYear);
$oldPrep = $oldSnap ? json_decode($oldSnap['prep_data'], true) : [];
$hasChanged = $this->hasPrepChanged($baseItems, $oldPrep);
@@ -446,7 +436,6 @@ class ClassPreparationController extends BaseController
$schoolYear = (string)($this->request->getPost('school_year') ?? $this->schoolYear);
$semParam = $this->request->getPost('semester');
$semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester;
$limitToSemester = $this->hasRosterForSemester($schoolYear, $semester);
$ids = $this->request->getPost('class_section_ids') ?? [];
if (!is_array($ids)) $ids = $ids ? [$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('sc.class_section_id', $classSectionId)
->where('sc.school_year', $schoolYear);
if ($limitToSemester && $semester !== '') {
$studentQ->where('sc.semester', $semester);
}
$studentRow = $studentQ->get()->getRowArray();
$studentCount = (int)($studentRow['cnt'] ?? 0);
$classLevel = $this->getClassLevelBySection((string)$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
->where('class_section_id', $classSectionId)
->where('school_year', $schoolYear)
->where('adjustable', 1)
->findAll();
$rawAdjustments = $this->getAdjustments((string) $classSectionId, (string) $schoolYear);
foreach ($rawAdjustments as $a) {
$item = $a['item_name'];
$delta = (int)$a['adjustment'];
@@ -482,13 +464,15 @@ class ClassPreparationController extends BaseController
}
try {
$this->prepLogModel->insert([
'class_section_id' => (string)$classSectionId,
'class_section' => $className,
'school_year' => $schoolYear,
'prep_data' => json_encode($items),
'created_at' => $now,
]);
$this->prepLogModel->insert(
$this->buildPrepLogData(
(string) $classSectionId,
(string) $className,
(string) $schoolYear,
$items,
$now
)
);
$count++;
} catch (\Throwable $e) {
// ignore and continue
@@ -528,12 +512,12 @@ class ClassPreparationController extends BaseController
}
/**
* Returns true if student_class has any rows for the given school year.
* The semester argument is ignored because assignments are tracked per year.
* Returns true when student_class contains at least one assignment
* 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 === '') {
return false;
}
@@ -542,72 +526,163 @@ class ClassPreparationController extends BaseController
return $this->rosterPresenceCache[$year];
}
$cnt = $this->db->table('student_class')
$exists = $this->db->table('student_class')
->where('school_year', $year)
->countAllResults();
->limit(1)
->countAllResults() > 0;
$this->rosterPresenceCache[$year] = $cnt > 0;
return $this->rosterPresenceCache[$year];
$this->rosterPresenceCache[$year] = $exists;
return $exists;
}
private function hasRosterForSemester(string $schoolYear, string $semester): bool
private function tableHasColumn(string $table, string $column): bool
{
$year = trim((string)$schoolYear);
$sem = trim((string)$semester);
if ($year === '' || $sem === '') {
return false;
$key = $table . '.' . $column;
if (!array_key_exists($key, $this->columnExistsCache)) {
$this->columnExistsCache[$key] = $this->db->fieldExists($column, $table);
}
$key = sprintf('sem:%s:%s', $year, $sem);
if (array_key_exists($key, $this->rosterPresenceCache)) {
return $this->rosterPresenceCache[$key];
return $this->columnExistsCache[$key];
}
$cnt = $this->db->table('student_class')
->where('school_year', $year)
->where('semester', $sem)
->countAllResults();
private function getAdjustments(string $classSectionId, string $schoolYear): array
{
$query = $this->adjustmentModel
->where('class_section_id', $classSectionId)
->where('adjustable', 1);
$this->rosterPresenceCache[$key] = $cnt > 0;
return $this->rosterPresenceCache[$key];
$table = $this->adjustmentModel->getTable();
if ($schoolYear !== '' && $this->tableHasColumn($table, 'school_year')) {
$query->where('school_year', $schoolYear);
}
private function buildInventoryAvailability(string $schoolYear, string $semester, bool $limitToSemester, array $allowed): array
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);
$hasName = $this->tableHasColumn('inventory_items', 'name');
$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')
->where('ii.type', 'classroom')
->where('ii.school_year', $schoolYear)
->whereIn('ic.name', $allowed);
if ($limitToSemester && $semester !== '') {
$joinRows->where('ii.semester', $semester);
}
$joinRows = $joinRows->groupBy('ic.name')->get()->getResultArray();
foreach ($joinRows as $r) {
$name = (string)($r['item_name'] ?? '');
if ($name !== '' && isset($inventoryMap[$name])) {
$inventoryMap[$name] = max($inventoryMap[$name], (int)($r['available'] ?? 0));
$periodClauses = ['im.item_id = ii.id'];
if ($schoolYear !== '') {
$periodClauses[] = 'im.school_year = ' . $this->db->escape($schoolYear);
}
if ($semester !== '') {
$periodClauses[] = 'im.semester = ' . $this->db->escape($semester);
}
if (count($periodClauses) > 1) {
$joinRows->where(
'EXISTS (SELECT 1 FROM inventory_movements im WHERE ' . implode(' AND ', $periodClauses) . ')',
null,
false
);
}
$joinRows = $joinRows
->groupBy('ic.name')
->get()
->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')
->where('type', 'classroom')
->where('school_year', $schoolYear)
->whereIn('name', $allowed);
if ($limitToSemester && $semester !== '') {
$nameRows->where('semester', $semester);
}
$nameRows = $nameRows->groupBy('name')->get()->getResultArray();
/*
* Some older schemas store the item name directly on inventory_items.
* Only run this fallback when that column actually exists.
*/
if ($hasName) {
$nameRows = $this->db->table('inventory_items ii_name')
->select('ii_name.name AS item_name, COALESCE(SUM(CASE WHEN ii_name.good_qty IS NOT NULL THEN ii_name.good_qty WHEN ii_name.`condition` = "good" THEN ii_name.quantity ELSE 0 END), 0) AS available', false)
->where('ii_name.type', 'classroom')
->whereIn('ii_name.name', $allowed);
foreach ($nameRows as $r) {
$name = (string)($r['item_name'] ?? '');
if ($name !== '' && isset($inventoryMap[$name])) {
$inventoryMap[$name] = max($inventoryMap[$name], (int)($r['available'] ?? 0));
$fallbackPeriodClauses = ['im.item_id = ii_name.id'];
if ($schoolYear !== '') {
$fallbackPeriodClauses[] = 'im.school_year = ' . $this->db->escape($schoolYear);
}
if ($semester !== '') {
$fallbackPeriodClauses[] = 'im.semester = ' . $this->db->escape($semester);
}
if (count($fallbackPeriodClauses) > 1) {
$nameRows->where(
'EXISTS (SELECT 1 FROM inventory_movements im WHERE ' . implode(' AND ', $fallbackPeriodClauses) . ')',
null,
false
);
}
$nameRows = $nameRows
->groupBy('ii_name.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)
);
}
}
}
+10 -1
View File
@@ -62,7 +62,7 @@ class EventController extends ResourceController
$this->parentModel = new ParentModel();
$this->emailService = new EmailService();
$this->schoolYear = $this->configModel->getConfig('school_year');
$this->schoolYear = $this->currentSchoolYearName();
$this->semester = $this->configModel->getConfig('semester');
$this->categories = [
'workshops',
@@ -88,6 +88,15 @@ class EventController extends ResourceController
return $this->eventChargesHasCreatedBy;
}
private function currentSchoolYearName(): string
{
try {
return service('schoolYearContext')->resolve(service('request'))->yearName();
} catch (\Throwable $e) {
return (string) ($this->configModel->getConfig('school_year') ?? '');
}
}
private function eventChargesSupportsWaiverSigned(): bool
{
if ($this->eventChargesHasWaiverSigned !== null) {
+13 -9
View File
@@ -150,10 +150,12 @@ class FamilyAdminController extends BaseController
}
// Recent payments (limit 10)
$payRows = $db->table('payments')
->select('id, parent_id, invoice_id, paid_amount, balance, payment_method, payment_date, status')
->whereIn('parent_id', $parentIds)
->orderBy('payment_date', 'DESC')
$payRows = $db->table('payments p')
->select('p.id, p.parent_id, p.invoice_id, p.paid_amount, p.payment_method, p.payment_date, p.status AS payment_status, p.installment_seq, p.number_of_installments, i.invoice_number, i.balance AS invoice_current_balance, i.status AS invoice_status, i.school_year')
->join('invoices i', 'i.id = p.invoice_id', 'inner')
->whereIn('p.parent_id', $parentIds)
->orderBy('p.payment_date', 'DESC')
->orderBy('p.id', 'DESC')
->limit(10)
->get()->getResultArray();
$fam['payments'] = $payRows;
@@ -359,7 +361,7 @@ class FamilyAdminController extends BaseController
if ($gid > 0) $gmap[$gid] = trim(($g['firstname'] ?? '') . ' ' . ($g['lastname'] ?? ''));
}
$ecRows = $db->table('emergency_contacts')
->select('id, parent_id, emergency_contact_name, relation, cellphone, email, school_year, semester, created_at, updated_at')
->select('id, parent_id, emergency_contact_name, relation, cellphone, email, created_at, updated_at')
->whereIn('parent_id', $parentIds)
->orderBy('updated_at', 'DESC')
->get()->getResultArray();
@@ -395,10 +397,12 @@ class FamilyAdminController extends BaseController
}
// Payments
$payRows = $db->table('payments')
->select('id, parent_id, invoice_id, paid_amount, balance, payment_method, payment_date, status')
->whereIn('parent_id', $parentIds)
->orderBy('payment_date', 'DESC')
$payRows = $db->table('payments p')
->select('p.id, p.parent_id, p.invoice_id, p.paid_amount, p.payment_method, p.payment_date, p.status AS payment_status, p.installment_seq, p.number_of_installments, i.invoice_number, i.balance AS invoice_current_balance, i.status AS invoice_status, i.school_year')
->join('invoices i', 'i.id = p.invoice_id', 'inner')
->whereIn('p.parent_id', $parentIds)
->orderBy('p.payment_date', 'DESC')
->orderBy('p.id', 'DESC')
->limit(10)
->get()->getResultArray();
$family['payments'] = $payRows;
+68 -43
View File
@@ -21,6 +21,60 @@ class FinancialController extends BaseController
return $this->request->isAJAX() || str_contains($accept, 'application/json');
}
private function selectedSchoolYear(): string
{
$requested = trim((string) ($this->request->getGet('school_year') ?? ''));
if ($requested !== '') {
return $requested;
}
return $this->currentSchoolYearName();
}
private function financialSchoolYearOptions(?string $selectedYear = null): array
{
$schoolYears = [];
$addYear = static function (mixed $value) use (&$schoolYears): void {
$year = trim((string) $value);
if ($year !== '' && ! in_array($year, $schoolYears, true)) {
$schoolYears[] = $year;
}
};
$addYear($selectedYear);
$addYear($this->currentSchoolYearName());
try {
$db = \Config\Database::connect();
if ($db->tableExists('school_years')) {
$rows = $db->table('school_years')
->select('name')
->orderBy('name', 'DESC')
->get()
->getResultArray();
foreach ($rows as $row) {
$addYear($row['name'] ?? '');
}
}
if ($db->tableExists('invoices') && $db->fieldExists('school_year', 'invoices')) {
$rows = $db->table('invoices')
->select('DISTINCT school_year', false)
->where('school_year IS NOT NULL', null, false)
->orderBy('school_year', 'DESC')
->get()
->getResultArray();
foreach ($rows as $row) {
$addYear($row['school_year'] ?? '');
}
}
} catch (\Throwable $e) {
}
return $schoolYears;
}
public function financialReport()
{
$invoiceModel = new InvoiceModel();
@@ -32,7 +86,7 @@ public function financialReport()
$dateFrom = $this->request->getGet('date_from');
$dateTo = $this->request->getGet('date_to');
$schoolYear = $this->request->getGet('school_year');
$schoolYear = $this->selectedSchoolYear();
// === Apply filters to models (invoice/refund/discount/expense/reimb) ===
if ($schoolYear) {
@@ -235,22 +289,7 @@ public function financialReport()
->findAll();
// --- School year options (for detailed view & JSON) ---
$schoolYears = [];
try {
$db = \Config\Database::connect();
$rows = $db->table('invoices')
->select('DISTINCT school_year', false)
->where('school_year IS NOT NULL', null, false)
->orderBy('school_year', 'DESC')
->get()->getResultArray();
foreach ($rows as $r) {
$val = (string)($r['school_year'] ?? '');
if ($val !== '' && !in_array($val, $schoolYears, true)) $schoolYears[] = $val;
}
} catch (\Throwable $e) {}
if (empty($schoolYears) && !empty($schoolYear)) {
$schoolYears[] = (string)$schoolYear;
}
$schoolYears = $this->financialSchoolYearOptions($schoolYear);
$eventFeesTotal = $this->getEventFeesTotal($schoolYear, $dateFrom, $dateTo);
@@ -298,28 +337,11 @@ public function financialReport()
{
$dateFrom = $this->request->getGet('date_from');
$dateTo = $this->request->getGet('date_to');
$schoolYear = $this->request->getGet('school_year');
$schoolYear = $this->selectedSchoolYear();
$data = $this->getFinancialSummary($dateFrom, $dateTo, $schoolYear);
// Build school year options from invoices table (fallback to configured year)
$schoolYears = [];
try {
$db = \Config\Database::connect();
$rows = $db->table('invoices')
->select('DISTINCT school_year', false)
->where('school_year IS NOT NULL', null, false)
->orderBy('school_year', 'DESC')
->get()->getResultArray();
foreach ($rows as $r) {
$val = (string)($r['school_year'] ?? '');
if ($val !== '' && !in_array($val, $schoolYears, true)) $schoolYears[] = $val;
}
} catch (\Throwable $e) {}
if (empty($schoolYears) && !empty($data['schoolYear'])) {
$schoolYears[] = (string)$data['schoolYear'];
}
$data['schoolYears'] = $schoolYears;
$data['schoolYears'] = $this->financialSchoolYearOptions((string)($data['schoolYear'] ?? $schoolYear));
if ($this->wantsJson() || strtolower((string)($this->request->getGet('format') ?? '')) === 'json') {
return $this->response->setJSON(['ok' => true] + $data + [
'csrf_token' => csrf_token(),
@@ -524,7 +546,7 @@ public function financialReport()
private function getFinancialSummaryDetailSections(?string $dateFrom = null, ?string $dateTo = null, ?string $schoolYear = null): array
{
$configModel = new \App\Models\ConfigurationModel();
$schoolYear = $schoolYear ?: $configModel->getConfig('school_year');
$schoolYear = $schoolYear ?: $this->currentSchoolYearName();
$derivedDateFrom = null;
$derivedDateTo = null;
@@ -658,10 +680,10 @@ public function financialReport()
}, $discountDetailsBuilder->orderBy('du.id', 'ASC')->get()->getResultArray());
$paymentDetailsBuilder = $db->table('payments p')
->select("p.id, p.invoice_id, p.parent_id, p.paid_amount, p.payment_method, p.payment_date, p.status, p.transaction_id, p.check_number, i.invoice_number, CONCAT(COALESCE(u.firstname, ''), ' ', COALESCE(u.lastname, '')) AS parent_name")
->join('invoices i', 'i.id = p.invoice_id', 'left')
->select("p.id, p.invoice_id, p.parent_id, p.paid_amount, p.payment_method, p.payment_date, p.status AS payment_status, p.transaction_id, p.check_number, i.invoice_number, i.balance AS invoice_current_balance, i.status AS invoice_status, i.school_year, CONCAT(COALESCE(u.firstname, ''), ' ', COALESCE(u.lastname, '')) AS parent_name")
->join('invoices i', 'i.id = p.invoice_id', 'inner')
->join('users u', 'u.id = p.parent_id', 'left')
->where('p.school_year', $schoolYear)
->where('i.school_year', $schoolYear)
->groupStart()
->whereNotIn('p.status', $paymentExclude)
->orWhere('p.status IS NULL', null, false)
@@ -677,9 +699,12 @@ public function financialReport()
'Parent' => trim((string)($row['parent_name'] ?? '')),
'Invoice #' => (string)($row['invoice_number'] ?? ''),
'Paid Amount' => (float)($row['paid_amount'] ?? 0),
'Invoice Balance' => (float)($row['invoice_current_balance'] ?? 0),
'Payment Method' => (string)($row['payment_method'] ?? ''),
'Payment Date' => (string)($row['payment_date'] ?? ''),
'Status' => (string)($row['status'] ?? ''),
'Payment Status' => (string)($row['payment_status'] ?? ''),
'Invoice Status' => (string)($row['invoice_status'] ?? ''),
'School Year' => (string)($row['school_year'] ?? ''),
'Transaction ID' => (string)($row['transaction_id'] ?? ''),
'Check Number' => (string)($row['check_number'] ?? ''),
];
@@ -1609,7 +1634,7 @@ public function financialReport()
$additionalModel = new \App\Models\AdditionalChargeModel();
// Allow override via parameter; fallback to configured year
$schoolYear = $schoolYear ?: $configModel->getConfig('school_year');
$schoolYear = $schoolYear ?: $this->currentSchoolYearName();
$derivedDateFrom = null;
$derivedDateTo = null;
if (!empty($schoolYear) && empty($dateFrom) && empty($dateTo)) {
@@ -2065,7 +2090,7 @@ public function financialReport()
$configModel = new \App\Models\ConfigurationModel();
$schoolYear = trim((string)($this->request->getGet('school_year') ?? ''));
if ($schoolYear === '') {
$schoolYear = (string) ($configModel->getConfig('school_year') ?? date('Y'));
$schoolYear = $this->currentSchoolYearName((string) ($configModel->getConfig('school_year') ?? date('Y')));
}
// Build school year options from invoices
+4 -1
View File
@@ -35,8 +35,11 @@ class FlagController extends Controller
$grades = [];
// Retrieve flags and class sections that currently have active students
$flags = $currentFlagModel->findAll();
$schoolYear = $configModel->getConfig('school_year');
if ((string)$schoolYear !== '' && $this->db->fieldExists('school_year', 'current_flag')) {
$currentFlagModel->where('school_year', (string)$schoolYear);
}
$flags = $currentFlagModel->findAll();
$studentCounts = $studentClassModel->getStudentCountsBySection($schoolYear);
$classSections = [];
+1 -6
View File
@@ -706,7 +706,6 @@ class GradingController extends Controller
$existing = $this->placementLevelModel
->where('student_id', $studentId)
->where('school_year', $schoolYear)
->first();
if ($level === null) {
@@ -718,7 +717,6 @@ class GradingController extends Controller
$payload = [
'student_id' => $studentId,
'school_year' => $schoolYear,
'level' => $level,
'updated_by' => session()->get('user_id'),
];
@@ -768,7 +766,6 @@ class GradingController extends Controller
if (!empty($studentIds)) {
$rows = $this->placementLevelModel
->whereIn('student_id', $studentIds)
->where('school_year', $schoolYear)
->findAll();
foreach ($rows as $row) {
$levels[(int) $row['student_id']] = $row['level'] ?? null;
@@ -806,7 +803,6 @@ class GradingController extends Controller
if (!empty($validIds)) {
$rows = $this->placementLevelModel
->whereIn('student_id', $validIds)
->where('school_year', $schoolYear)
->findAll();
foreach ($rows as $row) {
$existingRows[(int) $row['student_id']] = $row;
@@ -834,7 +830,6 @@ class GradingController extends Controller
$payload = [
'student_id' => $studentId,
'school_year' => $schoolYear,
'level' => $level,
'updated_by' => $userId,
];
@@ -1648,7 +1643,7 @@ public function belowSixty()
->join('students s', 's.id = sc.student_id', 'inner')
->join(
'placement_levels pl',
"pl.student_id = s.id AND pl.school_year = {$yrEsc}",
'pl.student_id = s.id',
'left'
)
+47 -18
View File
@@ -75,12 +75,7 @@ class InventoryController extends BaseController
$selectedSem = $selectedSemRaw === null ? (string) $this->semester : trim((string) $selectedSemRaw);
$builder = $this->itemModel->where('type', $type);
if (strtolower($selectedYear) !== 'all') {
$builder->where('school_year', $selectedYear);
}
if ($selectedSem !== '') {
$builder->where('semester', $selectedSem);
}
$this->applyInventoryMovementPeriodFilter($builder, 'inventory_items', $selectedYear, $selectedSem);
$items = $builder->orderBy('name', 'ASC')->findAll();
$categories = $this->catModel->optionsForType($type);
@@ -474,17 +469,26 @@ class InventoryController extends BaseController
// Distinct school years for a given inventory type (newest first).
private function getSchoolYearsForType(string $type): array
{
// Pull distinct non-null school_year values for this type
$years = $this->itemModel
->select('school_year')
->where('type', $type)
->where('school_year IS NOT NULL', null, false)
->groupBy('school_year')
->orderBy('school_year', 'DESC')
->findColumn('school_year') ?? [];
$rows = $this->db->table('inventory_movements m')
->distinct()
->select('m.school_year')
->join('inventory_items i', 'i.id = m.item_id', 'inner')
->where('m.school_year IS NOT NULL', null, false)
->where("TRIM(m.school_year) <>", '')
->orderBy('m.school_year', 'DESC');
if (strtolower($type) !== 'all') {
$rows->where('i.type', $type);
}
$rows = $rows->get()
->getResultArray();
// Normalize & de-dup
$years = array_values(array_unique(array_filter(array_map('trim', $years))));
$years = array_values(array_unique(array_filter(array_map(
static fn(array $row): string => trim((string)($row['school_year'] ?? '')),
$rows
))));
// Ensure the current year (from config) appears as an option, even if no rows yet
$currentYear = $this->schoolYear;
@@ -496,6 +500,31 @@ class InventoryController extends BaseController
return $years;
}
private function applyInventoryMovementPeriodFilter($builder, string $itemAlias, ?string $schoolYear, ?string $semester = null): void
{
$schoolYear = trim((string) $schoolYear);
$semester = trim((string) $semester);
$clauses = ["m.item_id = {$itemAlias}.id"];
if ($schoolYear !== '' && strtolower($schoolYear) !== 'all') {
$clauses[] = 'm.school_year = ' . $this->db->escape($schoolYear);
}
if ($semester !== '') {
$clauses[] = 'm.semester = ' . $this->db->escape($semester);
}
if (count($clauses) <= 1) {
return;
}
$builder->where(
'EXISTS (SELECT 1 FROM inventory_movements m WHERE ' . implode(' AND ', $clauses) . ')',
null,
false
);
}
private function recordMovement(
int $itemId,
int $qtyChange,
@@ -1095,7 +1124,7 @@ class InventoryController extends BaseController
// Filter by school year unless "all"
if (!$isAllYears) {
$qbItems->where('i.school_year', $selectedYear);
$this->applyInventoryMovementPeriodFilter($qbItems, 'i', $selectedYear);
}
// Optional: filter by type if provided
@@ -1123,7 +1152,7 @@ class InventoryController extends BaseController
return view('inventory/summary', [
'selectedYear' => $selectedYear,
'currentYear' => $this->schoolYear,
'schoolYears' => $this->getSchoolYearsForType('book') ?: [$this->schoolYear, 'All'],
'schoolYears' => $this->getSchoolYearsForType($selectedType) ?: [$this->schoolYear, 'All'],
'rows' => $rows,
'totals' => $totals,
// optionally pass the selected type if your view supports it
@@ -1202,7 +1231,7 @@ class InventoryController extends BaseController
}
// -------- Year dropdown options --------
$schoolYears = $this->getSchoolYearsForType('book') ?: [$this->schoolYear, 'All'];
$schoolYears = $this->getSchoolYearsForType($selectedType) ?: [$this->schoolYear, 'All'];
return view('inventory/summary', [
'selectedYear' => $selectedYear,
+13 -4
View File
@@ -67,17 +67,17 @@ class InvoiceController extends ResourceController
$this->chargesModel = new EventChargesModel();
$this->discountUsageModel = new DiscountUsageModel();
$this->refundModel = new RefundModel();
$this->db = \Config\Database::connect();
$this->request = \Config\Services::request();
$this->gradeFee = $this->configModel->getConfig('grade_fee');
$this->schoolYear = $this->configModel->getConfig('school_year');
$this->schoolYear = $this->currentSchoolYearName();
$this->semester = $this->configModel->getConfig('semester');
$this->dueDate = $this->configModel->getConfig('due_date');
$this->firstStudentFee = (float) ($this->configModel->getConfig('first_student_fee') ?? 350);
$this->secondStudentFee = (float) ($this->configModel->getConfig('second_student_fee') ?? 200);
$this->youthFee = (float) ($this->configModel->getConfig('youth_fee') ?? 200);
$this->refundDeadline = date('Y-m-d', strtotime($this->configModel->getConfig('refund_deadline')));
$this->db = \Config\Database::connect();
$this->request = \Config\Services::request();
}
public function index($schoolYear = null)
@@ -213,6 +213,15 @@ class InvoiceController extends ResourceController
]);
}
private function currentSchoolYearName(): string
{
try {
return service('schoolYearContext')->resolve($this->request)->yearName();
} catch (\Throwable $e) {
return (string) ($this->configModel->getConfig('school_year') ?? '');
}
}
/**
* API: Invoice management composite data (used by invoice_management view)
* Returns the same structure previously rendered server-side in index().
@@ -221,7 +230,7 @@ class InvoiceController extends ResourceController
{
$schoolYear = trim((string)($this->request->getGet('schoolYear') ?? $this->request->getGet('year') ?? ''));
if ($schoolYear === '') {
$schoolYear = $this->schoolYear;
$schoolYear = $this->currentSchoolYearName();
}
$invoiceData = [];
@@ -21,7 +21,7 @@ class LateSlipLogsController extends BaseController
{
$req = $this->request;
$defaultYear = (string) ($this->configModel->getConfig('school_year') ?? '');
$defaultYear = $this->currentSchoolYearName((string) ($this->schoolYear ?? ''));
$defaultSem = (string) ($this->configModel->getConfig('semester') ?? '');
$schoolYear = trim((string) ($req->getGet('school_year') ?? $defaultYear));
$semester = trim((string) ($req->getGet('semester') ?? $defaultSem));
@@ -149,6 +149,11 @@ class NotificationsController extends BaseController
$targetGroup = null;
}
$schoolYear = (string) ((new \App\Models\ConfigurationModel())->getConfig('school_year') ?? '');
if ($schoolYear !== '' && db_connect()->fieldExists('school_year', 'notifications')) {
$this->notificationModel->where('school_year', $schoolYear);
}
$rows = $this->notificationModel->getActiveNotifications($targetGroup);
if (!is_array($rows)) {
$rows = [];
+2 -7
View File
@@ -164,8 +164,7 @@ class ParentController extends BaseController
return redirect()->back()->with('error', 'Parent session not found.');
}
// Get current school year from config
$currentSchoolYear = $this->configModel->getConfig('school_year');
$currentSchoolYear = $this->currentSchoolYearName((string) ($this->schoolYear ?? ''));
// Get selected school year (no semester filter on parent view)
$selectedYear = $this->request->getVar('school_year') ?? $currentSchoolYear;
@@ -1487,8 +1486,6 @@ $existing = $this->studentModel
'cellphone' => $phone,
'email' => $email,
'relation' => $relation,
'semester' => $semester,
'school_year' => $schoolYear,
'updated_at' => utc_now(),
];
@@ -1568,8 +1565,6 @@ $existing = $this->studentModel
'cellphone' => $phone,
'email' => $email,
'relation' => $relation,
'semester' => $semester,
'school_year' => $schoolYear,
]);
}
}
@@ -1788,7 +1783,7 @@ $existing = $this->studentModel
public function parentEventPage()
{
$schoolYear = session()->get('school_year');
$schoolYear = $this->currentSchoolYearName((string) ($this->schoolYear ?? ''));
$semester = session()->get('semester');
$parentId = session()->get('user_id');
+31 -23
View File
@@ -63,7 +63,7 @@ class PaymentController extends ResourceController
$this->enrollmentModel = new EnrollmentModel();
$this->studentModel = new StudentModel();
$this->studentClassModel = new StudentClassModel();
$this->schoolYear = $this->configModel->getConfig('school_year');
$this->schoolYear = $this->currentSchoolYearName();
$this->semester = $this->configModel->getConfig('semester'); //installment_date
$this->installmentDate = $this->configModel->getConfig('installment_date');
$this->discountUsageModel = new DiscountUsageModel();
@@ -85,7 +85,6 @@ class PaymentController extends ResourceController
'payment_date' => $this->request->getPost('payment_date'),
'payment_type' => $this->request->getPost('payment_type'),
'status' => 'Pending',
'semester' => $this->request->getPost('semester'),
'school_year' => $this->request->getPost('school_year'),
];
@@ -99,7 +98,8 @@ class PaymentController extends ResourceController
// API: Get payments by parent ID
public function getByParentAPI($parentId)
{
$payments = $this->paymentModel->getPaymentsByParentId($parentId);
$selectedYear = $this->getSelectedPaymentHistoryYear();
$payments = $this->paymentModel->getPaymentsByParentId((int) $parentId, $selectedYear);
if ($payments) {
return $this->respond($payments);
} else {
@@ -110,13 +110,8 @@ class PaymentController extends ResourceController
// View: Get payments by parent ID (for web views)
public function getByParent($parentId)
{
// Fetch payments with invoice number (if available)
$payments = $this->paymentModel
->select('payments.*, invoices.invoice_number')
->join('invoices', 'invoices.id = payments.invoice_id', 'left')
->where('payments.parent_id', (int)$parentId)
->orderBy('payments.payment_date', 'DESC')
->findAll();
$selectedYear = $this->getSelectedPaymentHistoryYear();
$payments = $this->paymentModel->getPaymentsByParentId((int) $parentId, $selectedYear);
// Parent display name
$parent = $this->userModel->select('firstname, lastname')->find((int)$parentId) ?: [];
@@ -140,6 +135,22 @@ class PaymentController extends ResourceController
]);
}
private function getSelectedPaymentHistoryYear(): ?string
{
$selectedYear = $this->request->getGet('school_year') ?? $this->currentSchoolYearName();
return $selectedYear !== '' ? $selectedYear : null;
}
private function currentSchoolYearName(): string
{
try {
return service('schoolYearContext')->resolve($this->request)->yearName();
} catch (\Throwable $e) {
return (string) ($this->configModel->getConfig('school_year') ?? '');
}
}
// View: Create a new payment plan
public function create()
{
@@ -202,7 +213,7 @@ class PaymentController extends ResourceController
public function eventChargesShow()
{
$parents = $this->userModel->getParents();
$school_Year = $this->request->getGet('school_year') ?? $this->schoolYear;
$school_Year = $this->request->getGet('school_year') ?? $this->currentSchoolYearName();
$seme_ster = $this->request->getGet('semester') ?? $this->semester;
// Join with users and students for full info
@@ -346,12 +357,12 @@ class PaymentController extends ResourceController
->where('parent_id', $parentId)
->findAll();
// Payments (paginated)
$payments = $this->paymentModel
->where('parent_id', $parentId)
->orderBy('payment_date', 'DESC')
->paginate(10);
$pager = $this->paymentModel->pager;
// Payments (paginated). Join invoices so history is filtered by invoice term
// and displays current invoice state instead of stale payment snapshots.
$selectedYear = $this->getSelectedPaymentHistoryYear();
$paymentHistory = $this->paymentModel->parentPaymentHistoryQuery($parentId, $selectedYear);
$payments = $paymentHistory->paginate(10);
$pager = $paymentHistory->pager;
// Invoices
$rawInvoices = $this->invoiceModel
@@ -972,8 +983,7 @@ class PaymentController extends ResourceController
$checkFile,
$transactionId,
$paymentDate,
$this->schoolYear,
$this->semester,
$invYear,
$checkNumber,
$installmentSeq,
(array) $this->invoiceModel->find($invoiceId),
@@ -1015,7 +1025,7 @@ class PaymentController extends ResourceController
$rowParentDisc = $this->db->table('discount_usages')
->selectSum('discount_amount', 'sum_disc')
->where('parent_id', $parentId)
->where('school_year', $this->schoolYear)
->where('school_year', $invYear)
->get()->getRowArray();
if ($rowParentDisc && isset($rowParentDisc['sum_disc'])) {
$parentYearDiscountTotal = (float)$rowParentDisc['sum_disc'];
@@ -1270,7 +1280,6 @@ class PaymentController extends ResourceController
$transactionId = null,
$paymentDate = null,
$schoolYear = null,
$semester = null,
$checkNumber = null,
?int $installmentSeq = null,
?array $invoice = null,
@@ -1315,8 +1324,7 @@ class PaymentController extends ResourceController
'check_file' => $checkFile,
'check_number' => (strtolower($paymentMethod) === 'check') ? $checkNumber : null,
'updated_by' => session()->get('user_id'),
'school_year' => $schoolYear ?? $this->schoolYear,
'semester' => $semester ?? $this->semester,
'school_year' => $schoolYear ?? ($invoice['school_year'] ?? $this->schoolYear),
];
if (!$this->paymentModel->insert($paymentData)) {
@@ -1235,6 +1235,10 @@ public function updateBatchAssignment()
$status = $this->request->getGet('status') ?: null;
$filterYear = $this->request->getGet('school_year') ?: $this->schoolYear;
$userId = $this->request->getGet('user_id') ?: null;
$hasBatchSchoolYear = $this->db->fieldExists('school_year', 'reimbursement_batches');
$hasExpenseSchoolYear = $this->db->fieldExists('school_year', 'expenses');
$hasExpenseSemester = $this->db->fieldExists('semester', 'expenses');
$hasReimbursementSchoolYear = $this->db->fieldExists('school_year', 'reimbursements');
$filters = [
'school_year' => $filterYear,
@@ -1251,13 +1255,11 @@ public function updateBatchAssignment()
// Build closed batch summaries/details (all closed batches)
$batchSummaries = [];
$batchDetails = [];
$batchQuery = $this->db->table('reimbursement_batches b')
->select("
$batchSelect = "
b.id AS batch_id,
b.title AS batch_title,
b.yearly_batch_number,
b.closed_at,
b.school_year AS batch_school_year,
e.id AS expense_id,
e.amount AS expense_amount,
e.description,
@@ -1268,7 +1270,13 @@ public function updateBatchAssignment()
u.firstname AS purchaser_firstname,
u.lastname AS purchaser_lastname,
r.amount AS reimb_amount
")
";
if ($hasBatchSchoolYear) {
$batchSelect .= ', b.school_year AS batch_school_year';
}
$batchQuery = $this->db->table('reimbursement_batches b')
->select($batchSelect)
->join('reimbursement_batch_items bi', 'bi.batch_id = b.id', 'inner')
->join('expenses e', 'e.id = bi.expense_id', 'inner')
->join('users u', 'u.id = e.purchased_by', 'left')
@@ -1277,10 +1285,16 @@ public function updateBatchAssignment()
->where('bi.unassigned_at IS NULL', null, false);
if (!empty($filterYear)) {
if ($hasBatchSchoolYear && $hasExpenseSchoolYear) {
$batchQuery->groupStart()
->where('b.school_year', $filterYear)
->orWhere('e.school_year', $filterYear)
->groupEnd();
} elseif ($hasBatchSchoolYear) {
$batchQuery->where('b.school_year', $filterYear);
} elseif ($hasExpenseSchoolYear) {
$batchQuery->where('e.school_year', $filterYear);
}
}
if (!empty($userId)) {
$batchQuery->where('e.purchased_by', $userId);
@@ -1401,27 +1415,33 @@ public function updateBatchAssignment()
'items' => [],
'checks' => [],
];
$donationQuery = $this->db->table('expenses e')
->select('
$donationSelect = '
e.id AS expense_id,
e.amount AS expense_amount,
e.description,
e.retailor,
e.receipt_path AS expense_receipt,
e.purchased_by,
e.school_year,
e.semester,
e.status,
u.firstname AS purchaser_firstname,
u.lastname AS purchaser_lastname
')
';
if ($hasExpenseSchoolYear) {
$donationSelect .= ', e.school_year';
}
if ($hasExpenseSemester) {
$donationSelect .= ', e.semester';
}
$donationQuery = $this->db->table('expenses e')
->select($donationSelect)
->join('users u', 'u.id = e.purchased_by', 'left')
->where('e.category', 'Donation');
if (!empty($filterYear)) {
if (!empty($filterYear) && $hasExpenseSchoolYear) {
$donationQuery->where('e.school_year', $filterYear);
}
if (!empty($semester)) {
if (!empty($semester) && $hasExpenseSemester) {
$donationQuery->where('e.semester', $semester);
}
if (!empty($userId)) {
@@ -1488,6 +1508,8 @@ public function updateBatchAssignment()
$users = $this->recipientOptions();
$schoolYears = [];
if ($hasReimbursementSchoolYear) {
$years = $this->db->table('reimbursements')
->select('school_year')
->distinct()
@@ -1495,6 +1517,16 @@ public function updateBatchAssignment()
->get()
->getResultArray();
$schoolYears = array_column($years, 'school_year');
} elseif ($hasExpenseSchoolYear) {
$years = $this->db->table('expenses')
->select('school_year')
->distinct()
->where('school_year IS NOT NULL', null, false)
->orderBy('school_year', 'DESC')
->get()
->getResultArray();
$schoolYears = array_column($years, 'school_year');
}
// Add school years from fallback expenses (closed batches without reimbursements)
if (!empty($fallbackRows)) {
@@ -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,84 @@
<?php
namespace App\Controllers\View;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\RedirectResponse;
final class SchoolYearSelectionController extends BaseController
{
public function select(): RedirectResponse
{
$schoolYearId = (int) ($this->request->getPost('school_year_id') ?? 0);
$returnTo = (string) ($this->request->getPost('return_to') ?? '');
if ($schoolYearId <= 0) {
return redirect()->to($this->safeReturnTo($returnTo))
->with('error', 'Please select a valid school year.');
}
try {
service('schoolYearContext')->select($schoolYearId);
return redirect()->to($this->safeReturnTo($returnTo));
} catch (\Throwable $e) {
log_message('warning', 'School-year selection failed: {message}', [
'message' => $e->getMessage(),
]);
return redirect()->to($this->safeReturnTo($returnTo))
->with('error', 'The selected school year is not available.');
}
}
public function reset(): RedirectResponse
{
service('schoolYearContext')->clearSelection();
return redirect()->to($this->safeReturnTo((string) ($this->request->getPost('return_to') ?? '')));
}
private function safeReturnTo(string $returnTo): string
{
$fallback = $this->dashboardRoute();
$returnTo = trim($returnTo);
if ($returnTo === '') {
return $fallback;
}
$parts = parse_url($returnTo);
if ($parts === false) {
return $fallback;
}
if (isset($parts['host']) && strcasecmp((string) $parts['host'], (string) $this->request->getUri()->getHost()) !== 0) {
return $fallback;
}
$path = '/' . ltrim((string) ($parts['path'] ?? ''), '/');
if ($path === '/' || str_starts_with($path, '//')) {
return $fallback;
}
$query = [];
if (! empty($parts['query'])) {
parse_str((string) $parts['query'], $query);
foreach (['school_year_id', 'school_year', 'schoolYear', 'year'] as $key) {
unset($query[$key]);
}
}
$cleanQuery = http_build_query($query);
return $path . ($cleanQuery !== '' ? '?' . $cleanQuery : '');
}
private function dashboardRoute(): string
{
try {
return service('roleService')->bestDashboardRouteFor((array) session()->get('roles'));
} catch (\Throwable) {
return '/landing_page/guest_dashboard';
}
}
}
+45 -11
View File
@@ -2,12 +2,11 @@
namespace App\Controllers\View;
use App\Controllers\BaseController;
use App\Models\ConfigurationModel;
use App\Models\ClassSectionModel;
use CodeIgniter\Controller;
class ScorePredictor extends Controller
class ScorePredictor extends BaseController
{
protected $db;
protected $configModel;
@@ -60,17 +59,30 @@ class ScorePredictor extends Controller
public function combinedReport()
{
$request = service('request');
$currentSchoolYear = $this->schoolYear;
$currentSchoolYear = $this->currentSchoolYearName((string) ($this->schoolYear ?? ''));
$selectedYear = $request->getVar('school_year') ?? $currentSchoolYear;
$classSectionId = $request->getVar('class_section_id');
$yearEsc = $this->db->escape($selectedYear);
$acceptedEnrollmentStatuses = ['payment pending', 'enrolled'];
// Only show class sections that have at least one student in the selected year
$classSections = $this->db->table('classSection cs')
->select('cs.*')
->distinct()
->join('student_class sc', 'sc.class_section_id = cs.class_section_id', 'inner')
->join('enrollments e', 'e.student_id = sc.student_id AND e.school_year = ' . $yearEsc, 'inner')
->where('sc.school_year', $selectedYear)
->whereIn('e.enrollment_status', $acceptedEnrollmentStatuses)
->where('e.admission_status', 'accepted')
->groupStart()
->where('e.is_withdrawn', 0)
->orWhere('e.is_withdrawn', null)
->groupEnd()
->groupStart()
->where('sc.is_event_only', 0)
->orWhere('sc.is_event_only', null)
->groupEnd()
->notLike('cs.class_section_name', 'KG', 'after')
->groupBy('cs.id')
->orderBy('cs.class_section_name', 'ASC')
->get()
->getResultArray();
@@ -85,12 +97,23 @@ class ScorePredictor extends Controller
MAX(spring.semester_score) as spring_score');
// Reduce duplication from restored students while keeping a stable class section.
$builder->select('MAX(sc.class_section_id) as class_section_id');
$yearEsc = $this->db->escape($selectedYear);
$builder->join('student_class sc', 'sc.student_id = s.id AND sc.school_year = ' . $yearEsc, 'left');
$builder->join('student_class sc', 'sc.student_id = s.id AND sc.school_year = ' . $yearEsc, 'inner');
$builder->join('enrollments e', 'e.student_id = s.id AND e.school_year = ' . $yearEsc, 'inner');
$builder->join('classSection cs', 'cs.class_section_id = sc.class_section_id', 'left');
$builder->join('semester_scores fall', 'fall.student_id = s.id AND fall.semester = "fall" AND fall.school_year = "' . $selectedYear . '"', 'left');
$builder->join('semester_scores spring', 'spring.student_id = s.id AND spring.semester = "spring" AND spring.school_year = "' . $selectedYear . '"', 'left');
$builder->join('semester_scores fall', 'fall.student_id = s.id AND fall.semester = "fall" AND fall.school_year = ' . $yearEsc, 'left');
$builder->join('semester_scores spring', 'spring.student_id = s.id AND spring.semester = "spring" AND spring.school_year = ' . $yearEsc, 'left');
$builder->where('s.is_active', 1);
$builder->where('sc.class_section_id IS NOT NULL', null, false);
$builder->whereIn('e.enrollment_status', $acceptedEnrollmentStatuses);
$builder->where('e.admission_status', 'accepted');
$builder->groupStart()
->where('e.is_withdrawn', 0)
->orWhere('e.is_withdrawn', null)
->groupEnd();
$builder->groupStart()
->where('sc.is_event_only', 0)
->orWhere('sc.is_event_only', null)
->groupEnd();
$builder->groupStart()
->where('cs.class_section_name IS NULL')
->orNotLike('cs.class_section_name', 'KG', 'after')
@@ -106,11 +129,22 @@ class ScorePredictor extends Controller
// Stats for spring
$springStatsQuery = $this->db->table('semester_scores')
->select('AVG(semester_scores.semester_score) as mean, STDDEV(semester_scores.semester_score) as std')
->join('student_class', 'student_class.student_id = semester_scores.student_id')
->join('student_class', 'student_class.student_id = semester_scores.student_id AND student_class.school_year = ' . $yearEsc)
->join('enrollments e', 'e.student_id = semester_scores.student_id AND e.school_year = ' . $yearEsc, 'inner')
->join('classSection cs', 'cs.class_section_id = student_class.class_section_id', 'left')
->where('semester_scores.semester', 'spring')
->where('semester_scores.school_year', $selectedYear)
->where('student_class.school_year', $selectedYear)
->where('student_class.class_section_id IS NOT NULL', null, false)
->whereIn('e.enrollment_status', $acceptedEnrollmentStatuses)
->where('e.admission_status', 'accepted')
->groupStart()
->where('e.is_withdrawn', 0)
->orWhere('e.is_withdrawn', null)
->groupEnd()
->groupStart()
->where('student_class.is_event_only', 0)
->orWhere('student_class.is_event_only', null)
->groupEnd()
->groupStart()
->where('cs.class_section_name IS NULL')
->orNotLike('cs.class_section_name', 'KG', 'after')
+27 -16
View File
@@ -386,21 +386,8 @@ class StudentController extends BaseController
{
$schoolYear = (string)($this->schoolYear ?? '');
$activeStudents = $this->studentModel
->select('id, school_id, firstname, lastname, gender, age')
->where('is_active', 1)
->orderBy('lastname', 'ASC')
->orderBy('firstname', 'ASC')
->findAll();
$removedStudents = $this->studentModel
->select('id, school_id, firstname, lastname, gender, age')
->where('is_active', 0)
->orderBy('lastname', 'ASC')
->orderBy('firstname', 'ASC')
->findAll();
$classMap = [];
$activeYearStudentIds = [];
$classQuery = $this->db->table('student_class sc')
->select('sc.student_id, cs.class_section_name')
->join('classSection cs', 'cs.class_section_id = sc.class_section_id', 'left');
@@ -411,11 +398,35 @@ class StudentController extends BaseController
foreach ($classRows as $row) {
$sid = (int)($row['student_id'] ?? 0);
if ($sid > 0) {
$activeYearStudentIds[$sid] = true;
}
$name = trim((string)($row['class_section_name'] ?? ''));
if ($sid <= 0 || $name === '') continue;
$classMap[$sid][] = $name;
}
$students = $this->studentModel
->select('id, school_id, firstname, lastname, gender, age, is_active')
->orderBy('lastname', 'ASC')
->orderBy('firstname', 'ASC')
->findAll();
$activeStudents = [];
$removedStudents = [];
foreach ($students as $student) {
$studentId = (int)($student['id'] ?? 0);
$isGloballyActive = (int)($student['is_active'] ?? 0) === 1;
$hasSelectedYearClass = $studentId > 0 && isset($activeYearStudentIds[$studentId]);
if ($isGloballyActive && $hasSelectedYearClass) {
$activeStudents[] = $student;
} else {
$removedStudents[] = $student;
}
}
$attachClassNames = static function (array $students) use ($classMap): array {
foreach ($students as &$student) {
$sid = (int)($student['id'] ?? 0);
@@ -432,6 +443,7 @@ class StudentController extends BaseController
'active_students' => $attachClassNames($activeStudents),
'removed_students' => $attachClassNames($removedStudents),
'school_year' => $schoolYear,
'active_school_year' => (string)($this->schoolYear ?? ''),
]);
}
@@ -1671,8 +1683,7 @@ class StudentController extends BaseController
->findAll();
}
} elseif (in_array($role, ['teacher', 'teacher_assistant', 'teacher_dashboard'], true)) {
$configModel = new \App\Models\ConfigurationModel();
$schoolYear = session()->get('school_year') ?? $configModel->getConfig('school_year');
$schoolYear = $this->currentSchoolYearName((string) ($this->schoolYear ?? ''));
$classSectionId = (int)(session()->get('class_section_id') ?? 0);
if ($classSectionId > 0 && !empty($schoolYear)) {
+3 -3
View File
@@ -20,7 +20,7 @@ class TrophyController extends BaseController
{
$db = \Config\Database::connect();
$currentYear = $this->configModel->getConfig('school_year') ?? '';
$currentYear = $this->currentSchoolYearName();
$selectedYear = $this->request->getGet('school_year') ?? $currentYear;
$percentile = (float) ($this->request->getGet('percentile') ?? 75);
@@ -166,7 +166,7 @@ class TrophyController extends BaseController
{
$db = \Config\Database::connect();
$currentYear = $this->configModel->getConfig('school_year') ?? '';
$currentYear = $this->currentSchoolYearName();
$selectedYear = $this->request->getGet('school_year') ?? $currentYear;
$percentile = (float) ($this->request->getGet('percentile') ?? 75);
$percentile = max(1.0, min(99.0, $percentile));
@@ -283,7 +283,7 @@ class TrophyController extends BaseController
{
$db = \Config\Database::connect();
$currentYear = $this->configModel->getConfig('school_year') ?? '';
$currentYear = $this->currentSchoolYearName();
$selectedYear = $this->request->getGet('school_year') ?? $currentYear;
$percentile = (float) ($this->request->getGet('percentile') ?? 75);
$percentile = max(1.0, min(99.0, $percentile));
+9 -3
View File
@@ -961,12 +961,18 @@ class UserController extends BaseController
$perPage = max(1, min($perPage, 200));
$page = max(1, $page);
$totalActivities = (int) $this->loginActivityModel->countAll();
$activities = $this->loginActivityModel
$schoolYear = (string) ((new \App\Models\ConfigurationModel())->getConfig('school_year') ?? '');
$activityModel = $this->loginActivityModel;
if ($schoolYear !== '' && db_connect()->fieldExists('school_year', 'login_activity')) {
$activityModel->where('school_year', $schoolYear);
}
$totalActivities = (int) $activityModel->countAllResults(false);
$activities = $activityModel
->orderBy('login_time', 'DESC')
->paginate($perPage, 'loginActivity', $page) ?? [];
$pager = $this->loginActivityModel->pager;
$pager = $activityModel->pager;
$currentPage = $pager ? (int) $pager->getCurrentPage('loginActivity') : $page;
$pageCount = $pager ? (int) $pager->getPageCount('loginActivity') : (int) max(1, ceil($totalActivities / $perPage));
+12 -37
View File
@@ -103,26 +103,14 @@ class WhatsappController extends BaseController
$sectionName = $row['class_section_name'] ?? ('Section ' . $sectionId);
}
$existing = $this->linkModel->where([
'class_section_id' => $sectionId,
'school_year' => $this->schoolYear,
'semester' => $this->semester,
])->first();
$payload = [
'class_section_id' => $sectionId,
'class_section_name' => $sectionName,
'school_year' => $this->schoolYear,
'semester' => $this->semester,
'invite_link' => trim($inviteLink),
'active' => $active,
];
if ($existing) {
$this->linkModel->update($existing['id'], $payload);
} else {
$this->linkModel->insert($payload);
}
$this->linkModel->upsertLinkForSection(
$sectionId,
$sectionName,
(string) $this->schoolYear,
'',
$inviteLink,
$active === 1
);
return redirect()->back()->with('success', 'WhatsApp group link saved.');
}
@@ -434,8 +422,6 @@ class WhatsappController extends BaseController
sp.secondparent_lastname AS sp_lastname,
sp.secondparent_email AS sp_email,
sp.secondparent_phone AS sp_phone,
sp.school_year AS sp_school_year,
sp.semester AS sp_semester,
u.id AS u_id,
u.firstname AS u_firstname,
@@ -448,14 +434,6 @@ class WhatsappController extends BaseController
$b->join('users u', 'u.id = sp.firstparent_id', 'left');
// Scope by term using parents table (authoritative for the pairing)
if ($schoolYear !== '') {
$b->where('sp.school_year', $schoolYear);
}
if ($semester !== '') {
$b->where('sp.semester', $semester);
}
$rows = $b->get()->getResultArray();
// Flatten into a single contacts list (primary + second parent as separate rows)
@@ -606,11 +584,10 @@ class WhatsappController extends BaseController
$pb->join('students s', 's.id = sc.student_id', 'inner'); // adjust if your table is named `student` (singular)
$pb->join('users u', 'u.id = s.parent_id', 'inner'); // primary parent lives on students.parent_id
// Second parent row for the same term (allow NULL/'' semester if you sometimes omit it)
// Second parent row for the primary parent.
$pb->join(
'parents sp',
"sp.firstparent_id = u.id
AND sp.school_year = sc.school_year",
'sp.firstparent_id = u.id',
'left'
);
@@ -1202,7 +1179,7 @@ class WhatsappController extends BaseController
/**
* Class mode:
* - Given classSectionId, find students (student_class) for the term
* - Given classSectionId, find students (student_class) for the year
* - Map to primaries (users) and second-parents (parents)
* - Return one bundle **per primary parent** (so each parent gets their own email)
*/
@@ -1215,7 +1192,6 @@ class WhatsappController extends BaseController
$stuRows = $this->db->table('student_class')
->select('student_id')
->where('school_year', $this->schoolYear)
->where('semester', $this->semester)
->where('class_section_id', $classSectionId)
->get()->getResultArray();
if (empty($stuRows)) return [];
@@ -1302,7 +1278,7 @@ class WhatsappController extends BaseController
/**
* All mode:
* - Iterate all distinct class_section_id in student_class (for the term)
* - Iterate all distinct class_section_id in student_class (for the year)
* - Reuse class bundles per section and flatten
*/
private function bundlesForAllParentsAllClasses(array $linkBySection): array
@@ -1310,7 +1286,6 @@ class WhatsappController extends BaseController
$secRows = $this->db->table('student_class')
->select('DISTINCT class_section_id', false)
->where('school_year', $this->schoolYear)
->where('semester', $this->semester)
->orderBy('class_section_id', 'ASC')
->get()->getResultArray();
+15 -1
View File
@@ -13,6 +13,11 @@ class WinnersController extends BaseController
public function competitionIndex()
{
$competitionModel = new CompetitionModel();
$schoolYear = $this->currentSchoolYearName();
if ($schoolYear !== '') {
$competitionModel->where('school_year', $schoolYear);
}
$competitions = $competitionModel
->where('is_published', 1)
@@ -21,6 +26,7 @@ class WinnersController extends BaseController
return view('winners/competitions/index', [
'competitions' => $competitions,
'schoolYear' => $schoolYear,
]);
}
@@ -31,7 +37,14 @@ class WinnersController extends BaseController
$classSectionModel = new ClassSectionModel();
$classWinnerModel = new CompetitionClassWinnerModel();
$competition = $competitionModel->where('is_published', 1)->find($id);
$schoolYear = $this->currentSchoolYearName();
$competitionModel->where('is_published', 1);
if ($schoolYear !== '') {
$competitionModel->where('school_year', $schoolYear);
}
$competition = $competitionModel->find($id);
if (!$competition) {
return redirect()->to('/winners/competitions');
}
@@ -81,6 +94,7 @@ class WinnersController extends BaseController
'winnersByClass' => $winnersByClass,
'sectionMap' => $sectionMap,
'questionCounts' => $questionCounts,
'schoolYear' => $schoolYear,
]);
}
}
@@ -11,6 +11,10 @@ class FixPrintRequestsForeignKey extends Migration
// Drop the old foreign key if it exists
$this->forge->dropForeignKey('print_requests', 'print_requests_class_id_foreign');
if (! $this->db->tableExists('class_sections')) {
return;
}
// Add the new foreign key
$this->forge->addForeignKey('class_id', 'class_sections', 'id', 'CASCADE', 'CASCADE');
@@ -9,7 +9,14 @@ class RevertPrintRequestsForeignKey extends Migration
public function up()
{
// Drop the old foreign key if it exists
$db = \Config\Database::connect();
$keys = $db->getForeignKeyData('print_requests');
foreach ($keys as $key) {
if ($key->constraint_name === 'print_requests_class_id_foreign') {
$this->forge->dropForeignKey('print_requests', 'print_requests_class_id_foreign');
break;
}
}
// Add the new foreign key
$this->forge->addForeignKey('class_id', 'classes', 'id', 'CASCADE', 'CASCADE');
@@ -12,8 +12,7 @@ class FixPrintRequestsForeignKeyAgain extends Migration
$keys = $db->getForeignKeyData('print_requests');
foreach ($keys as $key) {
if ($key->constraint_name === 'print_requests_class_id_foreign') {
$this->forge->dropForeignKey('print_requests', 'print_requests_class_id_foreign');
break;
return;
}
}
@@ -8,12 +8,8 @@ class RemoveClassAssignmentSemester extends Migration
{
public function up()
{
if ($this->db->tableExists('teacher_class')) {
$this->forge->dropColumn('teacher_class', 'semester');
}
if ($this->db->tableExists('student_class')) {
$this->forge->dropColumn('student_class', 'semester');
}
// Keep the legacy semester columns in place. They may be ignored by newer
// code, but dropping them during a post-restore migrate destroys data.
}
public function down()
@@ -39,4 +35,13 @@ class RemoveClassAssignmentSemester extends Migration
]);
}
}
private function indexExists(string $table, string $index): bool
{
$result = $this->db->query(
'SHOW INDEX FROM `' . str_replace('`', '``', $table) . '` WHERE Key_name = ' . $this->db->escape($index)
);
return $result->getNumRows() > 0;
}
}
@@ -3,6 +3,7 @@
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class CreateTeacherSubmissionNotificationHistory extends Migration
{
@@ -56,7 +57,7 @@ class CreateTeacherSubmissionNotificationHistory extends Migration
'sent_at' => [
'type' => 'DATETIME',
'null' => false,
'default' => 'CURRENT_TIMESTAMP',
'default' => new RawSql('CURRENT_TIMESTAMP'),
],
]);
@@ -3,6 +3,7 @@
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class CreateExamDraftSubmissions extends Migration
{
@@ -89,7 +90,7 @@ class CreateExamDraftSubmissions extends Migration
'created_at' => [
'type' => 'DATETIME',
'null' => false,
'default' => 'CURRENT_TIMESTAMP',
'default' => new RawSql('CURRENT_TIMESTAMP'),
],
'updated_at' => [
'type' => 'DATETIME',
@@ -24,7 +24,7 @@ class CreatePlacementLevels extends Migration
]);
$this->forge->addKey('id', true);
$this->forge->addKey(['student_id', 'school_year'], true);
$this->forge->addUniqueKey(['student_id', 'school_year'], 'unique_student_school_year');
$this->forge->addKey('school_year');
$this->forge->createTable('placement_levels');
}
@@ -24,7 +24,7 @@ class CreatePlacementScores extends Migration
]);
$this->forge->addKey('id', true);
$this->forge->addKey(['batch_id', 'student_id'], true);
$this->forge->addUniqueKey(['batch_id', 'student_id'], 'unique_batch_student');
$this->forge->addKey('batch_id');
$this->forge->createTable('placement_scores');
}
@@ -65,7 +65,10 @@ class CreateMissingScoreOverrides extends Migration
$this->forge->addKey('id', true);
$this->forge->addKey(['class_section_id', 'semester', 'school_year', 'item_type'], false, 'missing_score_overrides_scope');
$this->forge->addKey(['student_id', 'class_section_id', 'semester', 'school_year', 'item_type', 'item_index'], true, 'missing_score_overrides_unique');
$this->forge->addUniqueKey(
['student_id', 'class_section_id', 'semester', 'school_year', 'item_type', 'item_index'],
'missing_score_overrides_unique'
);
$this->forge->createTable('missing_score_overrides', true);
}
@@ -10,13 +10,18 @@ class AddStyleToPreferences extends Migration
{
if ($this->db->tableExists('user_preferences')) {
if (! $this->db->fieldExists('style_color', 'user_preferences')) {
$this->forge->addColumn('user_preferences', [
'style_color' => [
$styleColor = [
'type' => 'VARCHAR',
'constraint' => 32,
'null' => true,
'after' => 'timezone',
],
];
if ($this->db->fieldExists('timezone', 'user_preferences')) {
$styleColor['after'] = 'timezone';
}
$this->forge->addColumn('user_preferences', [
'style_color' => $styleColor,
]);
}
if (! $this->db->fieldExists('menu_color', 'user_preferences')) {
@@ -9,7 +9,11 @@ class FinancialSystemLedgerCleanup extends Migration
public function up()
{
$this->addInstallmentSequenceColumn();
$this->backfillInstallmentSequence();
$this->ensurePaymentDateHasTime();
$this->ensureIndexes();
$this->repairPaymentInvoiceTerms();
$this->normalizePaymentStatuses();
$this->ensureConfigurationDefaults();
$this->archivePaypalTables();
$this->refreshFinancialNavItems();
@@ -24,6 +28,7 @@ class FinancialSystemLedgerCleanup extends Migration
}
$this->dropIndexIfExists('payments', 'idx_payments_invoice_id');
$this->dropIndexIfExists('payments', 'idx_payments_parent_year');
$this->dropIndexIfExists('payments', 'idx_payments_parent_year_semester');
$this->dropIndexIfExists('payments', 'uniq_payments_transaction_id');
$this->dropIndexIfExists('invoices', 'idx_invoices_parent_year_semester');
@@ -68,10 +73,33 @@ class FinancialSystemLedgerCleanup extends Migration
}
}
protected function backfillInstallmentSequence(): void
{
if (!$this->db->tableExists('payments') || !$this->db->fieldExists('installment_seq', 'payments')) {
return;
}
$this->db->query(
'UPDATE `payments`
SET `installment_seq` = `number_of_installments`
WHERE `installment_seq` IS NULL'
);
}
protected function ensurePaymentDateHasTime(): void
{
if (!$this->db->tableExists('payments') || !$this->db->fieldExists('payment_date', 'payments')) {
return;
}
$this->db->query('ALTER TABLE `payments` MODIFY `payment_date` DATETIME NOT NULL');
}
protected function ensureIndexes(): void
{
$this->addIndexIfMissing('payments', 'idx_payments_invoice_id', ['invoice_id']);
$this->addIndexIfMissing('payments', 'idx_payments_parent_year_semester', ['parent_id', 'school_year', 'semester']);
$this->dropIndexIfExists('payments', 'idx_payments_parent_year_semester');
$this->addIndexIfMissing('payments', 'idx_payments_parent_year', ['parent_id', 'school_year']);
$this->addIndexIfMissing('invoices', 'idx_invoices_parent_year_semester', ['parent_id', 'school_year', 'semester']);
$this->addIndexIfMissing('discount_usages', 'idx_discount_usages_invoice_id', ['invoice_id']);
$this->addIndexIfMissing('discount_usages', 'idx_discount_usages_parent_year_semester', ['parent_id', 'school_year', 'semester']);
@@ -86,6 +114,33 @@ class FinancialSystemLedgerCleanup extends Migration
}
}
protected function repairPaymentInvoiceTerms(): void
{
if (!$this->db->tableExists('payments') || !$this->db->tableExists('invoices')) {
return;
}
$this->db->query(
'UPDATE `payments` p
JOIN `invoices` i ON i.`id` = p.`invoice_id`
SET p.`school_year` = i.`school_year`
WHERE COALESCE(p.`school_year`, \'\') <> COALESCE(i.`school_year`, \'\')'
);
}
protected function normalizePaymentStatuses(): void
{
if (!$this->db->tableExists('payments') || !$this->db->fieldExists('status', 'payments')) {
return;
}
$this->db->query(
"UPDATE `payments`
SET `status` = 'recorded'
WHERE LOWER(TRIM(`status`)) IN ('paid', 'partially paid', 'payment recorded', 'full', 'completed')"
);
}
protected function ensureConfigurationDefaults(): void
{
if (!$this->db->tableExists('configuration')) {
@@ -128,8 +183,8 @@ class FinancialSystemLedgerCleanup extends Migration
protected function archivePaypalTables(): void
{
$this->renameTableIfPresent('paypal_payments', 'archived_paypal_payments');
$this->renameTableIfPresent('paypal_transactions', 'archived_paypal_transactions');
// Keep legacy PayPal tables under their original names. Renaming them
// during migrate makes restored data appear to disappear from the app.
}
protected function restorePaypalTables(): void
@@ -0,0 +1,363 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class FixSchoolYearColumns extends Migration
{
/**
* Tables that directly own an academic year.
*
* school_year stays as text by design. Valid values use YYYY-YYYY and
* the second year must be exactly the first year + 1.
*/
private array $yearOwnerTables = [
'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',
'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',
];
/** Tables where school_year is redundant or conceptually incorrect. */
private array $tablesWithoutDirectYear = [
'chapters',
'classes',
'class_preparation_log',
'class_prep_adjustments',
'contactus',
'emergency_contacts',
'inventory_items',
'invoice_students_list',
'ip_attempts',
'login_activity',
'messages',
'notifications',
'notification_recipients',
'parents',
'paypal_transactions',
'placement_levels',
'preferences',
'staff',
'students',
'support_requests',
'users',
'user_notifications',
];
/** Tables where semester is redundant or conceptually incorrect. */
private array $tablesWithoutDirectSemester = [
'badge_print_logs',
'classes',
'contactus',
'emergency_contacts',
'inventory_items',
'invoice_students_list',
'ip_attempts',
'notification_recipients',
'notifications',
'parents',
'support_requests',
'user_notifications',
'whatsapp_group_links',
];
public function up(): void
{
if ($this->db->DBDriver !== 'MySQLi') {
throw new \RuntimeException(
'This migration targets MySQL 8 because it uses enforced CHECK constraints.'
);
}
$this->db->resetDataCache();
// These annual entities lacked a school_year column in the audited schema.
foreach (['class_progress_reports', 'exams', 'print_requests'] as $table) {
if ($this->db->tableExists($table) && ! $this->db->fieldExists('school_year', $table)) {
// Nullable avoids inventing a year for existing rows.
// Backfill it, then make it NOT NULL in a later migration.
$this->forge->addColumn($table, [
'school_year' => [
'type' => 'VARCHAR',
'constraint' => 9,
'null' => true,
],
]);
}
}
$this->db->resetDataCache();
// Validate and normalize every direct owner to VARCHAR(9).
foreach ($this->yearOwnerTables as $table) {
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
continue;
}
$this->assertValidSchoolYears($table, 'school_year');
$this->normalizeYearColumn($table, 'school_year');
$this->ensureYearCheckConstraint($table, 'school_year');
$this->ensureYearIndex($table, 'school_year');
}
// Promotion is a transition and legitimately owns both source and target years.
if ($this->db->tableExists('promotion_queue')) {
foreach (['school_year_from', 'school_year_to'] as $column) {
if (! $this->db->fieldExists($column, 'promotion_queue')) {
continue;
}
$this->assertValidSchoolYears('promotion_queue', $column);
$this->normalizeYearColumn('promotion_queue', $column);
$this->ensureYearCheckConstraint('promotion_queue', $column);
$this->ensureYearIndex('promotion_queue', $column);
}
}
$this->db->resetDataCache();
// Do not drop redundant school_year/semester columns here. Restored
// production dumps may still contain meaningful historical data in
// those columns, and running migrate must not destroy it.
$this->db->resetDataCache();
foreach ($this->yearOwnerTables as $table) {
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
continue;
}
$this->ensureYearIndex($table, 'school_year');
}
}
public function down(): void
{
throw new \RuntimeException(
'This migration is intentionally irreversible because dropping school_year columns destroys data. Restore from backup instead of pretending rollback can resurrect it.'
);
}
private function assertValidSchoolYears(string $table, string $column): void
{
$tableName = $this->quoteIdentifier($table);
$columnName = $this->quoteIdentifier($column);
$invalid = $this->db->query(
"SELECT COUNT(*) AS aggregate
FROM {$tableName}
WHERE {$columnName} IS NOT NULL
AND (
{$columnName} NOT REGEXP '^[0-9]{4}-[0-9]{4}$'
OR CAST(RIGHT({$columnName}, 4) AS UNSIGNED)
<> CAST(LEFT({$columnName}, 4) AS UNSIGNED) + 1
)"
)->getRow();
if ((int) ($invalid->aggregate ?? 0) > 0) {
throw new \RuntimeException(
"Cannot migrate {$table}.{$column}: found {$invalid->aggregate} invalid school-year value(s). Expected YYYY-YYYY with consecutive years, for example 2025-2026."
);
}
}
private function normalizeYearColumn(string $table, string $column): void
{
$metadata = $this->db->query(
'SELECT IS_NULLABLE, COLLATION_NAME
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?',
[$table, $column]
)->getRow();
if ($metadata === null) {
return;
}
$nullable = $metadata->IS_NULLABLE === 'YES' ? 'NULL' : 'NOT NULL';
$collation = $metadata->COLLATION_NAME && preg_match('/^[A-Za-z0-9_]+$/', $metadata->COLLATION_NAME)
? ' COLLATE ' . $metadata->COLLATION_NAME
: '';
$this->db->query(sprintf(
'ALTER TABLE %s MODIFY COLUMN %s VARCHAR(9)%s %s',
$this->quoteIdentifier($table),
$this->quoteIdentifier($column),
$collation,
$nullable
));
}
private function ensureYearCheckConstraint(string $table, string $column): void
{
$constraint = $this->objectName('chk_sy', $table, $column);
$exists = $this->db->query(
'SELECT COUNT(*) AS aggregate
FROM information_schema.TABLE_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND CONSTRAINT_NAME = ?
AND CONSTRAINT_TYPE = \'CHECK\'',
[$table, $constraint]
)->getRow();
if ((int) ($exists->aggregate ?? 0) > 0) {
return;
}
$columnName = $this->quoteIdentifier($column);
$this->db->query(sprintf(
"ALTER TABLE %s ADD CONSTRAINT %s CHECK (
%s IS NULL OR (
%s REGEXP '^[0-9]{4}-[0-9]{4}$'
AND CAST(RIGHT(%s, 4) AS UNSIGNED)
= CAST(LEFT(%s, 4) AS UNSIGNED) + 1
)
)",
$this->quoteIdentifier($table),
$this->quoteIdentifier($constraint),
$columnName,
$columnName,
$columnName,
$columnName
));
}
private function ensureYearIndex(string $table, string $column): void
{
$indexed = $this->db->query(
'SELECT COUNT(*) AS aggregate
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?',
[$table, $column]
)->getRow();
if ((int) ($indexed->aggregate ?? 0) > 0) {
return;
}
$index = $this->objectName('idx_sy', $table, $column);
$this->db->query(sprintf(
'ALTER TABLE %s ADD INDEX %s (%s)',
$this->quoteIdentifier($table),
$this->quoteIdentifier($index),
$this->quoteIdentifier($column)
));
}
private function dropIndexesContainingColumn(string $table, string $column): void
{
$indexes = $this->db->query(
'SELECT DISTINCT INDEX_NAME
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?
AND INDEX_NAME <> \'PRIMARY\'',
[$table, $column]
)->getResult();
foreach ($indexes as $index) {
$this->db->query(sprintf(
'ALTER TABLE %s DROP INDEX %s',
$this->quoteIdentifier($table),
$this->quoteIdentifier($index->INDEX_NAME)
));
}
}
private function dropChecksContainingColumn(string $table, string $column): void
{
$checks = $this->db->query(
'SELECT tc.CONSTRAINT_NAME
FROM information_schema.TABLE_CONSTRAINTS tc
INNER JOIN information_schema.CHECK_CONSTRAINTS cc
ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE tc.CONSTRAINT_SCHEMA = DATABASE()
AND tc.TABLE_NAME = ?
AND tc.CONSTRAINT_TYPE = \'CHECK\'
AND cc.CHECK_CLAUSE LIKE ?',
[$table, '%' . $column . '%']
)->getResult();
foreach ($checks as $check) {
$this->db->query(sprintf(
'ALTER TABLE %s DROP CHECK %s',
$this->quoteIdentifier($table),
$this->quoteIdentifier($check->CONSTRAINT_NAME)
));
}
}
private function objectName(string $prefix, string $table, string $column): string
{
// MySQL identifiers are limited to 64 characters.
return substr($prefix . '_' . $table . '_' . $column . '_' . substr(sha1($table . '.' . $column), 0, 8), 0, 64);
}
private function quoteIdentifier(string $identifier): string
{
return '`' . str_replace('`', '``', $identifier) . '`';
}
}
@@ -0,0 +1,141 @@
<?php
declare(strict_types=1);
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use RuntimeException;
final class EnsureSchoolYearOnFinancialTables extends Migration
{
/** @var array<string, bool> table => nullable */
private array $tables = [
'discount_usages' => false,
'event_charges' => true,
'invoice_event' => true,
'payment_error' => true,
'payment_notification_logs' => true,
'payment_transactions' => true,
'reimbursement_batch_items' => true,
];
public function up(): void
{
if ($this->db->DBDriver !== 'MySQLi') {
throw new RuntimeException('This migration requires MySQL/MariaDB through the MySQLi driver.');
}
foreach ($this->tables as $table => $nullable) {
if (! $this->db->tableExists($table)) {
continue;
}
if (! $this->db->fieldExists('school_year', $table)) {
$this->forge->addColumn($table, [
'school_year' => [
'type' => 'VARCHAR',
'constraint' => 9,
'null' => $nullable,
'after' => $this->afterColumn($table),
],
]);
}
$this->backfillSchoolYear($table);
$this->assertValidYears($table);
$nullSql = $nullable ? 'NULL' : 'NOT NULL';
$this->db->query(
sprintf(
'ALTER TABLE `%s` MODIFY `school_year` VARCHAR(9) %s',
str_replace('`', '``', $table),
$nullSql
)
);
$this->ensureIndex($table);
}
}
public function down(): void
{
// These columns are part of the business model and must not be dropped on rollback.
}
private function assertValidYears(string $table): void
{
$sql = sprintf(
"SELECT COUNT(*) AS invalid_count
FROM `%s`
WHERE `school_year` IS NOT NULL
AND (
`school_year` NOT REGEXP '^[0-9]{4}-[0-9]{4}$'
OR CAST(RIGHT(`school_year`, 4) AS UNSIGNED)
<> CAST(LEFT(`school_year`, 4) AS UNSIGNED) + 1
)",
str_replace('`', '``', $table)
);
$row = $this->db->query($sql)->getRowArray();
$invalid = (int) ($row['invalid_count'] ?? 0);
if ($invalid > 0) {
throw new RuntimeException(
"Cannot normalize {$table}.school_year: {$invalid} invalid value(s). Expected YYYY-YYYY, for example 2025-2026."
);
}
}
private function backfillSchoolYear(string $table): void
{
if ($table === 'discount_usages' && $this->db->tableExists('invoices')) {
$this->db->query(
"UPDATE `discount_usages` du
INNER JOIN `invoices` i ON i.`id` = du.`invoice_id`
SET du.`school_year` = i.`school_year`
WHERE (du.`school_year` IS NULL OR TRIM(du.`school_year`) = '')
AND i.`school_year` REGEXP '^[0-9]{4}-[0-9]{4}$'
AND CAST(RIGHT(i.`school_year`, 4) AS UNSIGNED)
= CAST(LEFT(i.`school_year`, 4) AS UNSIGNED) + 1"
);
}
}
private function ensureIndex(string $table): void
{
$indexName = 'idx_' . $table . '_school_year';
if (strlen($indexName) > 64) {
$indexName = 'idx_' . substr(hash('sha256', $table . '_school_year'), 0, 24);
}
$row = $this->db->query(
'SELECT COUNT(*) AS index_count
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?',
[$table, 'school_year']
)->getRowArray();
if ((int) ($row['index_count'] ?? 0) === 0) {
$this->db->query(sprintf(
'CREATE INDEX `%s` ON `%s` (`school_year`)',
str_replace('`', '``', $indexName),
str_replace('`', '``', $table)
));
}
}
private function afterColumn(string $table): string
{
$preferred = ['semester', 'invoice_id', 'payment_id', 'batch_id'];
foreach ($preferred as $column) {
if ($this->db->fieldExists($column, $table)) {
return $column;
}
}
return 'id';
}
}
@@ -0,0 +1,249 @@
<?php
declare(strict_types=1);
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use RuntimeException;
final class ApplySchoolYearSemesterAuditCorrections extends Migration
{
private array $schoolYearIndexTables = [
'archived_paypal_transactions',
'class_progress_reports',
'exams',
'missing_score_overrides',
'payments',
'placement_batches',
'print_requests',
'report_card_acknowledgements',
'semester_scores',
'staff_attendance',
'teacher_attendance_data',
'whatsapp_group_links',
];
private array $semesterDropTables = [
'badge_print_logs',
'classes',
'contactus',
'emergency_contacts',
'inventory_items',
'invoice_students_list',
'ip_attempts',
'notification_recipients',
'notifications',
'parents',
'support_requests',
'user_notifications',
'whatsapp_group_links',
];
public function up(): void
{
if ($this->db->DBDriver !== 'MySQLi') {
throw new RuntimeException('This migration requires MySQL/MariaDB through the MySQLi driver.');
}
if ($this->db->tableExists('archived_paypal_transactions')
&& $this->db->fieldExists('school_year', 'archived_paypal_transactions')) {
$this->assertValidSchoolYears('archived_paypal_transactions', 'school_year');
$this->normalizeYearColumn('archived_paypal_transactions', 'school_year');
$this->ensureYearCheckConstraint('archived_paypal_transactions', 'school_year');
}
foreach ($this->schoolYearIndexTables as $table) {
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
continue;
}
$this->ensureIndex($table, 'school_year');
}
// Preserve legacy semester columns. They may be redundant for newer
// code paths, but migration must not delete restored production data.
foreach ($this->schoolYearIndexTables as $table) {
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
continue;
}
$this->ensureIndex($table, 'school_year');
}
}
public function down(): void
{
throw new RuntimeException(
'This migration is intentionally irreversible because dropping semester columns destroys data.'
);
}
private function assertValidSchoolYears(string $table, string $column): void
{
$tableName = $this->quoteIdentifier($table);
$columnName = $this->quoteIdentifier($column);
$invalid = $this->db->query(
"SELECT COUNT(*) AS aggregate
FROM {$tableName}
WHERE {$columnName} IS NOT NULL
AND (
{$columnName} NOT REGEXP '^[0-9]{4}-[0-9]{4}$'
OR CAST(RIGHT({$columnName}, 4) AS UNSIGNED)
<> CAST(LEFT({$columnName}, 4) AS UNSIGNED) + 1
)"
)->getRow();
if ((int) ($invalid->aggregate ?? 0) > 0) {
throw new RuntimeException(
"Cannot migrate {$table}.{$column}: found {$invalid->aggregate} invalid school-year value(s)."
);
}
}
private function normalizeYearColumn(string $table, string $column): void
{
$metadata = $this->db->query(
'SELECT IS_NULLABLE, COLLATION_NAME
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?',
[$table, $column]
)->getRow();
if ($metadata === null) {
return;
}
$nullable = $metadata->IS_NULLABLE === 'YES' ? 'NULL' : 'NOT NULL';
$collation = $metadata->COLLATION_NAME && preg_match('/^[A-Za-z0-9_]+$/', $metadata->COLLATION_NAME)
? ' COLLATE ' . $metadata->COLLATION_NAME
: '';
$this->db->query(sprintf(
'ALTER TABLE %s MODIFY COLUMN %s VARCHAR(9)%s %s',
$this->quoteIdentifier($table),
$this->quoteIdentifier($column),
$collation,
$nullable
));
}
private function ensureYearCheckConstraint(string $table, string $column): void
{
$constraint = $this->objectName('chk_sy', $table, $column);
$exists = $this->db->query(
'SELECT COUNT(*) AS aggregate
FROM information_schema.TABLE_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND CONSTRAINT_NAME = ?
AND CONSTRAINT_TYPE = \'CHECK\'',
[$table, $constraint]
)->getRow();
if ((int) ($exists->aggregate ?? 0) > 0) {
return;
}
$columnName = $this->quoteIdentifier($column);
$this->db->query(sprintf(
"ALTER TABLE %s ADD CONSTRAINT %s CHECK (
%s IS NULL OR (
%s REGEXP '^[0-9]{4}-[0-9]{4}$'
AND CAST(RIGHT(%s, 4) AS UNSIGNED)
= CAST(LEFT(%s, 4) AS UNSIGNED) + 1
)
)",
$this->quoteIdentifier($table),
$this->quoteIdentifier($constraint),
$columnName,
$columnName,
$columnName,
$columnName
));
}
private function ensureIndex(string $table, string $column): void
{
$indexed = $this->db->query(
'SELECT COUNT(*) AS aggregate
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?',
[$table, $column]
)->getRow();
if ((int) ($indexed->aggregate ?? 0) > 0) {
return;
}
$this->db->query(sprintf(
'ALTER TABLE %s ADD INDEX %s (%s)',
$this->quoteIdentifier($table),
$this->quoteIdentifier($this->objectName('idx_sy', $table, $column)),
$this->quoteIdentifier($column)
));
}
private function dropIndexesContainingColumn(string $table, string $column): void
{
$indexes = $this->db->query(
'SELECT DISTINCT INDEX_NAME
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?
AND INDEX_NAME <> \'PRIMARY\'',
[$table, $column]
)->getResult();
foreach ($indexes as $index) {
$this->db->query(sprintf(
'ALTER TABLE %s DROP INDEX %s',
$this->quoteIdentifier($table),
$this->quoteIdentifier($index->INDEX_NAME)
));
}
}
private function dropChecksContainingColumn(string $table, string $column): void
{
$checks = $this->db->query(
'SELECT tc.CONSTRAINT_NAME
FROM information_schema.TABLE_CONSTRAINTS tc
INNER JOIN information_schema.CHECK_CONSTRAINTS cc
ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
WHERE tc.CONSTRAINT_SCHEMA = DATABASE()
AND tc.TABLE_NAME = ?
AND tc.CONSTRAINT_TYPE = \'CHECK\'
AND cc.CHECK_CLAUSE LIKE ?',
[$table, '%' . $column . '%']
)->getResult();
foreach ($checks as $check) {
$this->db->query(sprintf(
'ALTER TABLE %s DROP CHECK %s',
$this->quoteIdentifier($table),
$this->quoteIdentifier($check->CONSTRAINT_NAME)
));
}
}
private function objectName(string $prefix, string $table, string $column): string
{
return substr($prefix . '_' . $table . '_' . $column . '_' . substr(sha1($table . '.' . $column), 0, 8), 0, 64);
}
private function quoteIdentifier(string $identifier): string
{
return '`' . str_replace('`', '``', $identifier) . '`';
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use RuntimeException;
final class EnsureWhatsappGroupLinksSchoolYearIndex extends Migration
{
public function up(): void
{
if ($this->db->DBDriver !== 'MySQLi') {
throw new RuntimeException('This migration requires MySQL/MariaDB through the MySQLi driver.');
}
if (! $this->db->tableExists('whatsapp_group_links')
|| ! $this->db->fieldExists('school_year', 'whatsapp_group_links')) {
return;
}
$indexed = $this->db->query(
'SELECT COUNT(*) AS aggregate
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = ?
AND COLUMN_NAME = ?',
['whatsapp_group_links', 'school_year']
)->getRow();
if ((int) ($indexed->aggregate ?? 0) > 0) {
return;
}
$this->db->query(
'ALTER TABLE `whatsapp_group_links` ADD INDEX `idx_sy_whatsapp_group_links_school_year` (`school_year`)'
);
}
public function down(): void
{
if ($this->db->tableExists('whatsapp_group_links')) {
$this->db->query('ALTER TABLE `whatsapp_group_links` DROP INDEX `idx_sy_whatsapp_group_links_school_year`');
}
}
}
@@ -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;
}
}
@@ -0,0 +1,145 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class GrantSubjectCurriculumPermission extends Migration
{
private string $permissionName = 'update_curriculum';
public function up(): void
{
if (
! $this->db->tableExists('roles')
|| ! $this->db->tableExists('permissions')
|| ! $this->db->tableExists('role_permissions')
) {
return;
}
$now = date('Y-m-d H:i:s');
$permission = $this->db->table('permissions')
->where('name', $this->permissionName)
->get()
->getRowArray();
if ($permission === null) {
$insert = [
'name' => $this->permissionName,
'created_at' => $now,
'updated_at' => $now,
];
if ($this->db->fieldExists('description', 'permissions')) {
$insert['description'] = 'Manage subject curriculum entries';
}
$this->db->table('permissions')->insert($insert);
$permissionId = (int) $this->db->insertID();
} else {
$permissionId = (int) $permission['id'];
}
if ($permissionId <= 0) {
return;
}
$roleRows = $this->db->table('roles')
->select('id, name')
->whereIn('name', [
'administrator',
'admin',
'principal',
'vice principal',
'vice_principal',
'administrative staff',
])
->get()
->getResultArray();
foreach ($roleRows as $role) {
$roleId = (int) ($role['id'] ?? 0);
if ($roleId <= 0) {
continue;
}
$existing = $this->db->table('role_permissions')
->where('role_id', $roleId)
->where('permission_id', $permissionId)
->get()
->getRowArray();
$permissionData = [
'can_create' => 1,
'can_read' => 1,
'can_update' => 1,
'can_delete' => 1,
'updated_at' => $now,
];
if ($this->db->fieldExists('can_manage', 'role_permissions')) {
$permissionData['can_manage'] = 1;
}
if ($existing === null) {
$permissionData['role_id'] = $roleId;
$permissionData['permission_id'] = $permissionId;
$permissionData['created_at'] = $now;
$this->db->table('role_permissions')->insert($permissionData);
continue;
}
$this->db->table('role_permissions')
->where('id', (int) $existing['id'])
->update($permissionData);
}
}
public function down(): void
{
if (
! $this->db->tableExists('roles')
|| ! $this->db->tableExists('permissions')
|| ! $this->db->tableExists('role_permissions')
) {
return;
}
$permission = $this->db->table('permissions')
->select('id')
->where('name', $this->permissionName)
->get()
->getRowArray();
if ($permission === null) {
return;
}
$roleRows = $this->db->table('roles')
->select('id')
->whereIn('name', [
'administrator',
'admin',
'principal',
'vice principal',
'vice_principal',
'administrative staff',
])
->get()
->getResultArray();
$roleIds = array_map(static fn(array $role): int => (int) ($role['id'] ?? 0), $roleRows);
$roleIds = array_values(array_filter($roleIds, static fn(int $roleId): bool => $roleId > 0));
if ($roleIds === []) {
return;
}
$this->db->table('role_permissions')
->where('permission_id', (int) $permission['id'])
->whereIn('role_id', $roleIds)
->delete();
}
}
+1
View File
@@ -52,6 +52,7 @@ class NavSeeder extends Seeder
// Configuration
['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
['parent'=>'Staffing','label'=>'Staff Profile','url'=>'staff/index','sort_order'=>1],
@@ -0,0 +1,9 @@
<?php
namespace App\Exceptions\SchoolYear;
use RuntimeException;
final class InvalidSchoolYearSelectionException extends RuntimeException
{
}
@@ -0,0 +1,9 @@
<?php
namespace App\Exceptions\SchoolYear;
use RuntimeException;
final class SchoolYearConfigurationException extends RuntimeException
{
}
@@ -0,0 +1,9 @@
<?php
namespace App\Exceptions\SchoolYear;
use RuntimeException;
final class SchoolYearNotFoundException extends RuntimeException
{
}
@@ -0,0 +1,9 @@
<?php
namespace App\Exceptions\SchoolYear;
use RuntimeException;
final class SchoolYearWriteConflictException extends RuntimeException
{
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Exceptions\SchoolYear\InvalidSchoolYearSelectionException;
use App\Exceptions\SchoolYear\SchoolYearConfigurationException;
use App\Exceptions\SchoolYear\SchoolYearNotFoundException;
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(),
]);
$status = $this->statusCodeFor($e);
if ($request->isAJAX() || str_contains(strtolower($request->getHeaderLine('Accept')), 'application/json')) {
return service('response')
->setStatusCode($status)
->setJSON([
'status' => $status,
'error' => 'Invalid school year',
'message' => $e->getMessage(),
]);
}
return service('response')
->setStatusCode($status)
->setBody(view('errors/school_year', [
'message' => $status >= 500
? 'School-year configuration is invalid. Please contact an administrator.'
: $e->getMessage(),
]));
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
return null;
}
private function statusCodeFor(Throwable $e): int
{
if ($e instanceof InvalidSchoolYearSelectionException) {
return 400;
}
if ($e instanceof SchoolYearNotFoundException) {
return 404;
}
if ($e instanceof SchoolYearConfigurationException) {
return 500;
}
return 400;
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Filters;
use App\Exceptions\SchoolYear\SchoolYearWriteConflictException;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
final class SchoolYearWritableFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
if (! $request instanceof IncomingRequest) {
return null;
}
try {
service('schoolYearWriteGuard')->assertWritable(
service('schoolYearContext')->resolve($request)
);
return null;
} catch (SchoolYearWriteConflictException $e) {
log_message('warning', 'Historical school-year write blocked: {message}', [
'message' => $e->getMessage(),
]);
if ($request->isAJAX() || str_contains(strtolower($request->getHeaderLine('Accept')), 'application/json')) {
return service('response')
->setStatusCode(409)
->setJSON([
'status' => 409,
'error' => 'Read-only school year',
'message' => $e->getMessage(),
]);
}
return redirect()->back()->with('error', $e->getMessage());
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
return null;
}
}
+10
View File
@@ -12,6 +12,16 @@ if (!function_exists('getSemester')) {
if (!function_exists('getSchoolYear')) {
function getSchoolYear() {
if (! is_cli() && session()->get('user_id')) {
try {
return service('schoolYearContext')->resolve(service('request'))->yearName();
} catch (\Throwable $e) {
log_message('warning', 'Falling back to configured school year: {message}', [
'message' => $e->getMessage(),
]);
}
}
$configModel = new \App\Models\ConfigurationModel();
return $configModel->getConfig('school_year');
}
+21
View File
@@ -7,6 +7,8 @@ final class FinancialStatus
public const INVOICE_UNPAID = 'unpaid';
public const INVOICE_PARTIALLY_PAID = 'partially_paid';
public const INVOICE_PAID = 'paid';
public const INVOICE_OVERPAID = 'overpaid';
public const INVOICE_CANCELLED = 'cancelled';
public const PAYMENT_RECORDED = 'recorded';
public const PAYMENT_VOIDED = 'voided';
@@ -18,6 +20,23 @@ final class FinancialStatus
public const PAYMENT_CANCELED = 'canceled';
public const PAYMENT_CANCELLED = 'cancelled';
public const PAYMENT_TRANSACTION_STATUSES = [
self::PAYMENT_RECORDED,
self::PAYMENT_VOIDED,
self::PAYMENT_REFUNDED,
self::PAYMENT_FAILED,
self::PAYMENT_REVERSED,
self::PAYMENT_CHARGEBACK,
];
public const INVOICE_STATUSES = [
self::INVOICE_UNPAID,
self::INVOICE_PARTIALLY_PAID,
self::INVOICE_PAID,
self::INVOICE_OVERPAID,
self::INVOICE_CANCELLED,
];
public const REFUND_PENDING = 'pending';
public const REFUND_APPROVED = 'approved';
public const REFUND_REJECTED = 'rejected';
@@ -55,6 +74,8 @@ final class FinancialStatus
return match (self::normalize($status)) {
'paid', 'full' => self::INVOICE_PAID,
'partially paid', 'partially_paid', 'partial' => self::INVOICE_PARTIALLY_PAID,
'overpaid' => self::INVOICE_OVERPAID,
'cancelled', 'canceled', 'cancelled invoice', 'canceled invoice' => self::INVOICE_CANCELLED,
default => self::INVOICE_UNPAID,
};
}
-1
View File
@@ -18,7 +18,6 @@ class AttendanceDataModel extends Model
'date',
'status',
'reason',
'reported',
'is_reported',
'is_notified',
'semester',
+1 -1
View File
@@ -7,6 +7,6 @@ class ClassPrepAdjustmentModel extends Model
{
protected $table = 'class_prep_adjustments';
protected $allowedFields = [
'class_section_id', 'item_name', 'adjustment', 'school_year', 'created_at'
'class_section_id', 'item_name', 'adjustment', 'adjustable', 'created_at'
];
}
-1
View File
@@ -11,7 +11,6 @@ class ClassPreparationLogModel extends Model
protected $allowedFields = [
'class_section_id',
'class_section',
'school_year',
'prep_data',
'created_at',
];
@@ -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);
}
}
+29
View File
@@ -77,6 +77,13 @@ class ConfigurationModel extends Model
public function getConfig($key)
{
$key = (string) $key;
if ($key === 'school_year') {
$activeSchoolYear = $this->activeSchoolYearName();
if ($activeSchoolYear !== null) {
return $activeSchoolYear;
}
}
if ($key === 'semester') {
try {
$semester = (new \App\Services\SemesterRangeService($this))->getSemesterForDate();
@@ -90,4 +97,26 @@ class ConfigurationModel extends Model
return $this->getConfigValueByKey($key);
}
private function activeSchoolYearName(): ?string
{
try {
if (! $this->db->tableExists('school_years')) {
return null;
}
$row = $this->db->table('school_years')
->select('name')
->where('status', 'active')
->orderBy('id', 'DESC')
->get(1)
->getRowArray();
$name = trim((string) ($row['name'] ?? ''));
return $name !== '' ? $name : null;
} catch (\Throwable) {
return null;
}
}
}
+1 -8
View File
@@ -19,8 +19,6 @@ class ContactUsModel extends Model
'reciever_id',
'subject',
'message',
'semester',
'school_year',
'created_at',
'updated_at'
];
@@ -35,8 +33,6 @@ class ContactUsModel extends Model
'reciever_id' => 'required|integer',
'subject' => 'required|string|max_length[255]',
'message' => 'required|string',
'semester' => 'required|string|max_length[255]',
'school_year' => 'permit_empty|string|max_length[9]'
];
protected $validationMessages = [];
@@ -51,10 +47,7 @@ class ContactUsModel extends Model
*/
public function getMessagesBySemesterAndYear($semester, $school_year)
{
return $this->where([
'semester' => $semester,
'school_year' => $school_year
])->findAll();
return $this->findAll();
}
/**
+10 -3
View File
@@ -6,12 +6,19 @@ use CodeIgniter\Model;
class EmailTemplateModel extends Model {
protected $table = 'email_templates';
protected $primaryKey = 'id';
protected $allowedFields = ['template_key','name','subject','body','is_active'];
protected $allowedFields = ['code', 'variant', 'subject', 'body_html', 'is_active', 'updated_by', 'updated_at'];
public function getActiveTemplates(): array {
return $this->where('is_active', 1)->orderBy('template_key','asc')->findAll();
return $this->select('email_templates.*, code AS template_key, code AS name, body_html AS body')
->where('is_active', 1)
->orderBy('code', 'asc')
->findAll();
}
public function findByKey(string $key): ?array {
return $this->where('template_key', $key)->where('is_active', 1)->first();
return $this->select('email_templates.*, code AS template_key, code AS name, body_html AS body')
->where('code', $key)
->where('is_active', 1)
->first();
}
}
-2
View File
@@ -16,8 +16,6 @@ class EmergencyContactModel extends Model
'cellphone',
'email',
'relation',
'semester',
'school_year',
'created_at',
'updated_at'
];
+2 -2
View File
@@ -86,7 +86,7 @@ class EnrollmentModel extends Model
/**
* Get all enrolled students (full student info) for a given parent.
*/
public function getEnrolledStudents(int $parentId, string $schoolYear = null, string $semester = null): array
public function getEnrolledStudents(int $parentId, ?string $schoolYear = null, ?string $semester = null): array
{
$builder = $this->select('students.*')
->join('students', 'students.id = enrollments.student_id')
@@ -106,7 +106,7 @@ class EnrollmentModel extends Model
/**
* Get student basic info (ID, name, grade) for a given parent where status is enrolled or Payment pending.
*/
public function getenrolledStudentDetails(int $parentId, string $schoolYear = null): array
public function getenrolledStudentDetails(int $parentId, ?string $schoolYear = null): array
{
$builder = $this->db->table('enrollments')
->select('students.id, students.firstname, students.lastname, students.grade_level')
-1
View File
@@ -28,7 +28,6 @@ class EventChargesModel extends Model
'external_parent_email',
'semester',
'school_year',
'created_by',
'updated_by',
'created_at',
'updated_at'
-9
View File
@@ -32,7 +32,6 @@ class ExamDraftModel extends Model
];
protected $allowedFields = [
'teacher_id',
'author_id',
'class_section_id',
'semester',
@@ -40,20 +39,14 @@ class ExamDraftModel extends Model
'exam_type',
'draft_title',
'author_comment',
'description',
'teacher_file',
'teacher_filename',
'author_file',
'author_filename',
'status',
'acceptance_type',
'review_revision',
'reviewer_id',
'admin_id',
'is_legacy',
'reviewer_comment',
'reviewer_comments',
'admin_comments',
'reviewed_at',
'final_file',
'final_filename',
@@ -87,11 +80,9 @@ class ExamDraftModel extends Model
* @var array<string, string>
*/
protected array $casts = [
'teacher_id' => 'int',
'author_id' => 'int',
'class_section_id' => 'int',
'reviewer_id' => '?int',
'admin_id' => '?int',
'review_revision' => 'int',
'version' => 'int',
'previous_draft_id' => '?int',
+2 -1
View File
@@ -12,9 +12,10 @@ class ExamModel extends Model
protected $allowedFields = [
'student_id',
'school_id',
'student_school_id',
'class_section_id',
'exam_name',
'school_year',
'created_at'
];
+44 -8
View File
@@ -39,23 +39,59 @@ class ExpenseModel extends Model
{
$db = \Config\Database::connect();
$builder = $db->table('expenses');
$builder->select('expenses.*,
r.id AS reimb_id,
r.amount AS reimb_amount, r.reimbursement_method, r.check_number,
r.receipt_path AS reimb_receipt, r.status AS reimb_status,
r.school_year, r.semester, r.created_at AS reimb_created_at,
r.reimbursed_to AS reimb_recipient_id,
reimb.firstname AS reimb_firstname, reimb.lastname AS reimb_lastname,
approver.firstname AS approver_firstname, approver.lastname AS approver_lastname');
$hasReimbursementSchoolYear = $db->fieldExists('school_year', 'reimbursements');
$hasReimbursementSemester = $db->fieldExists('semester', 'reimbursements');
$hasExpenseSchoolYear = $db->fieldExists('school_year', 'expenses');
$hasExpenseSemester = $db->fieldExists('semester', 'expenses');
$select = [
'expenses.*',
'r.id AS reimb_id',
'r.amount AS reimb_amount',
'r.reimbursement_method',
'r.check_number',
'r.receipt_path AS reimb_receipt',
'r.status AS reimb_status',
'r.created_at AS reimb_created_at',
'r.reimbursed_to AS reimb_recipient_id',
'reimb.firstname AS reimb_firstname',
'reimb.lastname AS reimb_lastname',
'approver.firstname AS approver_firstname',
'approver.lastname AS approver_lastname',
];
if ($hasReimbursementSchoolYear) {
$select[] = 'r.school_year';
} elseif ($hasExpenseSchoolYear) {
$select[] = 'expenses.school_year AS school_year';
}
if ($hasReimbursementSemester) {
$select[] = 'r.semester';
} elseif ($hasExpenseSemester) {
$select[] = 'expenses.semester AS semester';
} else {
$select[] = 'NULL AS semester';
}
$builder->select(implode(",\n", $select), false);
$builder->join('reimbursements r', 'r.expense_id = expenses.id', 'inner');
$builder->join('users reimb', 'reimb.id = r.reimbursed_to', 'left');
$builder->join('users approver', 'approver.id = r.approved_by', 'left');
if (!empty($filters['school_year'])) {
if ($hasReimbursementSchoolYear) {
$builder->where('r.school_year', $filters['school_year']);
} elseif ($hasExpenseSchoolYear) {
$builder->where('expenses.school_year', $filters['school_year']);
}
}
if (!empty($filters['semester'])) {
if ($hasReimbursementSemester) {
$builder->where('r.semester', $filters['semester']);
} elseif ($hasExpenseSemester) {
$builder->where('expenses.semester', $filters['semester']);
}
}
if (!empty($filters['status'])) {
$builder->where('r.status', $filters['status']);
-1
View File
@@ -18,7 +18,6 @@ class FinalExamModel extends Model
'class_section_id',
'updated_by',
'score',
'comment',
'semester',
'school_year',
'created_at',
+1 -1
View File
@@ -14,7 +14,7 @@ class FinalScoreModel extends Model
'student_id',
'school_id',
'class_section_id',
'teacher_id',
'updated_by',
'score',
'score_letter',
'comment',
-6
View File
@@ -30,10 +30,6 @@ protected $table = 'inventory_items';
'sku',
'notes',
// academic tags
'semester',
'school_year',
// audit
'updated_by',
@@ -50,7 +46,5 @@ protected $table = 'inventory_items';
'name' => 'required|min_length[2]',
'quantity' => 'permit_empty|integer',
'unit_price' => 'permit_empty|decimal',
'semester' => 'permit_empty|in_list[Spring,Fall]',
'school_year' => 'permit_empty|max_length[16]', // e.g. 2025-2026
];
}
-2
View File
@@ -20,8 +20,6 @@ class InvoiceStudentListModel extends Model
'student_lastname',
'school_id',
'enrolled',
'school_year',
'semester',
'created_at',
'updated_at'
];
-2
View File
@@ -13,8 +13,6 @@ class IpAttemptModel extends Model
'ip_address',
'attempts',
'last_attempt_at',
'semester',
'school_year',
'blocked_until'
];
-1
View File
@@ -15,7 +15,6 @@ class LoginActivityModel extends Model
'logout_time',
'ip_address',
'user_agent',
'school_year',
'semester',
'created_at',
'updated_at'
+4 -7
View File
@@ -21,8 +21,7 @@ class MessageModel extends Model
'priority',
'attachment',
'status',
'semester', // Added field
'school_year' // Added field
'semester'
];
protected $useTimestamps = false; // Since you're manually handling date fields
@@ -150,10 +149,8 @@ class MessageModel extends Model
*/
public function getMessagesBySemesterAndYear($semester, $school_year = null)
{
$builder = $this->where('semester', $semester);
if ($school_year) {
$builder->where('school_year', $school_year);
}
return $builder->orderBy('sent_datetime', 'DESC')->findAll();
return $this->where('semester', $semester)
->orderBy('sent_datetime', 'DESC')
->findAll();
}
}
+4 -3
View File
@@ -17,9 +17,10 @@ class NotificationModel extends Model
'status',
'action_url',
'attachment_path',
'semester',
'school_year',
'scheduled_at'
'expires_at',
'sent_at',
'scheduled_at',
'deleted_at'
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
-2
View File
@@ -15,7 +15,5 @@ class ParentModel extends Model
'secondparent_email',
'secondparent_phone',
'firstparent_id',
'semester',
'school_year',
];
}
+283 -66
View File
@@ -2,7 +2,9 @@
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
use CodeIgniter\Validation\ValidationInterface;
class PaymentModel extends Model
{
@@ -10,12 +12,22 @@ class PaymentModel extends Model
protected $primaryKey = 'id';
protected $returnType = 'array';
/**
* Keep this list broad, then filter it in __construct() against the real DB schema.
* This prevents CI from trying to insert/update columns that do not exist, such as `balance`.
*/
protected $allowedFields = [
'parent_id',
'invoice_id',
// Legacy invoice snapshot fields. Do not use these as source of truth.
'total_amount',
// Actual payment fields.
'paid_amount',
'balance',
'balance_amount',
'balance_after_payment',
'number_of_installments',
'installment_seq',
'transaction_id',
@@ -24,26 +36,44 @@ class PaymentModel extends Model
'payment_method',
'payment_date',
'school_year',
'semester',
'status',
'updated_by'
'updated_by',
];
protected $useTimestamps = false;
// ❗ Your DB handles created_at / updated_at with default CURRENT_TIMESTAMP
// Remove CI4 auto timestamp management unless you modify your DB schema
/**
* Let DB defaults handle created_at / updated_at.
* Keep validation strict for actual payment data, but do not require legacy snapshot columns.
*/
protected $cleanValidationRules = true;
protected $validationRules = [
'parent_id' => 'required|integer',
'invoice_id' => 'required|integer',
'total_amount' => 'required|decimal',
'paid_amount' => 'required|decimal',
'balance' => 'required|decimal',
'number_of_installments' => 'required|integer',
'payment_method' => 'required|max_length[50]', // ✅ Removed 'string'
'payment_date' => 'required|valid_date[Y-m-d H:i:s]',
'status' => 'required|max_length[50]', // ✅ Removed 'string'
// Legacy snapshot. Optional because invoice total belongs to invoices table.
'total_amount' => 'permit_empty|decimal',
'paid_amount' => 'required|decimal|greater_than[0]',
// These are optional because not every live schema has a balance snapshot column.
'balance' => 'permit_empty|decimal|greater_than_equal_to[0]',
'balance_amount' => 'permit_empty|decimal|greater_than_equal_to[0]',
'balance_after_payment' => 'permit_empty|decimal|greater_than_equal_to[0]',
// Legacy/current sequence columns.
'number_of_installments' => 'permit_empty|integer|greater_than[0]',
'installment_seq' => 'permit_empty|integer|greater_than[0]',
'transaction_id' => 'permit_empty|max_length[100]',
'payment_method' => 'required|in_list[cash,check,card]',
'payment_date' => 'required|valid_date',
'school_year' => 'permit_empty|max_length[20]',
'status' => 'required|max_length[50]',
'check_file' => 'permit_empty|max_length[255]',
'check_number' => 'permit_empty|max_length[100]',
'updated_by' => 'permit_empty|integer',
];
protected $validationMessages = [
@@ -56,112 +86,225 @@ class PaymentModel extends Model
'integer' => 'Invoice ID must be an integer.',
],
'total_amount' => [
'required' => 'Total amount is required.',
'decimal' => 'Total amount must be a valid decimal.',
],
'paid_amount' => [
'required' => 'Paid amount is required.',
'decimal' => 'Paid amount must be a valid decimal.',
'greater_than' => 'Paid amount must be greater than zero.',
],
'balance' => [
'required' => 'Balance is required.',
'decimal' => 'Balance must be a valid decimal.',
'greater_than_equal_to' => 'Balance must not be negative.',
],
'balance_amount' => [
'decimal' => 'Balance amount must be a valid decimal.',
'greater_than_equal_to' => 'Balance amount must not be negative.',
],
'balance_after_payment' => [
'decimal' => 'Balance after payment must be a valid decimal.',
'greater_than_equal_to' => 'Balance after payment must not be negative.',
],
'payment_date' => [
'required' => 'Payment date is required.',
'valid_date' => 'Payment date must be a valid date (Y-m-d H:i:s).',
'valid_date' => 'Payment date must be a valid date.',
],
'payment_method' => [
'required' => 'Payment method is required.',
'max_length' => 'Payment method must not exceed 50 characters.',
'in_list' => 'Payment method must be cash, check, or card.',
],
'status' => [
'required' => 'Status is required.',
'max_length' => 'Status must not exceed 50 characters.',
],
'number_of_installments' => [
'required' => 'Number of installments is required.',
'integer' => 'Number of installments must be an integer.',
'greater_than' => 'Number of installments must be greater than zero.',
],
'installment_seq' => [
'integer' => 'Installment sequence must be an integer.',
'greater_than' => 'Installment sequence must be greater than zero.',
],
'check_number' => [
'max_length' => 'Check number must not exceed 100 characters.',
]
],
];
/**
* Get payments by parent ID.
*
* @param int $parentId
* @return array
*/
public function getPaymentsByParentId(int $parentId): array
private array $paymentColumns = [];
private array $excludedPaymentStatuses = [
'void',
'voided',
'refunded',
'failed',
'chargeback',
'declined',
'reversed',
'canceled',
'cancelled',
];
public function __construct(?ConnectionInterface $db = null, ?ValidationInterface $validation = null)
{
return $this->where('parent_id', $parentId)
->orderBy('payment_date', 'DESC')
->findAll();
parent::__construct($db, $validation);
$this->paymentColumns = $this->getTableColumns($this->table);
// Remove fields that do not exist in the live DB.
// This prevents errors like "Unknown column balance".
$this->allowedFields = array_values(array_filter(
$this->allowedFields,
fn (string $field): bool => in_array($field, $this->paymentColumns, true)
));
// Remove validation rules for columns that do not exist.
foreach (array_keys($this->validationRules) as $field) {
if (!in_array($field, $this->allowedFields, true)) {
unset($this->validationRules[$field]);
unset($this->validationMessages[$field]);
}
}
}
/**
* Calculate the total paid amount for a specific parent.
* Get payments by parent ID with invoice context.
*
* @param int $parentId
* @return float
* The source of truth for invoice total/status/balance is invoices, not payments.
*/
public function getPaymentsByParentId(int $parentId, ?string $schoolYear = null): array
{
return $this->parentPaymentHistoryQuery($parentId, $schoolYear)->findAll();
}
/**
* Build parent payment history query with invoice context.
*
* Kept public so controllers can paginate without duplicating select/join logic.
*/
public function parentPaymentHistoryQuery(int $parentId, ?string $schoolYear = null): self
{
$paymentBalanceSelect = $this->getPaymentBalanceSelectExpression('payments');
$invoiceBalanceSelect = $this->columnExists('invoices', 'balance')
? 'invoices.balance AS invoice_current_balance'
: '0.00 AS invoice_current_balance';
$select = [
'payments.id',
'payments.invoice_id',
'invoices.invoice_number',
'payments.transaction_id',
'payments.paid_amount',
'payments.payment_method',
'payments.check_number',
'payments.check_file',
'payments.payment_date',
'payments.installment_seq',
'payments.number_of_installments',
$paymentBalanceSelect,
'payments.status AS payment_status',
'invoices.total_amount AS invoice_total',
$invoiceBalanceSelect,
'invoices.status AS invoice_status',
'invoices.school_year',
];
$model = new self($this->db);
$builder = $model->select(implode(', ', $select), false)
->join('invoices', 'invoices.id = payments.invoice_id', 'inner')
->where('payments.parent_id', $parentId);
if ($schoolYear !== null && $schoolYear !== '') {
$builder->where('invoices.school_year', $schoolYear);
}
return $builder
->orderBy('payments.payment_date', 'DESC')
->orderBy('payments.id', 'DESC');
}
/**
* Calculate the total paid amount for a parent in a school year.
*
* Uses invoices.school_year so old poisoned payment term data does not corrupt totals.
*/
public function getTotalPaidByParentId(int $parentId, string $schoolYear): float
{
$db = \Config\Database::connect();
$result = $db->table('payments')
->selectSum('paid_amount', 'total_paid')
->where('parent_id', $parentId)
->where('school_year', $schoolYear)
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
$result = $this->db->table('payments p')
->selectSum('p.paid_amount', 'total_paid')
->join('invoices i', 'i.id = p.invoice_id', 'inner')
->where('p.parent_id', $parentId)
->where('i.school_year', $schoolYear)
->where($this->successfulPaymentWhereSql('p.status'), null, false)
->get()
->getRowArray();
return $result && isset($result['total_paid']) ? (float) $result['total_paid'] : 0.00;
return $result && isset($result['total_paid'])
? (float) $result['total_paid']
: 0.00;
}
/**
* Update balance for a specific payment.
* Legacy method.
*
* @param int $paymentId
* @param float $amountPaid
* @return bool
* This should not be used for new payment recording.
* New payments should be inserted as immutable payment rows and invoices recalculated by InvoiceLedgerService.
*/
public function updateBalance(int $paymentId, float $amountPaid): bool
{
if ($amountPaid <= 0) {
return false;
}
$payment = $this->find($paymentId);
if (!$payment) {
return false;
}
$newBalance = $payment['balance'] - $amountPaid;
$updateData = [
'paid_amount' => round((float) ($payment['paid_amount'] ?? 0) + $amountPaid, 2),
];
return $this->update($paymentId, [
'paid_amount' => $payment['paid_amount'] + $amountPaid,
'balance' => $newBalance
]);
$balanceField = $this->getPaymentBalanceField();
if ($balanceField !== null && array_key_exists($balanceField, $payment)) {
$updateData[$balanceField] = max(
0.00,
round((float) ($payment[$balanceField] ?? 0) - $amountPaid, 2)
);
}
return $this->update($paymentId, $updateData);
}
/**
* Get payments by school year.
*
* @param string $schoolYear
* @return array
* Uses invoice school year when possible because payment.school_year may have old bad data.
*/
public function getPaymentsByYear(string $schoolYear): array
{
return $this->where('school_year', $schoolYear)
->orderBy('payment_date', 'DESC')
$paymentBalanceSelect = $this->getPaymentBalanceSelectExpression('payments');
$select = [
'payments.*',
'invoices.invoice_number',
'invoices.total_amount AS invoice_total',
'invoices.status AS invoice_status',
$paymentBalanceSelect,
];
return $this->select(implode(', ', $select), false)
->join('invoices', 'invoices.id = payments.invoice_id', 'inner')
->where('invoices.school_year', $schoolYear)
->orderBy('payments.payment_date', 'DESC')
->orderBy('payments.id', 'DESC')
->findAll();
}
/**
* Generate a new transaction ID.
* Generate a transaction ID.
*
* @return string
* This is okay for legacy/manual use, but a DB UNIQUE KEY on transaction_id is still required.
*/
public function generateNewTransactionId(): string
{
@@ -173,41 +316,115 @@ class PaymentModel extends Model
->first();
if ($latest && isset($latest['transaction_id'])) {
$lastNumber = (int) str_replace($prefix, '', $latest['transaction_id']);
$lastNumber = (int) str_replace($prefix, '', (string) $latest['transaction_id']);
$newNumber = $lastNumber + 1;
} else {
$newNumber = 1;
}
return $prefix . str_pad($newNumber, 6, '0', STR_PAD_LEFT);
return $prefix . str_pad((string) $newNumber, 6, '0', STR_PAD_LEFT);
}
/**
* Get latest successful payment per invoice.
*
* Uses latest payment ID instead of latest date only.
* Date-only matching can return duplicates when several payments happen on the same day.
*/
public function getPaymentsByInvoice($invoiceIds): array
{
// Normalize input
if (!is_array($invoiceIds)) {
$invoiceIds = [$invoiceIds];
}
$invoiceIds = array_values(array_filter(array_map('intval', $invoiceIds)));
if (empty($invoiceIds)) {
return [];
}
// Subquery: latest payment_date per invoice (Full/Partial only)
$latestSub = $this->db->table('payments')
->select('invoice_id, MAX(payment_date) AS max_date')
->whereIn('status', ['Full', 'Paid', 'Partially Paid'])
->select('invoice_id, MAX(id) AS max_id')
->whereIn('invoice_id', $invoiceIds)
->where('paid_amount >', 0)
->where($this->successfulPaymentWhereSql('status'), null, false)
->groupBy('invoice_id')
->getCompiledSelect();
// Main query: join payments to the latest per invoice
$rows = $this->db->table('payments p')
->select('p.invoice_id, p.paid_amount AS last_paid_amount, p.payment_date AS last_payment_date, p.status AS last_payment_status')
->join("($latestSub) latest", 'latest.invoice_id = p.invoice_id AND latest.max_date = p.payment_date', 'inner', false) // <-- escape=false
return $this->db->table('payments p')
->select([
'p.invoice_id',
'p.id AS payment_id',
'p.paid_amount AS last_paid_amount',
'p.payment_date AS last_payment_date',
'p.status AS last_payment_status',
'p.transaction_id',
'p.payment_method',
'p.check_number',
])
->join(
"($latestSub) latest",
'latest.invoice_id = p.invoice_id AND latest.max_id = p.id',
'inner',
false
)
->whereIn('p.invoice_id', $invoiceIds)
->whereIn('p.status', ['Full', 'Paid', 'Partially Paid'])
->get()
->getResultArray();
}
return $rows;
private function getPaymentBalanceField(): ?string
{
foreach (['balance_after_payment', 'balance', 'balance_amount'] as $field) {
if (in_array($field, $this->paymentColumns, true)) {
return $field;
}
}
return null;
}
private function getPaymentBalanceSelectExpression(string $alias = 'payments'): string
{
$field = $this->getPaymentBalanceField();
if ($field === null) {
return '0.00 AS balance_after_payment';
}
return "{$alias}.{$field} AS balance_after_payment";
}
private function successfulPaymentWhereSql(string $column): string
{
$escapedStatuses = array_map(
fn (string $status): string => $this->db->escape($status),
$this->excludedPaymentStatuses
);
return 'LOWER(COALESCE(' . $column . ', \'\')) NOT IN (' . implode(', ', $escapedStatuses) . ')';
}
private function getTableColumns(string $table): array
{
try {
return $this->db->getFieldNames($table);
} catch (\Throwable $e) {
log_message('error', '[PaymentModel] Could not read table columns for {table}: {error}', [
'table' => $table,
'error' => $e->getMessage(),
]);
return [];
}
}
private function columnExists(string $table, string $column): bool
{
try {
return $this->db->fieldExists($column, $table);
} catch (\Throwable $e) {
return false;
}
}
}
+10 -20
View File
@@ -18,18 +18,11 @@ class PaymentTransactionModel extends Model
'payment_method',
'payment_status',
'transaction_fee',
'payment_reference',
'semester',
'school_year',
'is_full_payment', // Flag to track full payment status
'created_at',
'updated_at'
'school_year'
];
// Set automatic timestamps
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $useTimestamps = false;
// Validation rules
protected $validationRules = [
@@ -38,8 +31,8 @@ class PaymentTransactionModel extends Model
'amount' => 'required|decimal',
'payment_method' => 'required|string|max_length[50]',
'payment_status' => 'required|string|max_length[50]',
'payment_reference' => 'permit_empty|string|max_length[255]',
'is_full_payment' => 'required|in_list[0,1]', // 0 for installment, 1 for full payment
'semester' => 'permit_empty|string|max_length[30]',
'school_year' => 'permit_empty|string|max_length[9]',
];
// Custom error messages
@@ -64,13 +57,6 @@ class PaymentTransactionModel extends Model
'required' => 'The payment status is required.',
'max_length' => 'The payment status must not exceed 50 characters.',
],
'payment_reference' => [
'max_length' => 'The payment reference must not exceed 255 characters.',
],
'is_full_payment' => [
'required' => 'The full payment flag is required.',
'in_list' => 'The full payment flag must be either 0 (installment) or 1 (full payment).',
],
];
/**
@@ -106,7 +92,9 @@ class PaymentTransactionModel extends Model
*/
public function updateTransactionStatus($transactionId, $status)
{
return $this->update($transactionId, ['payment_status' => $status]);
return $this->where('transaction_id', $transactionId)
->set(['payment_status' => $status])
->update();
}
/**
@@ -130,7 +118,9 @@ class PaymentTransactionModel extends Model
*/
public function updateTransactionFee($transactionId, $transactionFee)
{
return $this->update($transactionId, ['transaction_fee' => $transactionFee]);
return $this->where('transaction_id', $transactionId)
->set(['transaction_fee' => $transactionFee])
->update();
}
/**
-1
View File
@@ -12,7 +12,6 @@ class PlacementLevelModel extends Model
protected $allowedFields = [
'student_id',
'level',
'school_year',
'created_by',
'updated_by',
'created_at',
+2 -7
View File
@@ -12,8 +12,8 @@ class PreferencesModel extends Model
// Allowed fields to enable mass assignment
protected $allowedFields = [
'user_id', // Foreign key linking preferences to a user
'receive_email_notifications', // Email notifications preference
'receive_sms_notifications', // SMS notifications preference
'notification_email', // Email notifications preference
'notification_sms', // SMS notifications preference
'theme', // Theme preference (e.g., light or dark)
'language', // Language preference
'timezone', // Timezone preference
@@ -22,11 +22,6 @@ class PreferencesModel extends Model
'menu_custom_bg', // Custom menu background color
'menu_custom_text', // Custom menu text color
'menu_custom_mode', // Custom menu mode: light|dark
'receive_push_notifications', // Push notifications preference
'daily_summary_email', // Daily summary email preference
'privacy_mode', // Privacy mode setting
'marketing_emails', // Marketing emails preference
'account_activity_alerts', // Account activity alerts preference
'created_at', // Timestamp of when the record was created
'updated_at' // Timestamp of when the record was last updated
];
@@ -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',
];
}
+53
View File
@@ -0,0 +1,53 @@
<?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
{
$rows = $this->where('status', 'active')
->orderBy('id', 'DESC')
->findAll(2);
if (count($rows) !== 1) {
return null;
}
return $rows[0];
}
}
@@ -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',
];
}
+1 -2
View File
@@ -12,12 +12,11 @@ class SectionModel extends Model
protected $allowedFields = [
'section_name',
'description',
'created_at',
'updated_at',
'updated_by'
];
protected $useTimestamps = true;
protected $useTimestamps = false;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';

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