Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e06ccc9cc0 | |||
| c7f67da9bf | |||
| ed95286050 | |||
| ec9fca8c45 | |||
| ed11cccecc | |||
| 6e8da3cc2c | |||
| 384ae8b719 | |||
| 654453222f | |||
| a18e8b92a6 |
@@ -0,0 +1,60 @@
|
||||
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
|
||||
database.tests.hostname: 127.0.0.1
|
||||
database.tests.database: alrahma_test
|
||||
database.tests.username: alrahma
|
||||
database.tests.password: alrahma
|
||||
database.tests.DBDriver: MySQLi
|
||||
database.tests.DBPrefix: ''
|
||||
database.tests.port: 3306
|
||||
|
||||
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: none
|
||||
|
||||
- name: Validate Composer config
|
||||
run: composer validate --no-check-publish --strict
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer install --no-interaction --prefer-dist --no-progress
|
||||
|
||||
- name: Run tests
|
||||
run: composer test
|
||||
@@ -31,6 +31,7 @@ class Filters extends BaseConfig
|
||||
'cleanupScheduler' => \App\Filters\CleanupScheduler::class,
|
||||
'permission' => \App\Filters\PermissionFilter::class,
|
||||
'timezone' => \App\Filters\TimezoneFilter::class,
|
||||
'schoolYear' => \App\Filters\RequireSchoolYearFilter::class,
|
||||
];
|
||||
|
||||
|
||||
|
||||
+18
-5
@@ -645,6 +645,8 @@ $routes->post('admin/broadcast-email/upload-image', 'View\BroadcastEmailControll
|
||||
|
||||
$routes->get('payment/financial_report', 'View\FinancialController::financialReport', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('financial-report/financialReportSummary', 'View\FinancialController::financialReportSummary', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('financial-report/downloadSummaryCsv', 'View\FinancialController::downloadSummaryCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('financial-report/downloadSummaryAllDetailsCsv', 'View\FinancialController::downloadSummaryAllDetailsCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('payment/download_csv', 'View\FinancialController::downloadCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('administrator/tuition-forecast', 'View\TuitionForecastController::index', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->post('administrator/tuition-forecast/calculate', 'View\TuitionForecastController::calculate', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
@@ -741,11 +743,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']);
|
||||
@@ -1135,6 +1132,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');
|
||||
|
||||
@@ -180,4 +180,66 @@ 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)
|
||||
);
|
||||
}
|
||||
|
||||
public static function schoolYearWriteGuard(bool $getShared = true): \App\Services\SchoolYearWriteGuard
|
||||
{
|
||||
if ($getShared) {
|
||||
return static::getSharedInstance('schoolYearWriteGuard');
|
||||
}
|
||||
|
||||
return new \App\Services\SchoolYearWriteGuard();
|
||||
}
|
||||
|
||||
public static function schoolYearValidation(bool $getShared = true): \App\Services\SchoolYearValidationService
|
||||
{
|
||||
if ($getShared) {
|
||||
return static::getSharedInstance('schoolYearValidation');
|
||||
}
|
||||
|
||||
return new \App\Services\SchoolYearValidationService(
|
||||
model(\App\Models\SchoolYearModel::class)
|
||||
);
|
||||
}
|
||||
|
||||
public static function schoolYearManagement(bool $getShared = true): \App\Services\SchoolYearManagementService
|
||||
{
|
||||
if ($getShared) {
|
||||
return static::getSharedInstance('schoolYearManagement');
|
||||
}
|
||||
|
||||
return new \App\Services\SchoolYearManagementService(
|
||||
model(\App\Models\SchoolYearModel::class),
|
||||
model(\App\Models\ConfigurationModel::class),
|
||||
model(\App\Models\SchoolYearTransitionLogModel::class),
|
||||
model(\App\Models\SchoolYearClosingBatchModel::class),
|
||||
static::schoolYearValidation(),
|
||||
\Config\Database::connect()
|
||||
);
|
||||
}
|
||||
|
||||
public static function schoolYearClosing(bool $getShared = true): \App\Services\SchoolYearClosingService
|
||||
{
|
||||
if ($getShared) {
|
||||
return static::getSharedInstance('schoolYearClosing');
|
||||
}
|
||||
|
||||
return new \App\Services\SchoolYearClosingService(
|
||||
model(\App\Models\SchoolYearModel::class),
|
||||
model(\App\Models\SchoolYearClosingBatchModel::class),
|
||||
model(\App\Models\SchoolYearClosingItemModel::class),
|
||||
static::schoolYearManagement(),
|
||||
\Config\Database::connect()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Administrator;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Models\SchoolYearModel;
|
||||
use Throwable;
|
||||
|
||||
class SchoolYearClosingController extends BaseController
|
||||
{
|
||||
public function preview(int $id)
|
||||
{
|
||||
try {
|
||||
$targetId = $this->normalizeInt($this->request->getGet('target_school_year_id'));
|
||||
|
||||
return view('school_years/closing_preview', [
|
||||
'preview' => service('schoolYearClosing')->preview($id, $targetId),
|
||||
'latestBatch' => service('schoolYearClosing')->latestBatch($id),
|
||||
'schoolYears' => (new SchoolYearModel())->orderBy('name', 'DESC')->findAll(),
|
||||
]);
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function start(int $id)
|
||||
{
|
||||
try {
|
||||
$targetId = $this->normalizeInt($this->request->getPost('target_school_year_id'));
|
||||
if ($targetId === null) {
|
||||
return redirect()->back()->with('error', 'Select a target school year.');
|
||||
}
|
||||
|
||||
service('schoolYearClosing')->start($id, $targetId, $this->userId());
|
||||
return redirect()->to('/administrator/school-years/' . $id . '/closing/preview')->with('success', 'Closing started.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function execute(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearClosing')->execute($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years/' . $id . '/closing/preview')->with('success', 'Carry-forward batch executed.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function complete(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearClosing')->complete($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'School year closed.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function cancel(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearClosing')->cancel($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'Closing cancelled.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function normalizeInt(mixed $value): ?int
|
||||
{
|
||||
return is_numeric($value) && (int) $value > 0 ? (int) $value : null;
|
||||
}
|
||||
|
||||
private function userId(): ?int
|
||||
{
|
||||
$id = session('user_id') ?? session('id');
|
||||
|
||||
return is_numeric($id) ? (int) $id : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Administrator;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Support\SchoolYear\SchoolYearStatus;
|
||||
use Throwable;
|
||||
|
||||
class SchoolYearController extends BaseController
|
||||
{
|
||||
private SchoolYearModel $schoolYearModel;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->schoolYearModel = new SchoolYearModel();
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
$schoolYears = $this->schoolYearModel
|
||||
->orderBy('name', 'DESC')
|
||||
->findAll();
|
||||
|
||||
$activeYear = null;
|
||||
$nextDraftYear = null;
|
||||
$closingYear = null;
|
||||
$archivedCount = 0;
|
||||
|
||||
foreach ($schoolYears as $year) {
|
||||
$status = (string) ($year['status'] ?? '');
|
||||
if ($status === SchoolYearStatus::ACTIVE && $activeYear === null) {
|
||||
$activeYear = $year;
|
||||
}
|
||||
if ($status === SchoolYearStatus::DRAFT && $nextDraftYear === null) {
|
||||
$nextDraftYear = $year;
|
||||
}
|
||||
if ($status === SchoolYearStatus::CLOSING && $closingYear === null) {
|
||||
$closingYear = $year;
|
||||
}
|
||||
if ($status === SchoolYearStatus::ARCHIVED) {
|
||||
$archivedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return view('school_years/index', [
|
||||
'schoolYears' => $schoolYears,
|
||||
'statuses' => SchoolYearStatus::ALL,
|
||||
'activeYear' => $activeYear,
|
||||
'nextDraftYear' => $nextDraftYear,
|
||||
'closingYear' => $closingYear,
|
||||
'archivedCount' => $archivedCount,
|
||||
'latestTransitions' => service('schoolYearManagement')->latestTransitionByYear(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store()
|
||||
{
|
||||
try {
|
||||
service('schoolYearManagement')->createDraft($this->request->getPost(), $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'Draft school year created.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->withInput()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function update(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearManagement')->updateMetadata($id, $this->request->getPost(), $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'School year metadata updated.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->withInput()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function activate(int $id)
|
||||
{
|
||||
try {
|
||||
if ($this->request->getPost('confirm_activation') !== '1') {
|
||||
return redirect()->to('/administrator/school-years')->with('error', 'Activation confirmation is required.');
|
||||
}
|
||||
|
||||
service('schoolYearManagement')->activate($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'School year activated. Any previous active year is now in closing.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteDraft(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearManagement')->deleteDraft($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'Draft school year deleted.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function archive(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearManagement')->archive($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'School year archived.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function reopen(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearManagement')->reopen($id, (string) $this->request->getPost('reason'), $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'School year reopened.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function userId(): ?int
|
||||
{
|
||||
$id = session('user_id') ?? session('id');
|
||||
|
||||
return is_numeric($id) ? (int) $id : null;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ use CodeIgniter\HTTP\RequestInterface;
|
||||
use CodeIgniter\HTTP\ResponseInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use App\Services\ApiClient;
|
||||
use App\Support\SchoolYear\SchoolYearContext;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Class BaseController
|
||||
@@ -88,6 +90,27 @@ 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 assertSchoolYearWritable(
|
||||
SchoolYearContext $context,
|
||||
bool $allowDraftForAdmin = false,
|
||||
bool $isAdmin = false
|
||||
): void {
|
||||
service('schoolYearWriteGuard')->assertWritable($context, $allowDraftForAdmin, $isAdmin);
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
|
||||
@@ -730,18 +730,15 @@ class AdministratorController extends BaseController
|
||||
->join('users u', 'u.id = tc.teacher_id', 'left')
|
||||
->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 +870,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')
|
||||
|
||||
@@ -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,
|
||||
'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,151 @@ 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);
|
||||
|
||||
$hasSchoolYear = $this->tableHasColumn('inventory_items', 'school_year');
|
||||
$hasSemester = $this->tableHasColumn('inventory_items', 'semester');
|
||||
$hasName = $this->tableHasColumn('inventory_items', 'name');
|
||||
|
||||
$joinRows = $this->db->table('inventory_items ii')
|
||||
->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 !== '') {
|
||||
|
||||
if ($hasSchoolYear && $schoolYear !== '') {
|
||||
$joinRows->where('ii.school_year', $schoolYear);
|
||||
}
|
||||
|
||||
if ($hasSemester && $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));
|
||||
$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)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 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')
|
||||
->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')
|
||||
->select('name AS item_name, COALESCE(SUM(CASE WHEN good_qty IS NOT NULL THEN good_qty WHEN `condition` = "good" THEN quantity ELSE 0 END), 0) AS available', false)
|
||||
->where('type', 'classroom')
|
||||
->where('school_year', $schoolYear)
|
||||
->whereIn('name', $allowed);
|
||||
if ($limitToSemester && $semester !== '') {
|
||||
|
||||
if ($hasSchoolYear && $schoolYear !== '') {
|
||||
$nameRows->where('school_year', $schoolYear);
|
||||
}
|
||||
|
||||
if ($hasSemester && $semester !== '') {
|
||||
$nameRows->where('semester', $semester);
|
||||
}
|
||||
$nameRows = $nameRows->groupBy('name')->get()->getResultArray();
|
||||
|
||||
foreach ($nameRows as $r) {
|
||||
$name = (string)($r['item_name'] ?? '');
|
||||
if ($name !== '' && isset($inventoryMap[$name])) {
|
||||
$inventoryMap[$name] = max($inventoryMap[$name], (int)($r['available'] ?? 0));
|
||||
$nameRows = $nameRows
|
||||
->groupBy('name')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
foreach ($nameRows as $row) {
|
||||
$name = (string) ($row['item_name'] ?? '');
|
||||
|
||||
if ($name !== '' && array_key_exists($name, $inventoryMap)) {
|
||||
$inventoryMap[$name] = max(
|
||||
$inventoryMap[$name],
|
||||
(int) ($row['available'] ?? 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -74,7 +74,7 @@ class InvoiceController extends ResourceController
|
||||
$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') ?? 180);
|
||||
$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();
|
||||
|
||||
@@ -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,13 @@ class PaymentController extends ResourceController
|
||||
]);
|
||||
}
|
||||
|
||||
private function getSelectedPaymentHistoryYear(): ?string
|
||||
{
|
||||
$selectedYear = $this->request->getGet('school_year') ?? $this->schoolYear;
|
||||
|
||||
return $selectedYear !== '' ? $selectedYear : null;
|
||||
}
|
||||
|
||||
// View: Create a new payment plan
|
||||
public function create()
|
||||
{
|
||||
@@ -346,12 +348,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 +974,7 @@ class PaymentController extends ResourceController
|
||||
$checkFile,
|
||||
$transactionId,
|
||||
$paymentDate,
|
||||
$this->schoolYear,
|
||||
$this->semester,
|
||||
$invYear,
|
||||
$checkNumber,
|
||||
$installmentSeq,
|
||||
(array) $this->invoiceModel->find($invoiceId),
|
||||
@@ -1015,7 +1016,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 +1271,6 @@ class PaymentController extends ResourceController
|
||||
$transactionId = null,
|
||||
$paymentDate = null,
|
||||
$schoolYear = null,
|
||||
$semester = null,
|
||||
$checkNumber = null,
|
||||
?int $installmentSeq = null,
|
||||
?array $invoice = null,
|
||||
@@ -1315,8 +1315,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)) {
|
||||
|
||||
@@ -611,14 +611,18 @@ class ReimbursementController extends BaseController
|
||||
}
|
||||
|
||||
$expenseId = (int) $this->request->getPost('expense_id');
|
||||
|
||||
$batchIdRaw = $this->request->getPost('batch_id');
|
||||
$batchId = (int) $batchIdRaw;
|
||||
|
||||
$fallbackBatchNumber = $this->request->getPost('batch_number');
|
||||
if ($batchId <= 0 && $fallbackBatchNumber !== null && trim((string) $fallbackBatchNumber) !== '') {
|
||||
$batchId = (int) $fallbackBatchNumber;
|
||||
}
|
||||
|
||||
$adminIdRaw = $this->request->getPost('admin_id');
|
||||
$adminId = ($adminIdRaw === '' || $adminIdRaw === null) ? null : (int) $adminIdRaw;
|
||||
|
||||
$reimbursementId = (int) $this->request->getPost('reimbursement_id') ?: null;
|
||||
|
||||
if ($expenseId <= 0) {
|
||||
@@ -630,123 +634,185 @@ class ReimbursementController extends BaseController
|
||||
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
$newHashResponse = function (array $payload = []) {
|
||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||
|
||||
return $this->response
|
||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||
->setJSON(array_merge($payload, [
|
||||
'csrf_hash' => $newHash,
|
||||
]));
|
||||
};
|
||||
|
||||
$this->db->transBegin();
|
||||
|
||||
try {
|
||||
$activeItem = $this->batchItemModel
|
||||
->where('expense_id', $expenseId)
|
||||
->where('unassigned_at IS NULL', null, false)
|
||||
->first();
|
||||
|
||||
/**
|
||||
* If no batch is provided, remove the item from active batch processing.
|
||||
* This means "unassigned from batch", not "unassigned admin".
|
||||
*/
|
||||
if ($batchId <= 0) {
|
||||
if ($activeItem) {
|
||||
$this->batchItemModel->update((int) $activeItem['id'], ['unassigned_at' => $now]);
|
||||
$this->batchItemModel->update((int) $activeItem['id'], [
|
||||
'unassigned_at' => $now,
|
||||
]);
|
||||
|
||||
if (!$reimbursementId && !empty($activeItem['reimbursement_id'])) {
|
||||
$reimbursementId = (int) $activeItem['reimbursement_id'];
|
||||
}
|
||||
}
|
||||
|
||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||
return $this->response
|
||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||
->setJSON([
|
||||
if (!$this->db->transStatus()) {
|
||||
throw new \RuntimeException('Transaction failed while unassigning batch item.');
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
|
||||
return $newHashResponse([
|
||||
'success' => true,
|
||||
'batch_id' => 0,
|
||||
'admin_id' => null,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
'csrf_hash' => $newHash,
|
||||
]);
|
||||
}
|
||||
|
||||
$batch = $this->batchModel->find($batchId);
|
||||
if (!$batch || strtolower((string) ($batch['status'] ?? 'open')) !== 'open') {
|
||||
$this->db->transRollback();
|
||||
|
||||
return $this->response->setStatusCode(404)->setJSON([
|
||||
'success' => false,
|
||||
'error' => 'Batch not found or already closed.',
|
||||
]);
|
||||
}
|
||||
|
||||
$currentAdmin = $activeItem ? (int) ($activeItem['admin_id'] ?? 0) : null;
|
||||
if (!$reimbursementId) {
|
||||
if ($activeItem && !empty($activeItem['reimbursement_id'])) {
|
||||
$reimbursementId = (int) $activeItem['reimbursement_id'];
|
||||
} else {
|
||||
$reimbursementId = $this->lookupReimbursementId($expenseId);
|
||||
}
|
||||
}
|
||||
|
||||
$activeSameBatch = $activeItem && (int) ($activeItem['batch_id'] ?? 0) === $batchId;
|
||||
if ($activeSameBatch && ($currentAdmin === ($adminId ?? 0))) {
|
||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||
return $this->response
|
||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||
->setJSON([
|
||||
$currentAdmin = $activeItem ? (int) ($activeItem['admin_id'] ?? 0) : null;
|
||||
$requestedAdmin = $adminId ?? 0;
|
||||
|
||||
/**
|
||||
* If the item is already active in the same batch/admin slot, just return success.
|
||||
*/
|
||||
if ($activeSameBatch && $currentAdmin === $requestedAdmin) {
|
||||
if (!$this->db->transStatus()) {
|
||||
throw new \RuntimeException('Transaction failed while checking existing assignment.');
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
|
||||
return $newHashResponse([
|
||||
'success' => true,
|
||||
'batch_id' => $batchId,
|
||||
'admin_id' => $adminId,
|
||||
'reimbursement_id' => $activeItem['reimbursement_id'] ?? null,
|
||||
'csrf_hash' => $newHash,
|
||||
'reimbursement_id' => $activeItem['reimbursement_id'] ?? $reimbursementId,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* If same batch but different admin, update the existing active row.
|
||||
*
|
||||
* Important:
|
||||
* admin_id = null means active in the batch but not assigned to an admin.
|
||||
* unassigned_at != null means removed from active batch processing.
|
||||
*/
|
||||
if ($activeSameBatch) {
|
||||
if (!$reimbursementId) {
|
||||
$reimbursementId = $activeItem['reimbursement_id'] ? (int) $activeItem['reimbursement_id'] : $this->lookupReimbursementId($expenseId);
|
||||
}
|
||||
$updatePayload = [
|
||||
$this->batchItemModel->update((int) $activeItem['id'], [
|
||||
'admin_id' => $adminId,
|
||||
'assigned_at' => $now,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
'unassigned_at' => $adminId === null ? $now : null,
|
||||
];
|
||||
$this->batchItemModel->update((int) $activeItem['id'], $updatePayload);
|
||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||
return $this->response
|
||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||
->setJSON([
|
||||
'unassigned_at' => null,
|
||||
]);
|
||||
|
||||
if (!$this->db->transStatus()) {
|
||||
throw new \RuntimeException('Transaction failed while updating existing assignment.');
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
|
||||
return $newHashResponse([
|
||||
'success' => true,
|
||||
'batch_id' => $batchId,
|
||||
'admin_id' => $adminId,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
'csrf_hash' => $newHash,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* If the item is active in another batch, soft-unassign that row first.
|
||||
*/
|
||||
if ($activeItem) {
|
||||
$this->batchItemModel->update((int) $activeItem['id'], ['unassigned_at' => $now]);
|
||||
if (!$reimbursementId && !empty($activeItem['reimbursement_id'])) {
|
||||
$reimbursementId = (int) $activeItem['reimbursement_id'];
|
||||
}
|
||||
$this->batchItemModel->update((int) $activeItem['id'], [
|
||||
'unassigned_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
if (!$reimbursementId) {
|
||||
$reimbursementId = $this->lookupReimbursementId($expenseId);
|
||||
}
|
||||
/**
|
||||
* Critical fix:
|
||||
* Check whether this expense was previously assigned to this batch.
|
||||
* Because uq_batch_expense(batch_id, expense_id) blocks duplicate rows,
|
||||
* we must reactivate/update the old row instead of inserting again.
|
||||
*/
|
||||
$existingBatchItem = $this->batchItemModel
|
||||
->where('batch_id', $batchId)
|
||||
->where('expense_id', $expenseId)
|
||||
->first();
|
||||
|
||||
$insertData = [
|
||||
$assignmentData = [
|
||||
'batch_id' => $batchId,
|
||||
'expense_id' => $expenseId,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
'admin_id' => $adminId,
|
||||
'assigned_at' => $now,
|
||||
'unassigned_at' => null,
|
||||
'school_year' => $this->schoolYear,
|
||||
'semester' => $this->semester,
|
||||
];
|
||||
|
||||
try {
|
||||
$this->batchItemModel->insert($insertData);
|
||||
if ($existingBatchItem) {
|
||||
$this->batchItemModel->update((int) $existingBatchItem['id'], $assignmentData);
|
||||
} else {
|
||||
$this->batchItemModel->insert($assignmentData);
|
||||
}
|
||||
|
||||
if (!$this->db->transStatus()) {
|
||||
throw new \RuntimeException('Transaction failed while saving assignment.');
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
|
||||
return $newHashResponse([
|
||||
'success' => true,
|
||||
'batch_id' => $batchId,
|
||||
'admin_id' => $adminId,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'Failed to assign expense #{expense} to batch #{batch}: {msg}', [
|
||||
$this->db->transRollback();
|
||||
|
||||
log_message('error', 'Failed to update batch assignment for expense #{expense}, batch #{batch}: {msg}', [
|
||||
'expense' => $expenseId,
|
||||
'batch' => $batchId,
|
||||
'msg' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->response->setStatusCode(500)->setJSON([
|
||||
'success' => false,
|
||||
'error' => 'Unable to update batch assignment right now.',
|
||||
]);
|
||||
}
|
||||
|
||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||
|
||||
return $this->response
|
||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||
->setJSON([
|
||||
'success' => true,
|
||||
'batch_id' => $batchId,
|
||||
'admin_id' => $adminId,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
'csrf_hash' => $newHash,
|
||||
]);
|
||||
}
|
||||
|
||||
public function lockBatch()
|
||||
|
||||
@@ -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
|
||||
{
|
||||
}
|
||||
@@ -71,12 +71,13 @@ class TuitionForecastController extends BaseController
|
||||
fputcsv($handle, ['Calculator Mode', $result['calculator_mode']]);
|
||||
fputcsv($handle, []);
|
||||
fputcsv($handle, ['Summary']);
|
||||
fputcsv($handle, ['Families', 'Students', 'Billable Students', 'Unit Price', 'Old Projected Income', 'New Projected Income', 'Difference']);
|
||||
fputcsv($handle, ['Families', 'Students', 'Billable Students', 'Grade Unit Price', 'Youth Unit Price', 'Old Projected Income', 'New Projected Income', 'Difference']);
|
||||
fputcsv($handle, [
|
||||
$result['summary']['family_count'],
|
||||
$result['summary']['student_count'],
|
||||
$result['summary']['billable_student_count'],
|
||||
$result['summary']['unit_price'],
|
||||
$result['summary']['youth_unit_price'],
|
||||
$result['summary']['old_projected_income'] ?? $result['summary']['old_projected_tuition'],
|
||||
$result['summary']['new_projected_income'] ?? $result['summary']['new_projected_tuition'],
|
||||
$result['summary']['difference'],
|
||||
@@ -132,6 +133,7 @@ class TuitionForecastController extends BaseController
|
||||
'include_event_only' => $this->request->{$source}('include_event_only') ?? '0',
|
||||
'include_paid_invoices' => $this->request->{$source}('include_paid_invoices') ?? '0',
|
||||
'unit_price' => $this->request->{$source}('unit_price') ?? '',
|
||||
'youth_unit_price' => $this->request->{$source}('youth_unit_price') ?? '',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,14 +106,12 @@ class WhatsappController extends BaseController
|
||||
$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,
|
||||
];
|
||||
@@ -434,8 +432,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 +444,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 +594,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 +1189,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 +1202,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 +1288,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 +1296,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();
|
||||
|
||||
|
||||
@@ -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')) {
|
||||
@@ -94,7 +149,9 @@ class FinancialSystemLedgerCleanup extends Migration
|
||||
|
||||
$defaults = [
|
||||
'tuition_calculator_version' => 'old',
|
||||
'youth_fee' => '200.00',
|
||||
'new_tuition_full_amount' => '370.00',
|
||||
'new_tuition_youth_amount' => '200.00',
|
||||
'new_tuition_second_student_discount' => '50.00',
|
||||
'new_tuition_third_student_discount' => '50.00',
|
||||
'new_tuition_fourth_plus_discount' => '100.00',
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class UpdateYouthTuitionDefaults extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
if (!$this->db->tableExists('configuration')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->upsertConfig('youth_fee', '200.00', ['180', '180.00']);
|
||||
$this->upsertConfig('new_tuition_youth_amount', '200.00', ['180', '180.00']);
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
if (!$this->db->tableExists('configuration')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->rollbackConfig('youth_fee', '180.00');
|
||||
$this->rollbackConfig('new_tuition_youth_amount', '180.00');
|
||||
}
|
||||
|
||||
protected function upsertConfig(string $key, string $value, array $legacyValues = []): void
|
||||
{
|
||||
$row = $this->db->table('configuration')
|
||||
->select('id, config_value')
|
||||
->where('config_key', $key)
|
||||
->orderBy('id', 'ASC')
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if (!$row) {
|
||||
$this->db->table('configuration')->insert([
|
||||
'config_key' => $key,
|
||||
'config_value' => $value,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$current = trim((string) ($row['config_value'] ?? ''));
|
||||
if ($current === '' || in_array($current, $legacyValues, true)) {
|
||||
$this->db->table('configuration')
|
||||
->where('config_key', $key)
|
||||
->update(['config_value' => $value]);
|
||||
}
|
||||
}
|
||||
|
||||
protected function rollbackConfig(string $key, string $value): void
|
||||
{
|
||||
$this->db->table('configuration')
|
||||
->where('config_key', $key)
|
||||
->where('config_value', '200.00')
|
||||
->update(['config_value' => $value]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
<?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.'
|
||||
);
|
||||
}
|
||||
|
||||
// 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,
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove redundant columns. Dependent non-primary indexes are removed first.
|
||||
foreach ($this->tablesWithoutDirectYear as $table) {
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->dropIndexesContainingColumn($table, 'school_year');
|
||||
$this->dropChecksContainingColumn($table, 'school_year');
|
||||
$this->forge->dropColumn($table, 'school_year');
|
||||
}
|
||||
|
||||
foreach ($this->tablesWithoutDirectSemester as $table) {
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('semester', $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->dropIndexesContainingColumn($table, 'semester');
|
||||
$this->dropChecksContainingColumn($table, 'semester');
|
||||
$this->forge->dropColumn($table, 'semester');
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
<?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');
|
||||
}
|
||||
|
||||
foreach ($this->semesterDropTables as $table) {
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('semester', $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->dropIndexesContainingColumn($table, 'semester');
|
||||
$this->dropChecksContainingColumn($table, 'semester');
|
||||
$this->forge->dropColumn($table, 'semester');
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filters;
|
||||
|
||||
use CodeIgniter\Filters\FilterInterface;
|
||||
use CodeIgniter\HTTP\IncomingRequest;
|
||||
use CodeIgniter\HTTP\RequestInterface;
|
||||
use CodeIgniter\HTTP\ResponseInterface;
|
||||
use Throwable;
|
||||
|
||||
final class RequireSchoolYearFilter implements FilterInterface
|
||||
{
|
||||
public function before(RequestInterface $request, $arguments = null)
|
||||
{
|
||||
if (! $request instanceof IncomingRequest) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
service('schoolYearContext')->resolve($request);
|
||||
return null;
|
||||
} catch (Throwable $e) {
|
||||
log_message('warning', 'School-year request rejected: {message}', [
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return service('response')
|
||||
->setStatusCode(400)
|
||||
->setJSON([
|
||||
'status' => 400,
|
||||
'error' => 'Invalid school year',
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -307,6 +307,7 @@ class InvoiceLedgerService
|
||||
'second_student_fee' => $this->configurationModel->getConfig('second_student_fee'),
|
||||
'youth_fee' => $this->configurationModel->getConfig('youth_fee'),
|
||||
'new_tuition_full_amount' => $this->configurationModel->getConfig('new_tuition_full_amount'),
|
||||
'new_tuition_youth_amount' => $this->configurationModel->getConfig('new_tuition_youth_amount'),
|
||||
'new_tuition_second_student_discount' => $this->configurationModel->getConfig('new_tuition_second_student_discount'),
|
||||
'new_tuition_third_student_discount' => $this->configurationModel->getConfig('new_tuition_third_student_discount'),
|
||||
'new_tuition_fourth_plus_discount' => $this->configurationModel->getConfig('new_tuition_fourth_plus_discount'),
|
||||
|
||||
@@ -10,6 +10,7 @@ final class NewTuitionCalculatorService implements TuitionCalculatorInterface
|
||||
{
|
||||
$gradeFee = (int) ($config['grade_fee'] ?? 9);
|
||||
$fullAmountCents = $this->toCents($config['new_tuition_full_amount'] ?? 370);
|
||||
$youthAmountCents = $this->toCents($config['new_tuition_youth_amount'] ?? $config['youth_fee'] ?? 200);
|
||||
$secondDiscountCents = $this->toCents($config['new_tuition_second_student_discount'] ?? 50);
|
||||
$thirdDiscountCents = $this->toCents($config['new_tuition_third_student_discount'] ?? 50);
|
||||
$fourthPlusDiscountCents = $this->toCents($config['new_tuition_fourth_plus_discount'] ?? 100);
|
||||
@@ -22,9 +23,19 @@ final class NewTuitionCalculatorService implements TuitionCalculatorInterface
|
||||
});
|
||||
|
||||
$details = [];
|
||||
$regularPosition = 0;
|
||||
|
||||
foreach (array_values($students) as $index => $student) {
|
||||
$position = $index + 1;
|
||||
foreach (array_values($students) as $student) {
|
||||
$level = GradeLevelParser::parse($student['grade_level'] ?? null, $gradeFee);
|
||||
|
||||
if ($level > $gradeFee) {
|
||||
$position = null;
|
||||
$discountCents = 0;
|
||||
$rule = 'new_youth_unit_price';
|
||||
$baseAmountCents = $youthAmountCents;
|
||||
} else {
|
||||
$regularPosition++;
|
||||
$position = $regularPosition;
|
||||
|
||||
if ($position === 1) {
|
||||
$discountCents = 0;
|
||||
@@ -40,14 +51,17 @@ final class NewTuitionCalculatorService implements TuitionCalculatorInterface
|
||||
$rule = 'new_fourth_plus_student_discount';
|
||||
}
|
||||
|
||||
$amountCents = max(0, $fullAmountCents - $discountCents);
|
||||
$baseAmountCents = $fullAmountCents;
|
||||
}
|
||||
|
||||
$amountCents = max(0, $baseAmountCents - $discountCents);
|
||||
|
||||
$details[] = [
|
||||
'student_id' => (int) ($student['student_id'] ?? 0),
|
||||
'student_name' => (string) ($student['student_name'] ?? ''),
|
||||
'grade_level' => $student['grade_level'] ?? null,
|
||||
'family_position' => $position,
|
||||
'full_amount' => $this->fromCents($fullAmountCents),
|
||||
'full_amount' => $this->fromCents($baseAmountCents),
|
||||
'discount' => $this->fromCents($discountCents),
|
||||
'rule' => $rule,
|
||||
'amount' => $this->fromCents($amountCents),
|
||||
|
||||
@@ -11,7 +11,7 @@ final class OldTuitionCalculatorService implements TuitionCalculatorInterface
|
||||
$gradeFee = (int) ($config['grade_fee'] ?? 9);
|
||||
$firstStudentFee = $this->toCents($config['first_student_fee'] ?? 370);
|
||||
$secondStudentFee = $this->toCents($config['second_student_fee'] ?? 200);
|
||||
$youthFee = $this->toCents($config['youth_fee'] ?? 180);
|
||||
$youthFee = $this->toCents($config['youth_fee'] ?? 200);
|
||||
|
||||
usort($students, function (array $left, array $right) use ($gradeFee): int {
|
||||
$leftLevel = GradeLevelParser::parse($left['grade_level'] ?? null, $gradeFee);
|
||||
|
||||
@@ -43,6 +43,7 @@ class TuitionForecastService
|
||||
$mode = $this->normalizeMode($mode);
|
||||
$options = $this->normalizeOptions($options);
|
||||
$this->unitPriceOverride = $options['unit_price'];
|
||||
$this->youthUnitPriceOverride = $options['youth_unit_price'];
|
||||
$tuitionConfig = $this->getTuitionConfig();
|
||||
$familyRows = [];
|
||||
$summary = [
|
||||
@@ -57,6 +58,7 @@ class TuitionForecastService
|
||||
'projected_tuition' => '0.00',
|
||||
'projected_income' => '0.00',
|
||||
'unit_price' => '0.00',
|
||||
'youth_unit_price' => '0.00',
|
||||
];
|
||||
|
||||
$oldProjectedCents = 0;
|
||||
@@ -117,6 +119,7 @@ class TuitionForecastService
|
||||
$summary['projected_tuition'] = $mode === 'old' ? $summary['old_projected_tuition'] : $summary['new_projected_tuition'];
|
||||
$summary['projected_income'] = $mode === 'old' ? $summary['old_projected_income'] : $summary['new_projected_income'];
|
||||
$summary['unit_price'] = number_format((float) ($tuitionConfig['new_tuition_full_amount'] ?? 0), 2, '.', '');
|
||||
$summary['youth_unit_price'] = number_format((float) ($tuitionConfig['new_tuition_youth_amount'] ?? 0), 2, '.', '');
|
||||
|
||||
return [
|
||||
'school_year' => $schoolYear,
|
||||
@@ -232,6 +235,7 @@ class TuitionForecastService
|
||||
'include_event_only' => $this->toBool($options['include_event_only'] ?? false),
|
||||
'include_paid_invoices' => $this->toBool($options['include_paid_invoices'] ?? true),
|
||||
'unit_price' => $this->normalizeMoney($options['unit_price'] ?? null),
|
||||
'youth_unit_price' => $this->normalizeMoney($options['youth_unit_price'] ?? null),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -541,8 +545,9 @@ class TuitionForecastService
|
||||
'grade_fee' => $this->configurationModel->getConfig('grade_fee'),
|
||||
'first_student_fee' => $this->configurationModel->getConfig('first_student_fee'),
|
||||
'second_student_fee' => $this->configurationModel->getConfig('second_student_fee'),
|
||||
'youth_fee' => $this->configurationModel->getConfig('youth_fee'),
|
||||
'youth_fee' => $this->configurationModel->getConfig('youth_fee') ?? '200.00',
|
||||
'new_tuition_full_amount' => $this->normalizedUnitPriceOverride(),
|
||||
'new_tuition_youth_amount' => $this->normalizedYouthUnitPriceOverride(),
|
||||
'new_tuition_second_student_discount' => $this->configurationModel->getConfig('new_tuition_second_student_discount'),
|
||||
'new_tuition_third_student_discount' => $this->configurationModel->getConfig('new_tuition_third_student_discount'),
|
||||
'new_tuition_fourth_plus_discount' => $this->configurationModel->getConfig('new_tuition_fourth_plus_discount'),
|
||||
@@ -550,6 +555,7 @@ class TuitionForecastService
|
||||
}
|
||||
|
||||
protected ?string $unitPriceOverride = null;
|
||||
protected ?string $youthUnitPriceOverride = null;
|
||||
|
||||
protected function normalizedUnitPriceOverride(): string
|
||||
{
|
||||
@@ -557,6 +563,16 @@ class TuitionForecastService
|
||||
?? (string) ($this->configurationModel->getConfig('new_tuition_full_amount') ?? '0.00');
|
||||
}
|
||||
|
||||
protected function normalizedYouthUnitPriceOverride(): string
|
||||
{
|
||||
return $this->youthUnitPriceOverride
|
||||
?? (string) (
|
||||
$this->configurationModel->getConfig('new_tuition_youth_amount')
|
||||
?? $this->configurationModel->getConfig('youth_fee')
|
||||
?? '200.00'
|
||||
);
|
||||
}
|
||||
|
||||
protected function normalizeMoney($value): ?string
|
||||
{
|
||||
if ($value === null || trim((string) $value) === '') {
|
||||
|
||||
@@ -18,7 +18,6 @@ class AttendanceDataModel extends Model
|
||||
'date',
|
||||
'status',
|
||||
'reason',
|
||||
'reported',
|
||||
'is_reported',
|
||||
'is_notified',
|
||||
'semester',
|
||||
|
||||
@@ -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'
|
||||
];
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,8 +16,6 @@ class EmergencyContactModel extends Model
|
||||
'cellphone',
|
||||
'email',
|
||||
'relation',
|
||||
'semester',
|
||||
'school_year',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
];
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -28,7 +28,6 @@ class EventChargesModel extends Model
|
||||
'external_parent_email',
|
||||
'semester',
|
||||
'school_year',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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'
|
||||
];
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ class FinalExamModel extends Model
|
||||
'class_section_id',
|
||||
'updated_by',
|
||||
'score',
|
||||
'comment',
|
||||
'semester',
|
||||
'school_year',
|
||||
'created_at',
|
||||
|
||||
@@ -14,7 +14,7 @@ class FinalScoreModel extends Model
|
||||
'student_id',
|
||||
'school_id',
|
||||
'class_section_id',
|
||||
'teacher_id',
|
||||
'updated_by',
|
||||
'score',
|
||||
'score_letter',
|
||||
'comment',
|
||||
|
||||
@@ -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
|
||||
];
|
||||
}
|
||||
|
||||
@@ -20,8 +20,6 @@ class InvoiceStudentListModel extends Model
|
||||
'student_lastname',
|
||||
'school_id',
|
||||
'enrolled',
|
||||
'school_year',
|
||||
'semester',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
];
|
||||
|
||||
@@ -13,8 +13,6 @@ class IpAttemptModel extends Model
|
||||
'ip_address',
|
||||
'attempts',
|
||||
'last_attempt_at',
|
||||
'semester',
|
||||
'school_year',
|
||||
'blocked_until'
|
||||
];
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ class LoginActivityModel extends Model
|
||||
'logout_time',
|
||||
'ip_address',
|
||||
'user_agent',
|
||||
'school_year',
|
||||
'semester',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,8 @@ class NotificationModel extends Model
|
||||
'status',
|
||||
'action_url',
|
||||
'attachment_path',
|
||||
'semester',
|
||||
'school_year',
|
||||
'expires_at',
|
||||
'sent_at',
|
||||
'scheduled_at'
|
||||
];
|
||||
protected $useTimestamps = true;
|
||||
|
||||
@@ -15,7 +15,5 @@ class ParentModel extends Model
|
||||
'secondparent_email',
|
||||
'secondparent_phone',
|
||||
'firstparent_id',
|
||||
'semester',
|
||||
'school_year',
|
||||
];
|
||||
}
|
||||
|
||||
+283
-66
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -12,7 +12,6 @@ class PlacementLevelModel extends Model
|
||||
protected $allowedFields = [
|
||||
'student_id',
|
||||
'level',
|
||||
'school_year',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
'created_at',
|
||||
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Model;
|
||||
|
||||
class SchoolYearModel extends Model
|
||||
{
|
||||
protected $table = 'school_years';
|
||||
protected $primaryKey = 'id';
|
||||
protected $returnType = 'array';
|
||||
protected $useTimestamps = true;
|
||||
|
||||
protected $allowedFields = [
|
||||
'name',
|
||||
'status',
|
||||
'starts_on',
|
||||
'ends_on',
|
||||
'description',
|
||||
'registration_starts_on',
|
||||
'registration_ends_on',
|
||||
'previous_school_year_id',
|
||||
'next_school_year_id',
|
||||
'activated_at',
|
||||
'closing_started_at',
|
||||
'closed_at',
|
||||
'archived_at',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
];
|
||||
|
||||
protected $validationRules = [
|
||||
'name' => 'required|regex_match[/^\d{4}-\d{4}$/]|max_length[9]',
|
||||
'status' => 'required|in_list[draft,active,closing,closed,archived]',
|
||||
'starts_on' => 'permit_empty|valid_date[Y-m-d]',
|
||||
'ends_on' => 'permit_empty|valid_date[Y-m-d]',
|
||||
'registration_starts_on' => 'permit_empty|valid_date[Y-m-d]',
|
||||
'registration_ends_on' => 'permit_empty|valid_date[Y-m-d]',
|
||||
];
|
||||
|
||||
public function active(): ?array
|
||||
{
|
||||
return $this->where('status', 'active')
|
||||
->orderBy('id', 'DESC')
|
||||
->first();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Model;
|
||||
|
||||
class SchoolYearTransitionLogModel extends Model
|
||||
{
|
||||
protected $table = 'school_year_transition_logs';
|
||||
protected $primaryKey = 'id';
|
||||
protected $returnType = 'array';
|
||||
protected $useTimestamps = false;
|
||||
|
||||
protected $allowedFields = [
|
||||
'school_year_id',
|
||||
'from_status',
|
||||
'to_status',
|
||||
'action',
|
||||
'performed_by',
|
||||
'metadata_json',
|
||||
'created_at',
|
||||
];
|
||||
}
|
||||
@@ -12,7 +12,6 @@ class SectionModel extends Model
|
||||
protected $allowedFields = [
|
||||
'section_name',
|
||||
'description',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'updated_by'
|
||||
];
|
||||
|
||||
@@ -21,8 +21,6 @@ class StaffModel extends Model
|
||||
'phone',
|
||||
'role_name',
|
||||
'active_role',
|
||||
'status',
|
||||
'school_year',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
];
|
||||
@@ -44,7 +42,7 @@ class StaffModel extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert or update a staff row keyed by (user_id, school_year).
|
||||
* Insert or update a staff row keyed by user_id.
|
||||
* Ensures created_at is only set on insert and updated_at can be provided by caller.
|
||||
*/
|
||||
public function upsert(array $data): bool
|
||||
@@ -53,27 +51,9 @@ class StaffModel extends Model
|
||||
return false;
|
||||
}
|
||||
|
||||
// If school_year not provided, try to keep existing or fall back to current year string
|
||||
$schoolYear = $data['school_year'] ?? null;
|
||||
unset($data['school_year'], $data['status']);
|
||||
|
||||
if ($schoolYear === null) {
|
||||
// Try to find any existing row by user_id to reuse its school_year
|
||||
$existingAny = $this->where('user_id', $data['user_id'])->orderBy('id', 'DESC')->first();
|
||||
if ($existingAny && isset($existingAny['school_year'])) {
|
||||
$schoolYear = $existingAny['school_year'];
|
||||
$data['school_year'] = $schoolYear;
|
||||
}
|
||||
}
|
||||
|
||||
$existing = null;
|
||||
if ($schoolYear !== null) {
|
||||
$existing = $this->where('user_id', $data['user_id'])
|
||||
->where('school_year', $schoolYear)
|
||||
->first();
|
||||
} else {
|
||||
// If no school_year, treat (user_id) as key
|
||||
$existing = $this->where('user_id', $data['user_id'])->first();
|
||||
}
|
||||
|
||||
$now = utc_now();
|
||||
|
||||
@@ -100,4 +80,3 @@ class StaffModel extends Model
|
||||
return $this->insert($data) !== false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+471
-171
@@ -2,229 +2,529 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Database\BaseBuilder;
|
||||
use CodeIgniter\Model;
|
||||
|
||||
class StudentClassModel extends Model
|
||||
{
|
||||
protected $table = 'student_class';
|
||||
protected $primaryKey = 'id';
|
||||
protected $returnType = 'array';
|
||||
|
||||
protected $useAutoIncrement = true;
|
||||
protected $protectFields = true;
|
||||
|
||||
protected $allowedFields = [
|
||||
'student_id',
|
||||
'school_id',
|
||||
'class_section_id',
|
||||
'school_year',
|
||||
'is_event_only',
|
||||
'description',
|
||||
'updated_by',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'created_at'
|
||||
];
|
||||
|
||||
protected $useTimestamps = true;
|
||||
protected $createdField = 'created_at';
|
||||
protected $updatedField = 'updated_at';
|
||||
|
||||
protected $validationRules = [
|
||||
'student_id' => 'required|integer',
|
||||
'class_section_id'=> 'permit_empty|integer',
|
||||
'school_year' => 'required|max_length[20]',
|
||||
'is_event_only' => 'permit_empty|in_list[0,1]',
|
||||
'updated_by' => 'permit_empty|integer',
|
||||
];
|
||||
|
||||
protected $validationMessages = [];
|
||||
protected $skipValidation = false;
|
||||
protected $cleanValidationRules = true;
|
||||
|
||||
/**
|
||||
* Scope: only students active for classes/attendance.
|
||||
* Create a fresh builder for student_class.
|
||||
*
|
||||
* Using a fresh builder prevents WHERE conditions from a previous model
|
||||
* query from leaking into another query.
|
||||
*/
|
||||
public function active(): self
|
||||
private function freshBuilder(): BaseBuilder
|
||||
{
|
||||
return $this->select('student_class.*')
|
||||
->join('students', 'students.id = student_class.student_id', 'inner')
|
||||
return $this->db->table($this->table);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a fresh builder scoped to active students.
|
||||
*/
|
||||
private function activeStudentsBuilder(): BaseBuilder
|
||||
{
|
||||
return $this->freshBuilder()
|
||||
->select('student_class.*')
|
||||
->join(
|
||||
'students',
|
||||
'students.id = student_class.student_id',
|
||||
'inner'
|
||||
)
|
||||
->where('students.is_active', 1);
|
||||
}
|
||||
|
||||
public function getClassSectionNameByStudentId(int $studentId): ?string
|
||||
/**
|
||||
* Apply the active-student scope to the model.
|
||||
*
|
||||
* Prefer the dedicated retrieval methods below for new code because they
|
||||
* use fresh builders and cannot inherit stale model query state.
|
||||
*/
|
||||
public function active(): self
|
||||
{
|
||||
return $this->db->table($this->table)
|
||||
return $this
|
||||
->select('student_class.*')
|
||||
->join(
|
||||
'students',
|
||||
'students.id = student_class.student_id',
|
||||
'inner'
|
||||
)
|
||||
->where('students.is_active', 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the most recent class section name assigned to a student.
|
||||
*/
|
||||
public function getClassSectionNameByStudentId(
|
||||
int $studentId,
|
||||
?string $schoolYear = null
|
||||
): ?string {
|
||||
$builder = $this->freshBuilder()
|
||||
->select('cs.class_section_name')
|
||||
->join('classSection cs', 'cs.class_section_id = student_class.class_section_id')
|
||||
->join(
|
||||
'classSection cs',
|
||||
'cs.class_section_id = student_class.class_section_id',
|
||||
'inner'
|
||||
)
|
||||
->where('student_class.student_id', $studentId)
|
||||
->get()
|
||||
->getRow('class_section_name');
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
);
|
||||
|
||||
if ($schoolYear !== null && trim($schoolYear) !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Custom findAll() method
|
||||
public function findAll($limit = 0, $offset = 0)
|
||||
{
|
||||
// Optional: Add custom logic before fetching all records
|
||||
|
||||
// Then call the parent findAll method to fetch the records
|
||||
return parent::findAll($limit, $offset);
|
||||
}
|
||||
|
||||
// Method to get all students in a specific class section (optionally scoped to term)
|
||||
public function getClassStudents($classSectionId, ?string $schoolYear = null)
|
||||
{
|
||||
$qb = $this->active()->where('student_class.class_section_id', $classSectionId);
|
||||
if ($schoolYear !== null && $schoolYear !== '') {
|
||||
$qb->where('student_class.school_year', $schoolYear);
|
||||
}
|
||||
return $qb->findAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class section names for a student in a given school year.
|
||||
*
|
||||
* @param int|string $studentId
|
||||
* @param string $schoolYear
|
||||
* @param bool $asArray When true, return an array of names; otherwise a comma-separated string.
|
||||
* @return array|string
|
||||
*/
|
||||
public function getClassSectionsByStudentId($studentId, string $schoolYear, bool $asArray = false)
|
||||
{
|
||||
$rows = $this->db->table('student_class')
|
||||
->select('cs.class_section_name')
|
||||
->join('classSection cs', 'student_class.class_section_id = cs.class_section_id')
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where('student_class.class_section_id IS NOT NULL', null, false)
|
||||
->where('student_class.school_year', $schoolYear)
|
||||
->orderBy('cs.class_section_name', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$names = array_values(array_unique(array_filter(array_map(static function ($row) {
|
||||
return $row['class_section_name'] ?? null;
|
||||
}, $rows))));
|
||||
|
||||
if ($asArray) {
|
||||
return $names;
|
||||
}
|
||||
|
||||
return !empty($names) ? implode(', ', $names) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class section names for a student in a given school year, with optional event flag.
|
||||
*
|
||||
* @param int|string $studentId
|
||||
* @param string $schoolYear
|
||||
* @param bool $asArray When true, return an array of names; otherwise a comma-separated string.
|
||||
* @return array|string
|
||||
*/
|
||||
public function getClassSectionsByStudentIdWithFlags($studentId, string $schoolYear, bool $asArray = false)
|
||||
{
|
||||
$rows = $this->db->table('student_class')
|
||||
->select('cs.class_section_name, student_class.is_event_only')
|
||||
->join('classSection cs', 'student_class.class_section_id = cs.class_section_id')
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where('student_class.class_section_id IS NOT NULL', null, false)
|
||||
->where('student_class.school_year', $schoolYear)
|
||||
->orderBy('cs.class_section_name', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$names = array_values(array_unique(array_filter(array_map(static function ($row) {
|
||||
$name = $row['class_section_name'] ?? null;
|
||||
if (!$name) return null;
|
||||
$isEvent = (int)($row['is_event_only'] ?? 0) === 1;
|
||||
return $isEvent ? ($name . ' (Event)') : $name;
|
||||
}, $rows))));
|
||||
|
||||
if ($asArray) {
|
||||
return $names;
|
||||
}
|
||||
|
||||
return !empty($names) ? implode(', ', $names) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class_section_id values for a student/year.
|
||||
*
|
||||
* @param int|string $studentId
|
||||
* @param string $schoolYear
|
||||
* @return int[]
|
||||
*/
|
||||
public function getClassSectionIdsByStudentId($studentId, string $schoolYear): array
|
||||
{
|
||||
$rows = $this->db->table('student_class')
|
||||
->select('class_section_id')
|
||||
->where('student_id', $studentId)
|
||||
->where('class_section_id IS NOT NULL', null, false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$ids = array_map(static fn($r) => (int)($r['class_section_id'] ?? 0), $rows);
|
||||
return array_values(array_filter(array_unique($ids), static fn($v) => $v > 0));
|
||||
}
|
||||
|
||||
|
||||
public function getStudentsByClassSectionIds(array $classSectionIds)
|
||||
{
|
||||
return $this->select('students.id as student_id, students.firstname, students.lastname, students.school_id, students.is_new,students.photo_consent ,students.age, student_class.school_year, student_class.class_section_id')
|
||||
->join('students', 'students.id = student_class.student_id')
|
||||
->whereIn('student_class.class_section_id', $classSectionIds)
|
||||
->where('students.is_active', 1)
|
||||
->get()
|
||||
->getResultArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the class ID (grade) for a specific student.
|
||||
*
|
||||
* @param int $studentId
|
||||
* @return string class_id or 'N/A'
|
||||
*/
|
||||
public function getStudentGrade(int $studentId): string
|
||||
{
|
||||
$studentClass = $this->where('student_id', $studentId)
|
||||
->where('is_event_only', 0)
|
||||
->orderBy('created_at', 'DESC') // in case of multiple entries, get latest
|
||||
->first();
|
||||
|
||||
if ($studentClass && isset($studentClass['class_section_id'])) {
|
||||
$classSection = $this->db->table('classSection')
|
||||
->where('class_section_id', $studentClass['class_section_id'])
|
||||
$row = $builder
|
||||
->orderBy('student_class.created_at', 'DESC')
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
return $classSection['class_id'] ?? 'N/A';
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
log_message('error', "Student class or section not found for student ID: $studentId");
|
||||
$name = trim((string) ($row['class_section_name'] ?? ''));
|
||||
|
||||
return $name !== '' ? $name : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get active students assigned to a class section.
|
||||
*
|
||||
* student_class is scoped by school year only. It has no semester column.
|
||||
*/
|
||||
public function getClassStudents(
|
||||
int $classSectionId,
|
||||
?string $schoolYear = null
|
||||
): array {
|
||||
$builder = $this->activeStudentsBuilder()
|
||||
->where(
|
||||
'student_class.class_section_id',
|
||||
$classSectionId
|
||||
)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
);
|
||||
|
||||
if ($schoolYear !== null && trim($schoolYear) !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
);
|
||||
}
|
||||
|
||||
return $builder
|
||||
->orderBy('students.lastname', 'ASC')
|
||||
->orderBy('students.firstname', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return student IDs assigned to a class section for a school year.
|
||||
*/
|
||||
public function getStudentIdsByClassSection(
|
||||
int $classSectionId,
|
||||
string $schoolYear
|
||||
): array {
|
||||
$schoolYear = trim($schoolYear);
|
||||
|
||||
$builder = $this->freshBuilder()
|
||||
->select('student_class.student_id')
|
||||
->join(
|
||||
'students',
|
||||
'students.id = student_class.student_id',
|
||||
'inner'
|
||||
)
|
||||
->where(
|
||||
'student_class.class_section_id',
|
||||
$classSectionId
|
||||
)
|
||||
->where('students.is_active', 1)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
);
|
||||
|
||||
if ($schoolYear !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
$schoolYear
|
||||
);
|
||||
}
|
||||
|
||||
$rows = $builder
|
||||
->groupBy('student_class.student_id')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$studentIds = array_map(
|
||||
static fn(array $row): int =>
|
||||
(int) ($row['student_id'] ?? 0),
|
||||
$rows
|
||||
);
|
||||
|
||||
return array_values(array_unique(array_filter(
|
||||
$studentIds,
|
||||
static fn(int $studentId): bool => $studentId > 0
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class section names assigned to a student for a school year.
|
||||
*
|
||||
* @return array|string
|
||||
*/
|
||||
public function getClassSectionsByStudentId(
|
||||
int|string $studentId,
|
||||
string $schoolYear,
|
||||
bool $asArray = false
|
||||
): array|string {
|
||||
$rows = $this->freshBuilder()
|
||||
->select('cs.class_section_name')
|
||||
->join(
|
||||
'classSection cs',
|
||||
'student_class.class_section_id = cs.class_section_id',
|
||||
'inner'
|
||||
)
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
)
|
||||
->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
)
|
||||
->orderBy('cs.class_section_name', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$names = array_map(
|
||||
static fn(array $row): string =>
|
||||
trim((string) ($row['class_section_name'] ?? '')),
|
||||
$rows
|
||||
);
|
||||
|
||||
$names = array_values(array_unique(array_filter(
|
||||
$names,
|
||||
static fn(string $name): bool => $name !== ''
|
||||
)));
|
||||
|
||||
return $asArray ? $names : implode(', ', $names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class section names and indicate event-only assignments.
|
||||
*
|
||||
* @return array|string
|
||||
*/
|
||||
public function getClassSectionsByStudentIdWithFlags(
|
||||
int|string $studentId,
|
||||
string $schoolYear,
|
||||
bool $asArray = false
|
||||
): array|string {
|
||||
$rows = $this->freshBuilder()
|
||||
->select(
|
||||
'cs.class_section_name, student_class.is_event_only'
|
||||
)
|
||||
->join(
|
||||
'classSection cs',
|
||||
'student_class.class_section_id = cs.class_section_id',
|
||||
'inner'
|
||||
)
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
)
|
||||
->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
)
|
||||
->orderBy('cs.class_section_name', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$names = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$name = trim(
|
||||
(string) ($row['class_section_name'] ?? '')
|
||||
);
|
||||
|
||||
if ($name === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((int) ($row['is_event_only'] ?? 0) === 1) {
|
||||
$name .= ' (Event)';
|
||||
}
|
||||
|
||||
$names[] = $name;
|
||||
}
|
||||
|
||||
$names = array_values(array_unique($names));
|
||||
|
||||
return $asArray ? $names : implode(', ', $names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class-section IDs assigned to a student for a school year.
|
||||
*
|
||||
* @return int[]
|
||||
*/
|
||||
public function getClassSectionIdsByStudentId(
|
||||
int|string $studentId,
|
||||
string $schoolYear
|
||||
): array {
|
||||
$rows = $this->freshBuilder()
|
||||
->select('student_class.class_section_id')
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
)
|
||||
->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
)
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$ids = array_map(
|
||||
static fn(array $row): int =>
|
||||
(int) ($row['class_section_id'] ?? 0),
|
||||
$rows
|
||||
);
|
||||
|
||||
return array_values(array_unique(array_filter(
|
||||
$ids,
|
||||
static fn(int $id): bool => $id > 0
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return active students for a set of class-section IDs.
|
||||
*/
|
||||
public function getStudentsByClassSectionIds(
|
||||
array $classSectionIds,
|
||||
?string $schoolYear = null
|
||||
): array {
|
||||
$classSectionIds = array_values(array_unique(array_filter(
|
||||
array_map('intval', $classSectionIds),
|
||||
static fn(int $id): bool => $id > 0
|
||||
)));
|
||||
|
||||
if ($classSectionIds === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$builder = $this->freshBuilder()
|
||||
->select([
|
||||
'students.id AS student_id',
|
||||
'students.firstname',
|
||||
'students.lastname',
|
||||
'students.school_id',
|
||||
'students.is_new',
|
||||
'students.photo_consent',
|
||||
'students.age',
|
||||
'student_class.school_year',
|
||||
'student_class.class_section_id',
|
||||
'student_class.is_event_only',
|
||||
])
|
||||
->join(
|
||||
'students',
|
||||
'students.id = student_class.student_id',
|
||||
'inner'
|
||||
)
|
||||
->whereIn(
|
||||
'student_class.class_section_id',
|
||||
$classSectionIds
|
||||
)
|
||||
->where('students.is_active', 1);
|
||||
|
||||
if ($schoolYear !== null && trim($schoolYear) !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
);
|
||||
}
|
||||
|
||||
return $builder
|
||||
->orderBy('students.lastname', 'ASC')
|
||||
->orderBy('students.firstname', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the student's most recent non-event class grade.
|
||||
*/
|
||||
public function getStudentGrade(
|
||||
int $studentId,
|
||||
?string $schoolYear = null
|
||||
): string {
|
||||
$builder = $this->freshBuilder()
|
||||
->select('classSection.class_id')
|
||||
->join(
|
||||
'classSection',
|
||||
'classSection.class_section_id = student_class.class_section_id',
|
||||
'inner'
|
||||
)
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where('student_class.is_event_only', 0)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
);
|
||||
|
||||
if ($schoolYear !== null && trim($schoolYear) !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
);
|
||||
}
|
||||
|
||||
$row = $builder
|
||||
->orderBy('student_class.created_at', 'DESC')
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
$classId = trim((string) ($row['class_id'] ?? ''));
|
||||
|
||||
if ($classId !== '') {
|
||||
return $classId;
|
||||
}
|
||||
|
||||
log_message(
|
||||
'warning',
|
||||
'Student class or section not found for student ID: {studentId}',
|
||||
['studentId' => $studentId]
|
||||
);
|
||||
|
||||
return 'N/A';
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the student has at least one non-event class assignment for the year.
|
||||
* Determine whether a student has a non-event assignment for a year.
|
||||
*/
|
||||
public function hasNonEventAssignment(int $studentId, string $schoolYear): bool
|
||||
{
|
||||
return (bool) $this->where('student_id', $studentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->where('is_event_only', 0)
|
||||
->first();
|
||||
public function hasNonEventAssignment(
|
||||
int $studentId,
|
||||
string $schoolYear
|
||||
): bool {
|
||||
return $this->freshBuilder()
|
||||
->select('student_class.id')
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
)
|
||||
->where('student_class.is_event_only', 0)
|
||||
->limit(1)
|
||||
->get()
|
||||
->getRowArray() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return student counts per class_section_id, optionally scoped to a school year.
|
||||
* Return active student counts by class section.
|
||||
*
|
||||
* @param string|null $schoolYear
|
||||
* @return array<int|string,int> Map of class_section_id => count
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function getStudentCountsBySection(?string $schoolYear = null): array
|
||||
{
|
||||
$qb = $this->db->table($this->table)
|
||||
->select('class_section_id, COUNT(*) AS total')
|
||||
->join('students', 'students.id = student_class.student_id', 'inner')
|
||||
public function getStudentCountsBySection(
|
||||
?string $schoolYear = null
|
||||
): array {
|
||||
$builder = $this->freshBuilder()
|
||||
->select(
|
||||
'student_class.class_section_id, ' .
|
||||
'COUNT(DISTINCT student_class.student_id) AS total'
|
||||
)
|
||||
->join(
|
||||
'students',
|
||||
'students.id = student_class.student_id',
|
||||
'inner'
|
||||
)
|
||||
->where('students.is_active', 1)
|
||||
->where('student_class.class_section_id IS NOT NULL', null, false)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
)
|
||||
->groupBy('student_class.class_section_id');
|
||||
|
||||
if ($schoolYear !== null && $schoolYear !== '') {
|
||||
$qb->where('student_class.school_year', $schoolYear);
|
||||
if ($schoolYear !== null && trim($schoolYear) !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
);
|
||||
}
|
||||
|
||||
$rows = $qb->get()->getResultArray();
|
||||
$out = [];
|
||||
foreach ($rows as $r) {
|
||||
$cid = $r['class_section_id'] ?? null;
|
||||
if ($cid === null || $cid === '') continue;
|
||||
$out[$cid] = (int)($r['total'] ?? 0);
|
||||
$rows = $builder
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$counts = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$classSectionId = (int) (
|
||||
$row['class_section_id'] ?? 0
|
||||
);
|
||||
|
||||
if ($classSectionId <= 0) {
|
||||
continue;
|
||||
}
|
||||
return $out;
|
||||
|
||||
$counts[$classSectionId] = (int) (
|
||||
$row['total'] ?? 0
|
||||
);
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@ class StudentModel extends Model
|
||||
'photo_consent',
|
||||
'is_new',
|
||||
'parent_id',
|
||||
'school_year',
|
||||
'registration_date',
|
||||
'tuition_paid',
|
||||
'year_of_registration',
|
||||
@@ -122,7 +121,9 @@ class StudentModel extends Model
|
||||
|
||||
// school_year filter (skip if null or "all")
|
||||
if ($schoolYear !== null && strtolower($schoolYear) !== 'all') {
|
||||
$builder->where('students.school_year', $schoolYear);
|
||||
$builder
|
||||
->join('student_class sc_filter', 'sc_filter.student_id = students.id', 'inner')
|
||||
->where('sc_filter.school_year', $schoolYear);
|
||||
}
|
||||
|
||||
return $builder
|
||||
@@ -171,12 +172,13 @@ class StudentModel extends Model
|
||||
users.cellphone as phone,
|
||||
students.registration_grade,
|
||||
classSection.class_section_name as current_class,
|
||||
"' . $schoolYear . '" as school_year,
|
||||
student_class.school_year,
|
||||
"' . $semester . '" as semester
|
||||
')
|
||||
->join('users', 'users.id = students.parent_id', 'left')
|
||||
->join('student_class', 'student_class.student_id = students.id', 'left')
|
||||
->join('class_section', 'student_class.class_section_id = classSection.id', 'left')
|
||||
->join('classSection', 'student_class.class_section_id = classSection.class_section_id', 'left')
|
||||
->where('student_class.school_year', $schoolYear)
|
||||
->get()
|
||||
->getResultArray();
|
||||
}
|
||||
@@ -199,7 +201,7 @@ class StudentModel extends Model
|
||||
')
|
||||
->join('student_class', 'students.id = student_class.student_id', 'left')
|
||||
->join('teacher_class', 'student_class.class_section_id = teacher_class.class_section_id', 'left')
|
||||
->join('class_section', 'student_class.class_section_id = classSection.id', 'left')
|
||||
->join('classSection', 'student_class.class_section_id = classSection.class_section_id', 'left')
|
||||
->where('teacher_class.teacher_id', $teacherId)
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
+20
-24
@@ -28,7 +28,6 @@ class UserModel extends Model
|
||||
'failed_attempts',
|
||||
'last_failed_at',
|
||||
'semester',
|
||||
'school_year',
|
||||
'status',
|
||||
'is_suspended',
|
||||
'is_verified',
|
||||
@@ -237,13 +236,21 @@ class UserModel extends Model
|
||||
|
||||
public function getUsersByRoleAndSchoolYear(string $roleName, string $schoolYear): array
|
||||
{
|
||||
return $this->select('users.*')
|
||||
$builder = $this->select('users.*')
|
||||
->join('user_roles', 'user_roles.user_id = users.id')
|
||||
->join('roles', 'roles.id = user_roles.role_id')
|
||||
->where('roles.name', $roleName)
|
||||
->where('users.school_year', $schoolYear)
|
||||
->where('user_roles.deleted_at', null)
|
||||
->findAll();
|
||||
->where('user_roles.deleted_at', null);
|
||||
|
||||
if ($this->roleUsesTeacherAssignments($roleName)) {
|
||||
$builder->join(
|
||||
'teacher_class tc_year',
|
||||
'tc_year.teacher_id = users.id AND tc_year.school_year = ' . $this->db->escape($schoolYear),
|
||||
'inner'
|
||||
);
|
||||
}
|
||||
|
||||
return $builder->groupBy('users.id')->findAll();
|
||||
}
|
||||
|
||||
public function countAdminsBySchoolYear(string $schoolYear): int
|
||||
@@ -260,8 +267,8 @@ class UserModel extends Model
|
||||
)
|
||||
->join('user_roles ur', 'ur.user_id = u.id', 'inner')
|
||||
->join('roles r', 'r.id = ur.role_id', 'inner')
|
||||
->where('u.school_year', $schoolYear)
|
||||
->where('r.is_active', 1)
|
||||
->where('LOWER(r.name) NOT IN ("guest","teacher","teacher_assistant","parent")', null, false)
|
||||
->groupBy('u.id')
|
||||
->having('is_admin', 1);
|
||||
|
||||
@@ -357,28 +364,13 @@ class UserModel extends Model
|
||||
}
|
||||
|
||||
if (!empty($schoolYear)) {
|
||||
// Prefer user_roles.school_year if present (true year-scoped roles)
|
||||
$userRolesFields = [];
|
||||
try {
|
||||
$userRolesFields = $this->db->getFieldNames('user_roles');
|
||||
} catch (\Throwable $e) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
if (in_array('school_year', $userRolesFields, true)) {
|
||||
$builder->where('ur.school_year', $schoolYear);
|
||||
} else {
|
||||
// Fallback: role-aware filter
|
||||
$escYear = $this->db->escape($schoolYear);
|
||||
|
||||
// Include user if:
|
||||
// (A) They are assigned as teacher/TA in teacher_class for that year
|
||||
// OR
|
||||
// (B) They have at least one non-teacher-ish (and non-parent) role (admin/staff/etc.)
|
||||
//
|
||||
// Teacher-ish detection: name contains 'teacher' OR equals 'ta'
|
||||
// (B) They have at least one non-teacher-ish (and non-parent) global role.
|
||||
$builder->groupStart()
|
||||
// A) has teacher assignment that year
|
||||
->where("
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
@@ -387,7 +379,6 @@ class UserModel extends Model
|
||||
AND tc.school_year = {$escYear}
|
||||
)
|
||||
", null, false)
|
||||
// B) OR has any non-teacher-ish, non-parent role
|
||||
->orWhere("
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
@@ -400,11 +391,16 @@ class UserModel extends Model
|
||||
", null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
}
|
||||
|
||||
return $builder
|
||||
->groupBy('users.id')
|
||||
->orderBy($sort === 'roles' ? 'roles' : $sort, $order)
|
||||
->findAll();
|
||||
}
|
||||
|
||||
private function roleUsesTeacherAssignments(string $roleName): bool
|
||||
{
|
||||
$role = strtolower(trim($roleName));
|
||||
return $role === 'ta' || str_contains($role, 'teacher');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,8 +13,6 @@ class UserRoleModel extends Model
|
||||
protected $allowedFields = [
|
||||
'user_id',
|
||||
'role_id',
|
||||
'semester',
|
||||
'school_year',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'updated_by',
|
||||
|
||||
@@ -11,7 +11,6 @@ class WhatsappGroupLinkModel extends Model
|
||||
'class_section_id',
|
||||
'class_section_name',
|
||||
'school_year',
|
||||
'semester',
|
||||
'invite_link',
|
||||
'active',
|
||||
];
|
||||
@@ -22,9 +21,9 @@ class WhatsappGroupLinkModel extends Model
|
||||
*
|
||||
* @param int $sectionId Class/section code (not PK).
|
||||
* @param string $year School year, e.g. "2025-2026".
|
||||
* @param string $sem Semester, e.g. "Fall".
|
||||
* @param string $sem Deprecated/ignored; links are scoped by school year.
|
||||
* @param bool $onlyActive If true, require active=1.
|
||||
* @param bool $allowNullSemester If true, accept rows with semester IS NULL as well.
|
||||
* @param bool $allowNullSemester Deprecated/ignored.
|
||||
*/
|
||||
public function getLinkForSection(
|
||||
int $sectionId,
|
||||
@@ -40,17 +39,6 @@ class WhatsappGroupLinkModel extends Model
|
||||
->where('class_section_id', $sectionId)
|
||||
->where('school_year', $year);
|
||||
|
||||
if ($sem !== '') {
|
||||
if ($allowNullSemester) {
|
||||
$b = $b->groupStart()
|
||||
->where('semester', $sem)
|
||||
->orWhere('semester IS NULL', null, false)
|
||||
->groupEnd();
|
||||
} else {
|
||||
$b = $b->where('semester', $sem);
|
||||
}
|
||||
}
|
||||
|
||||
if ($onlyActive) {
|
||||
$b = $b->where('active', 1);
|
||||
}
|
||||
@@ -70,7 +58,7 @@ class WhatsappGroupLinkModel extends Model
|
||||
* @param string $year
|
||||
* @param string $sem
|
||||
* @param bool|null $onlyActive true: active only, false: inactive only, null: both
|
||||
* @param bool $allowNullSemester If true, include rows with semester IS NULL.
|
||||
* @param bool $allowNullSemester Deprecated/ignored.
|
||||
*/
|
||||
public function getAllForTerm(
|
||||
string $year,
|
||||
@@ -84,17 +72,6 @@ class WhatsappGroupLinkModel extends Model
|
||||
$b = $this->asArray()
|
||||
->where('school_year', $year);
|
||||
|
||||
if ($sem !== '') {
|
||||
if ($allowNullSemester) {
|
||||
$b = $b->groupStart()
|
||||
->where('semester', $sem)
|
||||
->orWhere('semester IS NULL', null, false)
|
||||
->groupEnd();
|
||||
} else {
|
||||
$b = $b->where('semester', $sem);
|
||||
}
|
||||
}
|
||||
|
||||
if ($onlyActive === true) {
|
||||
$b = $b->where('active', 1);
|
||||
} elseif ($onlyActive === false) {
|
||||
@@ -122,7 +99,6 @@ class WhatsappGroupLinkModel extends Model
|
||||
'class_section_id' => $sectionId,
|
||||
'class_section_name' => $sectionName,
|
||||
'school_year' => trim($year),
|
||||
'semester' => trim($sem),
|
||||
'invite_link' => trim($inviteLink),
|
||||
'active' => $active ? 1 : 0,
|
||||
];
|
||||
@@ -131,7 +107,6 @@ class WhatsappGroupLinkModel extends Model
|
||||
$existing = $this->asArray()
|
||||
->where('class_section_id', $sectionId)
|
||||
->where('school_year', $payload['school_year'])
|
||||
->where('semester', $payload['semester'])
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
|
||||
@@ -42,7 +42,7 @@ class WhatsappInviteLogModel extends Model
|
||||
/**
|
||||
* Log a successful send.
|
||||
*/
|
||||
public function logSuccess(int $parentId, string $email, int $classSectionId = null, int $linkId = null): bool
|
||||
public function logSuccess(int $parentId, string $email, ?int $classSectionId = null, ?int $linkId = null): bool
|
||||
{
|
||||
return (bool) $this->insert([
|
||||
'parent_id' => $parentId,
|
||||
@@ -58,7 +58,7 @@ class WhatsappInviteLogModel extends Model
|
||||
/**
|
||||
* Log a failure with error message.
|
||||
*/
|
||||
public function logFailure(int $parentId, string $email, string $error, int $classSectionId = null, int $linkId = null): bool
|
||||
public function logFailure(int $parentId, string $email, string $error, ?int $classSectionId = null, ?int $linkId = null): bool
|
||||
{
|
||||
return (bool) $this->insert([
|
||||
'parent_id' => $parentId,
|
||||
|
||||
@@ -61,7 +61,7 @@ class FeeCalculationService
|
||||
// Retrieve fee configs
|
||||
$firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350);
|
||||
$secondStudentFee = (float) ($configModel->getConfig('second_student_fee') ?? 200);
|
||||
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 180);
|
||||
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 200);
|
||||
|
||||
// Assign tuition_fee to all students (before filtering refunds)
|
||||
$regularCount = 0;
|
||||
@@ -148,7 +148,7 @@ class FeeCalculationService
|
||||
|
||||
$firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350);
|
||||
$secondStudentFee = (float) ($configModel->getConfig('second_student_fee') ?? 200);
|
||||
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 180);
|
||||
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 200);
|
||||
|
||||
// ✅ Pre-fetch and assign grade/class section names before sorting
|
||||
foreach ($students as &$student) {
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SchoolYearClosingBatchModel;
|
||||
use App\Models\SchoolYearClosingItemModel;
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Support\SchoolYear\SchoolYearStatus;
|
||||
use CodeIgniter\Database\BaseConnection;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearClosingService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
private readonly SchoolYearClosingBatchModel $batchModel,
|
||||
private readonly SchoolYearClosingItemModel $itemModel,
|
||||
private readonly SchoolYearManagementService $managementService,
|
||||
private readonly BaseConnection $db,
|
||||
) {
|
||||
}
|
||||
|
||||
public function preview(int $sourceYearId, ?int $targetYearId = null): array
|
||||
{
|
||||
$source = $this->requireYear($sourceYearId);
|
||||
$target = $targetYearId !== null ? $this->schoolYearModel->find($targetYearId) : $this->nextDraftYear((string) $source['name']);
|
||||
$sourceName = (string) $source['name'];
|
||||
|
||||
$finance = $this->financialSummary($sourceName);
|
||||
$overview = [
|
||||
'students' => $this->countBySchoolYear('student_class', $sourceName, 'student_id'),
|
||||
'families' => $this->countFamilies($sourceName),
|
||||
'classes' => $this->countBySchoolYear('classSection', $sourceName, 'class_id'),
|
||||
'teachers' => $this->countBySchoolYear('teacher_class', $sourceName, 'teacher_id'),
|
||||
'invoices' => $finance['invoice_count'],
|
||||
'total_invoiced' => $finance['total_invoiced'],
|
||||
'total_paid' => $finance['total_paid'],
|
||||
'total_outstanding' => $finance['total_outstanding'],
|
||||
];
|
||||
|
||||
$findings = [];
|
||||
if ($target === null) {
|
||||
$findings[] = $this->finding('blocking', 'Missing target year', 'Create a draft target school year before starting closing.');
|
||||
} elseif (! in_array((string) $target['status'], [SchoolYearStatus::DRAFT, SchoolYearStatus::ACTIVE], true)) {
|
||||
$findings[] = $this->finding('blocking', 'Invalid target year', 'The target school year must be draft or active.');
|
||||
}
|
||||
|
||||
foreach ($this->unpaidInvoiceFindings($sourceName) as $finding) {
|
||||
$findings[] = $finding;
|
||||
}
|
||||
|
||||
if ($this->countMissingSchoolYearRows('invoices') > 0) {
|
||||
$findings[] = $this->finding('blocking', 'Invoices missing school year', 'Some invoice records are not assigned to a school year.');
|
||||
}
|
||||
|
||||
$carryForward = $this->carryForwardFamilies($sourceName);
|
||||
$warnings = array_values(array_filter($findings, static fn (array $f): bool => $f['severity'] === 'warning'));
|
||||
$blockers = array_values(array_filter($findings, static fn (array $f): bool => $f['severity'] === 'blocking'));
|
||||
|
||||
$result = [
|
||||
'source' => $source,
|
||||
'target' => $target,
|
||||
'overview' => $overview,
|
||||
'finance' => $finance,
|
||||
'findings' => $findings,
|
||||
'blockers' => $blockers,
|
||||
'warnings' => $warnings,
|
||||
'carry_forward' => $carryForward,
|
||||
'generated_at' => date('Y-m-d H:i:s'),
|
||||
];
|
||||
$result['hash'] = $this->hashPreview($result);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function start(int $sourceYearId, int $targetYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$source = $this->requireYear($sourceYearId);
|
||||
|
||||
if (($source['status'] ?? '') !== SchoolYearStatus::ACTIVE) {
|
||||
throw new InvalidArgumentException('Only an active school year can begin closing.');
|
||||
}
|
||||
|
||||
$preview = $this->preview($sourceYearId, $targetYearId);
|
||||
if ($preview['blockers'] !== []) {
|
||||
throw new InvalidArgumentException('Resolve blocking closing issues before starting closing.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$batchId = $this->batchModel->insert([
|
||||
'source_school_year_id' => $sourceYearId,
|
||||
'target_school_year_id' => $targetYearId,
|
||||
'status' => 'started',
|
||||
'preview_hash' => $preview['hash'],
|
||||
'total_families' => count($preview['carry_forward']),
|
||||
'total_positive_balance' => $preview['finance']['positive_balance'],
|
||||
'total_credit_balance' => $preview['finance']['credit_balance'],
|
||||
'started_by' => $userId,
|
||||
'started_at' => $now,
|
||||
], true);
|
||||
|
||||
foreach ($preview['carry_forward'] as $row) {
|
||||
$this->itemModel->insert([
|
||||
'closing_batch_id' => $batchId,
|
||||
'family_id' => (int) $row['family_id'],
|
||||
'source_balance' => $row['source_balance'],
|
||||
'credit_amount' => $row['credit_amount'],
|
||||
'carry_forward_amount' => $row['carry_forward_amount'],
|
||||
'status' => 'pending',
|
||||
]);
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update($sourceYearId, [
|
||||
'status' => SchoolYearStatus::CLOSING,
|
||||
'closing_started_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::ACTIVE, SchoolYearStatus::CLOSING, 'closing_start', $userId, [
|
||||
'target_school_year_id' => $targetYearId,
|
||||
'closing_batch_id' => $batchId,
|
||||
'preview_hash' => $preview['hash'],
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to start school year closing.');
|
||||
}
|
||||
}
|
||||
|
||||
public function execute(int $sourceYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$batch = $this->latestOpenBatch($sourceYearId);
|
||||
if ($batch === null) {
|
||||
throw new InvalidArgumentException('No open closing batch exists.');
|
||||
}
|
||||
|
||||
$preview = $this->preview($sourceYearId, (int) $batch['target_school_year_id']);
|
||||
if ($preview['hash'] !== (string) $batch['preview_hash']) {
|
||||
throw new InvalidArgumentException('Closing preview has changed. Refresh and restart closing before executing carry-forward.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$items = $this->itemModel->where('closing_batch_id', (int) $batch['id'])->findAll();
|
||||
foreach ($items as $item) {
|
||||
if (($item['status'] ?? '') === 'completed') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->itemModel->update((int) $item['id'], ['status' => 'completed']);
|
||||
}
|
||||
$this->batchModel->update((int) $batch['id'], ['status' => 'executed']);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::CLOSING, 'carry_forward_execute', $userId, [
|
||||
'closing_batch_id' => (int) $batch['id'],
|
||||
'note' => 'Marked previewed carry-forward items complete. Target accounting records require the dedicated opening-balance schema.',
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to execute carry-forward.');
|
||||
}
|
||||
}
|
||||
|
||||
public function complete(int $sourceYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$batch = $this->latestOpenBatch($sourceYearId);
|
||||
if ($batch === null || ($batch['status'] ?? '') !== 'executed') {
|
||||
throw new InvalidArgumentException('Carry-forward must be executed before completing closing.');
|
||||
}
|
||||
|
||||
$pending = $this->itemModel
|
||||
->where('closing_batch_id', (int) $batch['id'])
|
||||
->where('status !=', 'completed')
|
||||
->countAllResults();
|
||||
if ($pending > 0) {
|
||||
throw new InvalidArgumentException('All closing batch items must complete before the year can be closed.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$this->batchModel->update((int) $batch['id'], [
|
||||
'status' => 'completed',
|
||||
'completed_by' => $userId,
|
||||
'completed_at' => $now,
|
||||
]);
|
||||
$this->schoolYearModel->update($sourceYearId, [
|
||||
'status' => SchoolYearStatus::CLOSED,
|
||||
'closed_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::CLOSED, 'closing_complete', $userId, [
|
||||
'closing_batch_id' => (int) $batch['id'],
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to complete closing.');
|
||||
}
|
||||
}
|
||||
|
||||
public function cancel(int $sourceYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$batch = $this->latestOpenBatch($sourceYearId);
|
||||
if ($batch !== null && in_array((string) $batch['status'], ['executed', 'completed'], true)) {
|
||||
throw new InvalidArgumentException('Closing cannot be cancelled after carry-forward has executed.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
if ($batch !== null) {
|
||||
$this->batchModel->update((int) $batch['id'], ['status' => 'cancelled']);
|
||||
}
|
||||
$this->schoolYearModel->update($sourceYearId, [
|
||||
'status' => SchoolYearStatus::ACTIVE,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::ACTIVE, 'closing_cancel', $userId, [
|
||||
'closing_batch_id' => $batch['id'] ?? null,
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to cancel closing.');
|
||||
}
|
||||
}
|
||||
|
||||
public function latestBatch(int $sourceYearId): ?array
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_closing_batches')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->batchModel
|
||||
->where('source_school_year_id', $sourceYearId)
|
||||
->orderBy('id', 'DESC')
|
||||
->first();
|
||||
}
|
||||
|
||||
private function requireYear(int $id): array
|
||||
{
|
||||
$year = $this->schoolYearModel->find($id);
|
||||
if ($year === null) {
|
||||
throw new InvalidArgumentException('School year not found.');
|
||||
}
|
||||
|
||||
return $year;
|
||||
}
|
||||
|
||||
private function nextDraftYear(string $sourceName): ?array
|
||||
{
|
||||
if (! preg_match('/^(\d{4})-(\d{4})$/', $sourceName, $matches)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$nextName = $matches[2] . '-' . ((int) $matches[2] + 1);
|
||||
|
||||
return $this->schoolYearModel
|
||||
->where('name', $nextName)
|
||||
->first();
|
||||
}
|
||||
|
||||
private function financialSummary(string $schoolYear): array
|
||||
{
|
||||
$summary = [
|
||||
'invoice_count' => 0,
|
||||
'total_invoiced' => 0.0,
|
||||
'total_paid' => 0.0,
|
||||
'total_outstanding' => 0.0,
|
||||
'positive_balance' => 0.0,
|
||||
'credit_balance' => 0.0,
|
||||
];
|
||||
|
||||
if (! $this->db->tableExists('invoices')) {
|
||||
return $summary;
|
||||
}
|
||||
|
||||
$row = $this->db->table('invoices')
|
||||
->select('COUNT(*) AS invoice_count')
|
||||
->select('COALESCE(SUM(total_amount), 0) AS total_invoiced')
|
||||
->select('COALESCE(SUM(paid_amount), 0) AS total_paid')
|
||||
->select('COALESCE(SUM(balance), 0) AS total_outstanding')
|
||||
->select('COALESCE(SUM(CASE WHEN balance > 0 THEN balance ELSE 0 END), 0) AS positive_balance', false)
|
||||
->select('COALESCE(SUM(CASE WHEN balance < 0 THEN ABS(balance) ELSE 0 END), 0) AS credit_balance', false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getRowArray() ?? [];
|
||||
|
||||
foreach ($summary as $key => $value) {
|
||||
$summary[$key] = $key === 'invoice_count' ? (int) ($row[$key] ?? 0) : round((float) ($row[$key] ?? 0), 2);
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
private function unpaidInvoiceFindings(string $schoolYear): array
|
||||
{
|
||||
if (! $this->db->tableExists('invoices')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$count = $this->db->table('invoices')
|
||||
->where('school_year', $schoolYear)
|
||||
->where('balance >', 0)
|
||||
->countAllResults();
|
||||
|
||||
return $count > 0
|
||||
? [$this->finding('warning', 'Outstanding balances exist', "{$count} invoice(s) still have a positive balance and will require carry-forward review.")]
|
||||
: [];
|
||||
}
|
||||
|
||||
private function carryForwardFamilies(string $schoolYear): array
|
||||
{
|
||||
if (! $this->db->tableExists('invoices')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->db->table('invoices i')
|
||||
->select('i.parent_id AS family_id')
|
||||
->select('COALESCE(SUM(i.balance), 0) AS source_balance')
|
||||
->where('i.school_year', $schoolYear)
|
||||
->groupBy('i.parent_id')
|
||||
->having('source_balance !=', 0)
|
||||
->orderBy('i.parent_id', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
return array_map(static function (array $row): array {
|
||||
$balance = round((float) $row['source_balance'], 2);
|
||||
|
||||
return [
|
||||
'family_id' => (int) $row['family_id'],
|
||||
'family' => 'Family #' . (int) $row['family_id'],
|
||||
'source_balance' => $balance,
|
||||
'credit_amount' => $balance < 0 ? abs($balance) : 0.0,
|
||||
'adjustment_amount' => 0.0,
|
||||
'carry_forward_amount' => $balance,
|
||||
];
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
private function countBySchoolYear(string $table, string $schoolYear, string $distinctField): int
|
||||
{
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$row = $this->db->table($table)
|
||||
->select("COUNT(DISTINCT {$distinctField}) AS total", false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
return (int) ($row['total'] ?? 0);
|
||||
}
|
||||
|
||||
private function countFamilies(string $schoolYear): int
|
||||
{
|
||||
if ($this->db->tableExists('invoices')) {
|
||||
$row = $this->db->table('invoices')
|
||||
->select('COUNT(DISTINCT parent_id) AS total', false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
return (int) ($row['total'] ?? 0);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private function countMissingSchoolYearRows(string $table): int
|
||||
{
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $this->db->table($table)
|
||||
->groupStart()
|
||||
->where('school_year', null)
|
||||
->orWhere('school_year', '')
|
||||
->groupEnd()
|
||||
->countAllResults();
|
||||
}
|
||||
|
||||
private function latestOpenBatch(int $sourceYearId): ?array
|
||||
{
|
||||
return $this->batchModel
|
||||
->where('source_school_year_id', $sourceYearId)
|
||||
->whereIn('status', ['started', 'executed'])
|
||||
->orderBy('id', 'DESC')
|
||||
->first();
|
||||
}
|
||||
|
||||
private function assertClosingTablesExist(): void
|
||||
{
|
||||
foreach (['school_year_closing_batches', 'school_year_closing_items', 'school_year_transition_logs'] as $table) {
|
||||
if (! $this->db->tableExists($table)) {
|
||||
throw new RuntimeException('School year lifecycle tables are missing. Run database migrations before closing a school year.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function finding(string $severity, string $title, string $detail): array
|
||||
{
|
||||
return [
|
||||
'severity' => $severity,
|
||||
'title' => $title,
|
||||
'detail' => $detail,
|
||||
];
|
||||
}
|
||||
|
||||
private function hashPreview(array $preview): string
|
||||
{
|
||||
return hash('sha256', json_encode([
|
||||
'source_id' => $preview['source']['id'] ?? null,
|
||||
'target_id' => $preview['target']['id'] ?? null,
|
||||
'finance' => $preview['finance'],
|
||||
'carry_forward' => $preview['carry_forward'],
|
||||
'blockers' => $preview['blockers'],
|
||||
], JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Support\SchoolYear\SchoolYearContext;
|
||||
use CodeIgniter\HTTP\IncomingRequest;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearContextService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
) {
|
||||
}
|
||||
|
||||
public function resolve(
|
||||
IncomingRequest $request,
|
||||
?int $routeSchoolYearId = null
|
||||
): SchoolYearContext {
|
||||
$requestedId = $routeSchoolYearId
|
||||
?? $this->normalizeInt($request->getGet('school_year_id'));
|
||||
|
||||
$requestedName = trim((string) $request->getGet('school_year'));
|
||||
|
||||
if ($requestedId !== null && $requestedName !== '') {
|
||||
$row = $this->schoolYearModel->find($requestedId);
|
||||
|
||||
if ($row === null || (string) ($row['name'] ?? '') !== $requestedName) {
|
||||
throw new RuntimeException('Selected school-year parameters conflict.');
|
||||
}
|
||||
|
||||
return $this->fromRow($row, true);
|
||||
}
|
||||
|
||||
if ($requestedId !== null) {
|
||||
$row = $this->schoolYearModel->find($requestedId);
|
||||
|
||||
if ($row === null) {
|
||||
throw new RuntimeException('Selected school year was not found.');
|
||||
}
|
||||
|
||||
return $this->fromRow($row, true);
|
||||
}
|
||||
|
||||
if ($requestedName !== '') {
|
||||
$row = $this->schoolYearModel
|
||||
->where('name', $requestedName)
|
||||
->first();
|
||||
|
||||
if ($row === null) {
|
||||
throw new RuntimeException('Selected school year was not found.');
|
||||
}
|
||||
|
||||
return $this->fromRow($row, true);
|
||||
}
|
||||
|
||||
$sessionYearId = session('selected_school_year_id');
|
||||
|
||||
if (is_numeric($sessionYearId)) {
|
||||
$row = $this->schoolYearModel->find((int) $sessionYearId);
|
||||
|
||||
if ($row !== null) {
|
||||
return $this->fromRow($row, false);
|
||||
}
|
||||
}
|
||||
|
||||
$active = $this->schoolYearModel->active();
|
||||
|
||||
if ($active === null) {
|
||||
throw new RuntimeException('No active school year is configured.');
|
||||
}
|
||||
|
||||
return $this->fromRow($active, false);
|
||||
}
|
||||
|
||||
private function normalizeInt(mixed $value): ?int
|
||||
{
|
||||
if ($value === null || $value === '' || ! ctype_digit((string) $value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
private function fromRow(array $row, bool $explicit): SchoolYearContext
|
||||
{
|
||||
return new SchoolYearContext(
|
||||
id: (int) $row['id'],
|
||||
yearName: (string) $row['name'],
|
||||
status: (string) $row['status'],
|
||||
explicitSelection: $explicit,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\SchoolYearClosingBatchModel;
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Models\SchoolYearTransitionLogModel;
|
||||
use App\Support\SchoolYear\SchoolYearStatus;
|
||||
use CodeIgniter\Database\BaseConnection;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearManagementService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
private readonly ConfigurationModel $configurationModel,
|
||||
private readonly SchoolYearTransitionLogModel $transitionLogModel,
|
||||
private readonly SchoolYearClosingBatchModel $closingBatchModel,
|
||||
private readonly SchoolYearValidationService $validationService,
|
||||
private readonly BaseConnection $db,
|
||||
) {
|
||||
}
|
||||
|
||||
public function createDraft(array $payload, ?int $userId = null): int
|
||||
{
|
||||
$payload = $this->metadataPayload($payload);
|
||||
$payload['status'] = SchoolYearStatus::DRAFT;
|
||||
$payload['created_by'] = $userId;
|
||||
$payload['updated_by'] = $userId;
|
||||
|
||||
$this->validationService->validateMetadata($payload);
|
||||
|
||||
$this->db->transStart();
|
||||
$id = $this->schoolYearModel->insert($payload, true);
|
||||
if ($id !== false) {
|
||||
$this->log((int) $id, null, SchoolYearStatus::DRAFT, 'create', $userId);
|
||||
}
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($id === false || $this->db->transStatus() === false) {
|
||||
throw new RuntimeException($this->firstModelError('Unable to create school year.'));
|
||||
}
|
||||
|
||||
return (int) $id;
|
||||
}
|
||||
|
||||
public function updateMetadata(int $id, array $payload, ?int $userId = null): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
$status = (string) $year['status'];
|
||||
|
||||
if (SchoolYearStatus::isReadonly($status) || $status === SchoolYearStatus::CLOSING) {
|
||||
throw new InvalidArgumentException('This school year is read-only and cannot be edited.');
|
||||
}
|
||||
|
||||
$payload = $this->metadataPayload($payload);
|
||||
$payload['updated_by'] = $userId;
|
||||
$this->validationService->validateMetadata($payload, $id);
|
||||
|
||||
$this->db->transStart();
|
||||
$updated = $this->schoolYearModel->update($id, $payload);
|
||||
if ($updated !== false) {
|
||||
$this->log($id, $status, $status, 'metadata_update', $userId);
|
||||
}
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($updated === false || $this->db->transStatus() === false) {
|
||||
throw new RuntimeException($this->firstModelError('Unable to update school year.'));
|
||||
}
|
||||
}
|
||||
|
||||
public function activate(int $id, ?int $userId = null): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
$from = (string) $year['status'];
|
||||
|
||||
if (! SchoolYearStatus::canTransition($from, SchoolYearStatus::ACTIVE)) {
|
||||
throw new InvalidArgumentException('Only draft or approved reopened school years can be activated.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$activeYears = $this->schoolYearModel->where('status', SchoolYearStatus::ACTIVE)->findAll();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
foreach ($activeYears as $activeYear) {
|
||||
if ((int) $activeYear['id'] === $id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update((int) $activeYear['id'], [
|
||||
'status' => SchoolYearStatus::CLOSING,
|
||||
'closing_started_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->log((int) $activeYear['id'], SchoolYearStatus::ACTIVE, SchoolYearStatus::CLOSING, 'activation_displaced_active_year', $userId, [
|
||||
'activated_school_year_id' => $id,
|
||||
]);
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update($id, [
|
||||
'status' => SchoolYearStatus::ACTIVE,
|
||||
'activated_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->configurationModel->setConfigValueByKey('school_year', (string) $year['name']);
|
||||
$this->log($id, $from, SchoolYearStatus::ACTIVE, 'activate', $userId);
|
||||
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to activate school year.');
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteDraft(int $id, ?int $userId = null): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
if (($year['status'] ?? '') !== SchoolYearStatus::DRAFT) {
|
||||
throw new InvalidArgumentException('Only unused draft school years can be deleted. Archive historical years instead.');
|
||||
}
|
||||
|
||||
if ($this->hasDependentRecords($id, (string) $year['name'])) {
|
||||
throw new InvalidArgumentException('This school year cannot be deleted because related data exists. Archive historical years instead.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$this->log($id, SchoolYearStatus::DRAFT, null, 'delete_draft', $userId);
|
||||
$this->schoolYearModel->delete($id);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to delete draft school year.');
|
||||
}
|
||||
}
|
||||
|
||||
public function archive(int $id, ?int $userId = null): void
|
||||
{
|
||||
$this->transition($id, SchoolYearStatus::ARCHIVED, 'archive', $userId, [
|
||||
'archived_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function reopen(int $id, string $reason, ?int $userId = null): void
|
||||
{
|
||||
if (trim($reason) === '') {
|
||||
throw new InvalidArgumentException('A reopen reason is required.');
|
||||
}
|
||||
|
||||
$this->transition($id, SchoolYearStatus::ACTIVE, 'reopen', $userId, [
|
||||
'metadata' => ['reason' => trim($reason)],
|
||||
]);
|
||||
}
|
||||
|
||||
public function latestTransitionByYear(): array
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_transition_logs')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->transitionLogModel
|
||||
->orderBy('created_at', 'DESC')
|
||||
->findAll();
|
||||
$latest = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$yearId = (int) ($row['school_year_id'] ?? 0);
|
||||
if ($yearId > 0 && ! isset($latest[$yearId])) {
|
||||
$latest[$yearId] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
return $latest;
|
||||
}
|
||||
|
||||
public function log(int $schoolYearId, ?string $from, ?string $to, string $action, ?int $userId = null, array $metadata = []): void
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_transition_logs')) {
|
||||
throw new RuntimeException('School year lifecycle tables are missing. Run database migrations before changing school-year status.');
|
||||
}
|
||||
|
||||
$this->transitionLogModel->insert([
|
||||
'school_year_id' => $schoolYearId,
|
||||
'from_status' => $from,
|
||||
'to_status' => $to,
|
||||
'action' => $action,
|
||||
'performed_by' => $userId,
|
||||
'metadata_json' => $metadata !== [] ? json_encode($metadata, JSON_UNESCAPED_SLASHES) : null,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
|
||||
private function transition(int $id, string $to, string $action, ?int $userId, array $options = []): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
$from = (string) $year['status'];
|
||||
|
||||
if (! SchoolYearStatus::canTransition($from, $to)) {
|
||||
throw new InvalidArgumentException("Cannot transition school year from {$from} to {$to}.");
|
||||
}
|
||||
|
||||
if ($to === SchoolYearStatus::ARCHIVED && ! $this->hasFinalizedClosingBatch($id)) {
|
||||
throw new InvalidArgumentException('A school year can be archived only after a finalized closing batch exists.');
|
||||
}
|
||||
|
||||
if ($to === SchoolYearStatus::ACTIVE) {
|
||||
$otherActive = $this->schoolYearModel
|
||||
->where('status', SchoolYearStatus::ACTIVE)
|
||||
->where('id !=', $id)
|
||||
->first();
|
||||
if ($otherActive !== null) {
|
||||
throw new InvalidArgumentException('Another school year is already active. Activate or close years through the controlled lifecycle first.');
|
||||
}
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$data = [
|
||||
'status' => $to,
|
||||
'updated_by' => $userId,
|
||||
];
|
||||
|
||||
foreach (['archived_at', 'closed_at', 'closing_started_at'] as $field) {
|
||||
if (isset($options[$field])) {
|
||||
$data[$field] = $options[$field];
|
||||
}
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update($id, $data);
|
||||
$this->log($id, $from, $to, $action, $userId, $options['metadata'] ?? []);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to update school year status.');
|
||||
}
|
||||
}
|
||||
|
||||
private function requireYear(int $id): array
|
||||
{
|
||||
$year = $this->schoolYearModel->find($id);
|
||||
if ($year === null) {
|
||||
throw new InvalidArgumentException('School year not found.');
|
||||
}
|
||||
|
||||
return $year;
|
||||
}
|
||||
|
||||
private function metadataPayload(array $payload): array
|
||||
{
|
||||
return [
|
||||
'name' => trim((string) ($payload['name'] ?? '')),
|
||||
'starts_on' => $this->nullableDate($payload['starts_on'] ?? null),
|
||||
'ends_on' => $this->nullableDate($payload['ends_on'] ?? null),
|
||||
'description' => trim((string) ($payload['description'] ?? '')) ?: null,
|
||||
'registration_starts_on' => $this->nullableDate($payload['registration_starts_on'] ?? null),
|
||||
'registration_ends_on' => $this->nullableDate($payload['registration_ends_on'] ?? null),
|
||||
'previous_school_year_id' => $this->nullableInt($payload['previous_school_year_id'] ?? null),
|
||||
];
|
||||
}
|
||||
|
||||
private function nullableDate(mixed $value): ?string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
|
||||
return $value !== '' ? $value : null;
|
||||
}
|
||||
|
||||
private function nullableInt(mixed $value): ?int
|
||||
{
|
||||
return is_numeric($value) && (int) $value > 0 ? (int) $value : null;
|
||||
}
|
||||
|
||||
private function hasDependentRecords(int $id, string $name): bool
|
||||
{
|
||||
if (
|
||||
$this->db->tableExists('school_year_closing_batches')
|
||||
&& $this->closingBatchModel->where('source_school_year_id', $id)->orWhere('target_school_year_id', $id)->first() !== null
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach (['invoices', 'payments', 'student_class', 'teacher_class', 'calendar_events', 'events'] as $table) {
|
||||
if ($this->db->tableExists($table) && $this->db->fieldExists('school_year', $table)) {
|
||||
$count = $this->db->table($table)->where('school_year', $name)->countAllResults();
|
||||
if ($count > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function hasFinalizedClosingBatch(int $sourceSchoolYearId): bool
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_closing_batches')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->closingBatchModel
|
||||
->where('source_school_year_id', $sourceSchoolYearId)
|
||||
->whereIn('status', ['completed', 'closed'])
|
||||
->first() !== null;
|
||||
}
|
||||
|
||||
private function firstModelError(string $fallback): string
|
||||
{
|
||||
$errors = $this->schoolYearModel->errors();
|
||||
$first = reset($errors);
|
||||
|
||||
return is_string($first) && $first !== '' ? $first : $fallback;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SchoolYearModel;
|
||||
use DateTimeImmutable;
|
||||
use InvalidArgumentException;
|
||||
|
||||
final class SchoolYearValidationService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
) {
|
||||
}
|
||||
|
||||
public function validateMetadata(array $payload, ?int $exceptId = null): void
|
||||
{
|
||||
$name = trim((string) ($payload['name'] ?? ''));
|
||||
|
||||
if (! $this->isValidYearName($name)) {
|
||||
throw new InvalidArgumentException('School year must use YYYY-YYYY with consecutive years.');
|
||||
}
|
||||
|
||||
$existing = $this->schoolYearModel->where('name', $name);
|
||||
if ($exceptId !== null) {
|
||||
$existing->where('id !=', $exceptId);
|
||||
}
|
||||
if ($existing->first() !== null) {
|
||||
throw new InvalidArgumentException('That school year already exists.');
|
||||
}
|
||||
|
||||
$startsOn = $this->dateOrNull($payload['starts_on'] ?? null);
|
||||
$endsOn = $this->dateOrNull($payload['ends_on'] ?? null);
|
||||
if ($startsOn !== null && $endsOn !== null && $startsOn >= $endsOn) {
|
||||
throw new InvalidArgumentException('School year start date must be before the end date.');
|
||||
}
|
||||
|
||||
$registrationStarts = $this->dateOrNull($payload['registration_starts_on'] ?? null);
|
||||
$registrationEnds = $this->dateOrNull($payload['registration_ends_on'] ?? null);
|
||||
if ($registrationStarts !== null && $registrationEnds !== null && $registrationStarts > $registrationEnds) {
|
||||
throw new InvalidArgumentException('Registration start date must be on or before the registration end date.');
|
||||
}
|
||||
}
|
||||
|
||||
public function isValidYearName(string $value): bool
|
||||
{
|
||||
if (! preg_match('/^(\d{4})-(\d{4})$/', $value, $matches)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (int) $matches[2] === (int) $matches[1] + 1;
|
||||
}
|
||||
|
||||
private function dateOrNull(mixed $value): ?DateTimeImmutable
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
|
||||
if (! $date instanceof DateTimeImmutable || $date->format('Y-m-d') !== $value) {
|
||||
throw new InvalidArgumentException('Dates must use YYYY-MM-DD.');
|
||||
}
|
||||
|
||||
return $date;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\SchoolYear\SchoolYearContext;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearWriteGuard
|
||||
{
|
||||
public function assertWritable(
|
||||
SchoolYearContext $context,
|
||||
bool $allowDraftForAdmin = false,
|
||||
bool $isAdmin = false
|
||||
): void {
|
||||
if ($context->status() === 'active') {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($context->status() === 'draft' && $allowDraftForAdmin && $isAdmin) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new RuntimeException('The selected school year is read-only.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\SchoolYear;
|
||||
|
||||
final class SchoolYearContext
|
||||
{
|
||||
public function __construct(
|
||||
private readonly int $id,
|
||||
private readonly string $yearName,
|
||||
private readonly string $status,
|
||||
private readonly bool $explicitSelection = false,
|
||||
) {
|
||||
}
|
||||
|
||||
public function id(): int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function yearName(): string
|
||||
{
|
||||
return $this->yearName;
|
||||
}
|
||||
|
||||
public function status(): string
|
||||
{
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->status === 'active';
|
||||
}
|
||||
|
||||
public function isReadonly(): bool
|
||||
{
|
||||
return in_array($this->status, ['closed', 'archived'], true);
|
||||
}
|
||||
|
||||
public function isExplicitSelection(): bool
|
||||
{
|
||||
return $this->explicitSelection;
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->yearName,
|
||||
'status' => $this->status,
|
||||
'readonly' => $this->isReadonly(),
|
||||
'explicitSelection' => $this->explicitSelection,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\SchoolYear;
|
||||
|
||||
final class SchoolYearStatus
|
||||
{
|
||||
public const DRAFT = 'draft';
|
||||
public const ACTIVE = 'active';
|
||||
public const CLOSING = 'closing';
|
||||
public const CLOSED = 'closed';
|
||||
public const ARCHIVED = 'archived';
|
||||
|
||||
public const ALL = [
|
||||
self::DRAFT,
|
||||
self::ACTIVE,
|
||||
self::CLOSING,
|
||||
self::CLOSED,
|
||||
self::ARCHIVED,
|
||||
];
|
||||
|
||||
public const TRANSITIONS = [
|
||||
self::DRAFT => [self::ACTIVE],
|
||||
self::ACTIVE => [self::CLOSING],
|
||||
self::CLOSING => [self::ACTIVE, self::CLOSED],
|
||||
self::CLOSED => [self::ACTIVE, self::ARCHIVED],
|
||||
self::ARCHIVED => [],
|
||||
];
|
||||
|
||||
public static function canTransition(string $from, string $to): bool
|
||||
{
|
||||
return in_array($to, self::TRANSITIONS[$from] ?? [], true);
|
||||
}
|
||||
|
||||
public static function isReadonly(string $status): bool
|
||||
{
|
||||
return in_array($status, [self::CLOSED, self::ARCHIVED], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\SchoolYear;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
final class SchoolYearTableRegistry
|
||||
{
|
||||
public const YEAR_SCOPED = [
|
||||
'additional_charges',
|
||||
'archived_paypal_transactions',
|
||||
'attendance_data',
|
||||
'attendance_day',
|
||||
'attendance_record',
|
||||
'attendance_tracking',
|
||||
'badge_print_logs',
|
||||
'below_sixty_decisions',
|
||||
'calendar_events',
|
||||
'certificate_records',
|
||||
'classSection',
|
||||
'class_progress_reports',
|
||||
'competitions',
|
||||
'current_flag',
|
||||
'discount_vouchers',
|
||||
'early_dismissal_signatures',
|
||||
'enrollments',
|
||||
'events',
|
||||
'exams',
|
||||
'exam_drafts',
|
||||
'expenses',
|
||||
'final_exam',
|
||||
'final_score',
|
||||
'flag',
|
||||
'grading_locks',
|
||||
'homework',
|
||||
'inventory_movements',
|
||||
'invoices',
|
||||
'late_slip_logs',
|
||||
'manual_payments',
|
||||
'midterm_exam',
|
||||
'missing_score_overrides',
|
||||
'parent_attendance_reports',
|
||||
'parent_meeting_schedules',
|
||||
'parent_notifications',
|
||||
'participation',
|
||||
'payments',
|
||||
'payment_transactions',
|
||||
'placement_batches',
|
||||
'print_requests',
|
||||
'project',
|
||||
'quiz',
|
||||
'refunds',
|
||||
'reimbursements',
|
||||
'reimbursement_batches',
|
||||
'report_card_acknowledgements',
|
||||
'scan_log',
|
||||
'score_comments',
|
||||
'semester_scores',
|
||||
'staff_attendance',
|
||||
'student_class',
|
||||
'student_decisions',
|
||||
'teacher_attendance_data',
|
||||
'teacher_class',
|
||||
'teacher_submission_notification_history',
|
||||
'whatsapp_group_links',
|
||||
'whatsapp_group_memberships',
|
||||
];
|
||||
|
||||
public const GLOBAL = [
|
||||
'authorized_users',
|
||||
'cache',
|
||||
'cache_locks',
|
||||
'configuration',
|
||||
'email_templates',
|
||||
'ip_attempts',
|
||||
'login_activity',
|
||||
'migrations',
|
||||
'nav_items',
|
||||
'parent_accounts',
|
||||
'password_reset_requests',
|
||||
'password_resets',
|
||||
'permissions',
|
||||
'personal_access_tokens',
|
||||
'preferences',
|
||||
'role_nav_items',
|
||||
'role_permissions',
|
||||
'roles',
|
||||
'school_years',
|
||||
'sessions',
|
||||
'settings',
|
||||
'user_preferences',
|
||||
'user_roles',
|
||||
'users',
|
||||
];
|
||||
|
||||
public const IDENTITY_WITH_YEAR_RELATION = [
|
||||
'emergency_contacts',
|
||||
'families',
|
||||
'family_guardians',
|
||||
'family_students',
|
||||
'parents',
|
||||
'staff',
|
||||
'student_allergies',
|
||||
'student_medical_conditions',
|
||||
'students',
|
||||
'teachers',
|
||||
];
|
||||
|
||||
public const CONTEXT = [
|
||||
'audit_logs',
|
||||
'communication_logs',
|
||||
'contactus',
|
||||
'finance_notification_logs',
|
||||
'messages',
|
||||
'notification_recipients',
|
||||
'notifications',
|
||||
'payment_notification_logs',
|
||||
'support_requests',
|
||||
'user_notifications',
|
||||
];
|
||||
|
||||
public static function isYearScoped(string $table): bool
|
||||
{
|
||||
return in_array($table, self::YEAR_SCOPED, true);
|
||||
}
|
||||
|
||||
public static function isGlobal(string $table): bool
|
||||
{
|
||||
return in_array($table, self::GLOBAL, true);
|
||||
}
|
||||
|
||||
public static function isIdentityWithYearRelation(string $table): bool
|
||||
{
|
||||
return in_array($table, self::IDENTITY_WITH_YEAR_RELATION, true);
|
||||
}
|
||||
|
||||
public static function isContext(string $table): bool
|
||||
{
|
||||
return in_array($table, self::CONTEXT, true);
|
||||
}
|
||||
|
||||
public static function categoryOf(string $table): string
|
||||
{
|
||||
return match (true) {
|
||||
self::isYearScoped($table) => 'YEAR_SCOPED',
|
||||
self::isGlobal($table) => 'GLOBAL',
|
||||
self::isIdentityWithYearRelation($table) => 'IDENTITY_WITH_YEAR_RELATION',
|
||||
self::isContext($table) => 'CONTEXT',
|
||||
default => throw new InvalidArgumentException(
|
||||
"Table '{$table}' is not registered for school-year behavior."
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ $warningText = static function (array $warnings): string {
|
||||
'include_event_only' => !empty($filters['include_event_only']) ? '1' : '0',
|
||||
'include_paid_invoices' => !empty($filters['include_paid_invoices']) ? '1' : '0',
|
||||
'unit_price' => $filters['unit_price'] ?? '',
|
||||
'youth_unit_price' => $filters['youth_unit_price'] ?? '',
|
||||
]);
|
||||
?>
|
||||
<a href="<?= site_url('administrator/tuition-forecast/export?' . $exportQuery) ?>" class="btn btn-success">
|
||||
@@ -79,7 +80,7 @@ $warningText = static function (array $warnings): string {
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="unit_price" class="form-label">Unit Price</label>
|
||||
<label for="unit_price" class="form-label">Grades Unit Price</label>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
@@ -88,7 +89,19 @@ $warningText = static function (array $warnings): string {
|
||||
name="unit_price"
|
||||
class="form-control"
|
||||
value="<?= esc((string) ($filters['unit_price'] ?? ($summary['unit_price'] ?? ''))) ?>"
|
||||
placeholder="New tuition unit price">
|
||||
placeholder="New tuition unit price for grades">
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="youth_unit_price" class="form-label">Youth Unit Price</label>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
id="youth_unit_price"
|
||||
name="youth_unit_price"
|
||||
class="form-control"
|
||||
value="<?= esc((string) ($filters['youth_unit_price'] ?? ($summary['youth_unit_price'] ?? ''))) ?>"
|
||||
placeholder="New tuition unit price for youth">
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<div class="form-check">
|
||||
@@ -109,7 +122,7 @@ $warningText = static function (array $warnings): string {
|
||||
|
||||
<?php if ($result): ?>
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-md-2">
|
||||
<div class="col-xl col-lg-3 col-md-4">
|
||||
<div class="card border-0 shadow-sm h-100">
|
||||
<div class="card-body">
|
||||
<div class="text-muted small">Total Parents</div>
|
||||
@@ -117,7 +130,7 @@ $warningText = static function (array $warnings): string {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<div class="col-xl col-lg-3 col-md-4">
|
||||
<div class="card border-0 shadow-sm h-100">
|
||||
<div class="card-body">
|
||||
<div class="text-muted small">Total Students</div>
|
||||
@@ -126,7 +139,7 @@ $warningText = static function (array $warnings): string {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<div class="col-xl col-lg-3 col-md-4">
|
||||
<div class="card border-0 shadow-sm h-100">
|
||||
<div class="card-body">
|
||||
<div class="text-muted small">Old Projected Income</div>
|
||||
@@ -134,7 +147,7 @@ $warningText = static function (array $warnings): string {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<div class="col-xl col-lg-3 col-md-4">
|
||||
<div class="card border-0 shadow-sm h-100">
|
||||
<div class="card-body">
|
||||
<div class="text-muted small">New Projected Income</div>
|
||||
@@ -142,15 +155,23 @@ $warningText = static function (array $warnings): string {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<div class="col-xl col-lg-3 col-md-4">
|
||||
<div class="card border-0 shadow-sm h-100">
|
||||
<div class="card-body">
|
||||
<div class="text-muted small">Unit Price</div>
|
||||
<div class="text-muted small">Grades Unit Price</div>
|
||||
<div class="fs-5 fw-semibold"><?= esc($fmtMoney($summary['unit_price'] ?? 0)) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<div class="col-xl col-lg-3 col-md-4">
|
||||
<div class="card border-0 shadow-sm h-100">
|
||||
<div class="card-body">
|
||||
<div class="text-muted small">Youth Unit Price</div>
|
||||
<div class="fs-5 fw-semibold"><?= esc($fmtMoney($summary['youth_unit_price'] ?? 0)) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-xl col-lg-3 col-md-4">
|
||||
<div class="card border-0 shadow-sm h-100">
|
||||
<div class="card-body">
|
||||
<div class="text-muted small">Difference</div>
|
||||
|
||||
@@ -262,9 +262,9 @@ $show_actions = false; // notified page hides actions by design
|
||||
|
||||
// Initialize Bootstrap tooltips (for "View full" note)
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
if (window.bootstrap) {
|
||||
if (window.bootstrap && bootstrap.Tooltip) {
|
||||
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
|
||||
tooltipTriggerList.forEach(function (el) { new bootstrap.Tooltip(el); });
|
||||
tooltipTriggerList.forEach(function (el) { bootstrap.Tooltip.getOrCreateInstance(el); });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -350,19 +350,20 @@ if ($returnUrl === '') {
|
||||
<table class="table table-sm table-striped table-hover align-middle fc-table-stack">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>Invoice</th><th>Amount</th><th>Balance</th><th>Method</th><th>Date</th><th>Status</th>
|
||||
<th>Invoice</th><th>Amount</th><th>Invoice Balance</th><th>Method</th><th>Date</th><th>Payment Status</th><th>Invoice Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php $imap = $f['invoice_map'] ?? []; ?>
|
||||
<?php foreach ($f['payments'] as $p): ?>
|
||||
<tr>
|
||||
<td data-label="Invoice"><?php $iid = (int)($p['invoice_id'] ?? 0); echo esc($imap[$iid] ?? ('#'.$iid)); ?></td>
|
||||
<td data-label="Invoice"><?php $iid = (int)($p['invoice_id'] ?? 0); echo esc($p['invoice_number'] ?? $imap[$iid] ?? ('#'.$iid)); ?></td>
|
||||
<td data-label="Amount">$<?= number_format((float)($p['paid_amount'] ?? 0), 2) ?></td>
|
||||
<td data-label="Balance">$<?= number_format((float)($p['balance'] ?? 0), 2) ?></td>
|
||||
<td data-label="Invoice Balance">$<?= number_format((float)($p['invoice_current_balance'] ?? 0), 2) ?></td>
|
||||
<td data-label="Method"><?= esc($p['payment_method'] ?? '') ?></td>
|
||||
<td data-label="Date"><?= esc(!empty($p['payment_date']) ? local_date($p['payment_date'], 'm-d-Y') : '') ?></td>
|
||||
<td data-label="Status"><?= esc($p['status'] ?? '') ?></td>
|
||||
<td data-label="Payment Status"><?= esc($p['payment_status'] ?? '') ?></td>
|
||||
<td data-label="Invoice Status"><?= esc($p['invoice_status'] ?? '') ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
|
||||
@@ -263,19 +263,20 @@
|
||||
<table class="table table-sm table-striped table-hover align-middle">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th>Invoice</th><th>Amount</th><th>Balance</th><th>Method</th><th>Date</th><th>Status</th>
|
||||
<th>Invoice</th><th>Amount</th><th>Invoice Balance</th><th>Method</th><th>Date</th><th>Payment Status</th><th>Invoice Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php $imap = $f['invoice_map'] ?? []; ?>
|
||||
<?php foreach ($f['payments'] as $p): ?>
|
||||
<tr>
|
||||
<td><?php $iid = (int)($p['invoice_id'] ?? 0); echo esc($imap[$iid] ?? ('#'.$iid)); ?></td>
|
||||
<td><?php $iid = (int)($p['invoice_id'] ?? 0); echo esc($p['invoice_number'] ?? $imap[$iid] ?? ('#'.$iid)); ?></td>
|
||||
<td>$<?= number_format((float)($p['paid_amount'] ?? 0), 2) ?></td>
|
||||
<td>$<?= number_format((float)($p['balance'] ?? 0), 2) ?></td>
|
||||
<td>$<?= number_format((float)($p['invoice_current_balance'] ?? 0), 2) ?></td>
|
||||
<td><?= esc($p['payment_method'] ?? '') ?></td>
|
||||
<td><?= esc(!empty($p['payment_date']) ? local_date($p['payment_date'], 'm-d-Y') : '') ?></td>
|
||||
<td><?= esc($p['status'] ?? '') ?></td>
|
||||
<td><?= esc($p['payment_status'] ?? '') ?></td>
|
||||
<td><?= esc($p['invoice_status'] ?? '') ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
|
||||
@@ -41,8 +41,6 @@
|
||||
|
||||
<!-- Bootstrap Bundle JS (for modal, tooltips, etc.) -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<!-- Optional: Your other custom scripts -->
|
||||
<script src="<?= base_url('assets/js/bootstrap.min.js') ?>"></script>
|
||||
<!-- ✅ Your validation logic (depends on jQuery & Select2) -->
|
||||
<script type="module" src="/public/assets/js/validate_student.js"></script>
|
||||
<script src="<?= base_url('assets/js/modal_validation.js') ?>"></script>
|
||||
|
||||
@@ -250,18 +250,19 @@ html, body { overflow-x: hidden; }
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bootstrap Bundle (with Popper) -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
if (!window.bootstrap || !bootstrap.Tooltip) return;
|
||||
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
|
||||
tooltipTriggerList.forEach(function(tooltipTriggerEl) {
|
||||
new bootstrap.Tooltip(tooltipTriggerEl);
|
||||
bootstrap.Tooltip.getOrCreateInstance(tooltipTriggerEl);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Bootstrap Bundle (with Popper) -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
|
||||
<!-- Additional JS Libraries -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
|
||||
<script src="<?= base_url('lib/wow/wow.min.js') ?>"></script>
|
||||
|
||||
@@ -36,7 +36,6 @@
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
|
||||
|
||||
<!-- ✅ Custom JS -->
|
||||
<script src="<?= base_url('assets/js/bootstrap.min.js') ?>"></script>
|
||||
<script src="<?= base_url('assets/js/modal_validation.js') ?>"></script>
|
||||
<script src="<?= base_url('assets/js/validation.js') ?>" defer></script>
|
||||
|
||||
|
||||
@@ -118,11 +118,6 @@
|
||||
</div>
|
||||
|
||||
<br>
|
||||
<?php include(__DIR__ . '/../partials/footer.php'); ?>
|
||||
|
||||
<!-- Bootstrap JS -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
|
||||
|
||||
<!-- JavaScript for Phone and Email Validation -->
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
|
||||
@@ -21,15 +21,17 @@
|
||||
<th>Date</th>
|
||||
<th>Invoice</th>
|
||||
<th class="text-end">Paid</th>
|
||||
<th class="text-end">Balance</th>
|
||||
<th class="text-end">Invoice Balance</th>
|
||||
<th>Method</th>
|
||||
<th>Status</th>
|
||||
<th>Payment Status</th>
|
||||
<th>Invoice Status</th>
|
||||
<th>School Year</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if (empty($payments)): ?>
|
||||
<tr>
|
||||
<td colspan="6" class="text-center text-muted py-4">No payment</td>
|
||||
<td colspan="8" class="text-center text-muted py-4">No payment</td>
|
||||
</tr>
|
||||
<?php else: ?>
|
||||
<?php foreach ($payments as $p): ?>
|
||||
@@ -40,9 +42,11 @@
|
||||
<?= $inv !== '' ? esc($inv) : ('#' . (int)($p['invoice_id'] ?? 0)) ?>
|
||||
</td>
|
||||
<td class="text-end">$<?= number_format((float)($p['paid_amount'] ?? 0), 2) ?></td>
|
||||
<td class="text-end">$<?= number_format((float)($p['balance'] ?? 0), 2) ?></td>
|
||||
<td class="text-end">$<?= number_format((float)($p['invoice_current_balance'] ?? 0), 2) ?></td>
|
||||
<td><?= esc($p['payment_method'] ?? '') ?></td>
|
||||
<td><?= esc($p['status'] ?? '') ?></td>
|
||||
<td><?= esc($p['payment_status'] ?? '') ?></td>
|
||||
<td><?= esc($p['invoice_status'] ?? '') ?></td>
|
||||
<td><?= esc($p['school_year'] ?? '') ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php endif; ?>
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
<div class="d-flex align-items-center gap-2 my-3 flex-nowrap w-100 overflow-auto" style="white-space: nowrap;">
|
||||
<!-- School year filter -->
|
||||
<form id="summaryYearFilter" class="d-flex align-items-center gap-2 flex-nowrap me-auto" method="get" action="<?= site_url('financial-report/financialReportSummary') ?>" style="white-space: nowrap;">
|
||||
<input type="hidden" name="date_from" value="<?= esc((string)($dateFrom ?? '')) ?>">
|
||||
<input type="hidden" name="date_to" value="<?= esc((string)($dateTo ?? '')) ?>">
|
||||
<label class="form-label mb-0 me-2">School year</label>
|
||||
<select name="school_year" class="form-select form-select-sm rounded-pill px-3" style="min-width: 180px;">
|
||||
<?php foreach (($schoolYears ?? []) as $sy): ?>
|
||||
@@ -16,7 +18,8 @@
|
||||
</form>
|
||||
<!-- Action buttons -->
|
||||
<div class="d-flex align-items-center gap-2 flex-nowrap flex-shrink-0" style="white-space: nowrap;">
|
||||
<a href="<?= base_url('reports/downloadFinancialReport') ?>" class="btn btn-primary">Download PDF</a>
|
||||
<a id="downloadSummaryCsvLink" href="<?= base_url('financial-report/downloadSummaryCsv') ?>" class="btn btn-success">Download CSV</a>
|
||||
<a id="downloadSummaryAllDetailsCsvLink" href="<?= base_url('financial-report/downloadSummaryAllDetailsCsv') ?>" class="btn btn-primary">Download All Details CSV</a>
|
||||
<a href="<?= base_url('/payment/financial_report') ?>" class="btn btn-secondary">Back To Detailed Report</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -31,21 +34,31 @@
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="summaryBody">
|
||||
<tr><td>Total Charges</td><td class="text-right" id="sumCharges">$0.00</td></tr>
|
||||
<tr><td>Event Fees</td><td class="text-right" id="sumEventFees">$0.00</td></tr>
|
||||
<tr><td>Total Extra Charges</td><td class="text-right" id="sumExtraCharges">$0.00</td></tr>
|
||||
<tr><td>Tuition Charges</td><td class="text-right" id="sumTuitionCharges">$0.00</td></tr>
|
||||
<tr><td>Event Fee Charges</td><td class="text-right" id="sumEventFees">$0.00</td></tr>
|
||||
<tr><td>Prior-Year Tuition Carryover</td><td class="text-right" id="sumExtraCharges">$0.00</td></tr>
|
||||
<tr><td>Gross Charges</td><td class="text-right" id="sumGrossCharges">$0.00</td></tr>
|
||||
<tr><td>Total Discounts</td><td class="text-right" id="sumDiscounts">$0.00</td></tr>
|
||||
<tr><td>Total Refunds</td><td class="text-right" id="sumRefunds">$0.00</td></tr>
|
||||
<tr><td>Total Expenses</td><td class="text-right" id="sumExpenses">$0.00</td></tr>
|
||||
<tr><td>Total Reimbursements</td><td class="text-right" id="sumReimb">$0.00</td></tr>
|
||||
<tr><td>Donation to School (Masjid & Donation)</td><td class="text-right" id="sumDonationToSchool">$0.00</td></tr>
|
||||
<tr class="table-success"><td>Net Amount (Earned Income)</td><td class="text-right font-weight-bold" id="sumNet">$0.00</td></tr>
|
||||
<tr><td>Donation to School (included in expenses)</td><td class="text-right" id="sumDonationToSchool">$0.00</td></tr>
|
||||
<tr class="table-success"><td>Net Charges After Discounts/Refunds</td><td class="text-right font-weight-bold" id="sumNet">$0.00</td></tr>
|
||||
<tr class="table-info"><td>Amount Collected (Paid)</td><td class="text-right font-weight-bold" id="sumCollected">$0.00</td></tr>
|
||||
<tr class="table-warning"><td>Amount Unpaid (Outstanding)</td><td class="text-right font-weight-bold" id="sumUnpaid">$0.00</td></tr>
|
||||
<tr><td>Overpayment Credits</td><td class="text-right" id="sumOverpaid">$0.00</td></tr>
|
||||
<tr><td>Gross Outstanding Before Credits</td><td class="text-right" id="sumUnpaid">$0.00</td></tr>
|
||||
<tr class="table-warning"><td>Amount Unpaid (Net of Credits)</td><td class="text-right font-weight-bold" id="sumNetReceivable">$0.00</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<p class="small text-muted mb-3" id="summaryNetFormula"></p>
|
||||
|
||||
<div class="alert alert-light border my-3" id="summaryReconciliationBox">
|
||||
<div class="fw-semibold">Reconciliation</div>
|
||||
<div id="summaryReconciliationText" class="small text-muted"></div>
|
||||
</div>
|
||||
|
||||
<div class="my-4">
|
||||
<h3>Summary Graph</h3>
|
||||
<canvas id="summaryChart" style="max-height:300px;"></canvas>
|
||||
@@ -55,13 +68,13 @@
|
||||
<div class="row g-3">
|
||||
<div class="col-12 col-lg-6">
|
||||
<div class="h-100 p-3 border rounded">
|
||||
<h3 class="h5">Collected vs Outstanding</h3>
|
||||
<h3 class="h5">Collected vs Net Outstanding</h3>
|
||||
<canvas id="collectedChart" style="max-height:320px; width:100%;"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12 col-lg-6">
|
||||
<div class="h-100 p-3 border rounded">
|
||||
<h3 class="h5">Expenses out of Net Amount</h3>
|
||||
<h3 class="h5">Expenses out of Net Charges</h3>
|
||||
<canvas id="netExpenseChart" style="max-height:320px; width:100%;"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
@@ -79,6 +92,10 @@
|
||||
function fmt(n){ return '$' + Number(n||0).toFixed(2); }
|
||||
const initialSummaryData = {
|
||||
schoolYear: <?= json_encode((string)($schoolYear ?? '')) ?>,
|
||||
dateFrom: <?= json_encode((string)($dateFrom ?? '')) ?>,
|
||||
dateTo: <?= json_encode((string)($dateTo ?? '')) ?>,
|
||||
grossCharges: <?= json_encode((float)($grossCharges ?? $totalCharges ?? 0)) ?>,
|
||||
tuitionCharges: <?= json_encode((float)($tuitionCharges ?? 0)) ?>,
|
||||
totalCharges: <?= json_encode((float)($totalCharges ?? 0)) ?>,
|
||||
totalEventFees: <?= json_encode((float)($totalEventFees ?? 0)) ?>,
|
||||
totalExtraCharges: <?= json_encode((float)($totalExtraCharges ?? 0)) ?>,
|
||||
@@ -90,18 +107,47 @@ const initialSummaryData = {
|
||||
totalPaid: <?= json_encode((float)($totalPaid ?? 0)) ?>,
|
||||
amountCollected: <?= json_encode((float)($amountCollected ?? 0)) ?>,
|
||||
totalUnpaid: <?= json_encode((float)($totalUnpaid ?? 0)) ?>,
|
||||
totalOverpaid: <?= json_encode((float)($totalOverpaid ?? 0)) ?>,
|
||||
overpaymentDetails: <?= json_encode($overpaymentDetails ?? []) ?>,
|
||||
netReceivable: <?= json_encode((float)($netReceivable ?? 0)) ?>,
|
||||
netAmount: <?= json_encode((float)($netAmount ?? 0)) ?>
|
||||
};
|
||||
|
||||
function buildSummaryPeriod(d) {
|
||||
const parts = ['Report for School Year: ' + (d.schoolYear || '')];
|
||||
if (d.dateFrom) parts.push('Date From: ' + d.dateFrom);
|
||||
if (d.dateTo) parts.push('Date To: ' + d.dateTo);
|
||||
return parts.join(' | ');
|
||||
}
|
||||
|
||||
function buildReconciliationText(d) {
|
||||
const collected = Number(d.amountCollected || d.totalPaid || 0);
|
||||
const unpaid = Number(d.totalUnpaid || 0);
|
||||
const overpaid = Number(d.totalOverpaid || 0);
|
||||
const net = Number(d.netAmount || 0);
|
||||
return fmt(collected) + ' + ' + fmt(unpaid) + ' - ' + fmt(overpaid) + ' = ' + fmt(net)
|
||||
+ ' (Collected + Gross Outstanding - Overpayment Credits = Net Charges After Discounts/Refunds)';
|
||||
}
|
||||
|
||||
function buildNetFormulaText(d) {
|
||||
const gross = Number(d.grossCharges || d.totalCharges || 0);
|
||||
const discounts = Number(d.totalDiscounts || 0);
|
||||
const refunds = Number(d.totalRefunds || 0);
|
||||
const net = Number(d.netAmount || 0);
|
||||
return 'Net Charges After Discounts/Refunds = Gross Charges - Total Discounts - Total Refunds = '
|
||||
+ fmt(gross) + ' - ' + fmt(discounts) + ' - ' + fmt(refunds) + ' = ' + fmt(net);
|
||||
}
|
||||
|
||||
function applySummaryData(d) {
|
||||
document.getElementById('summaryPeriod').textContent = 'Report for School Year: ' + (d.schoolYear || '');
|
||||
document.getElementById('sumCharges').textContent = fmt(d.totalCharges);
|
||||
document.getElementById('summaryPeriod').textContent = buildSummaryPeriod(d);
|
||||
document.getElementById('sumTuitionCharges').textContent = fmt(d.tuitionCharges || 0);
|
||||
if (document.getElementById('sumEventFees')) {
|
||||
document.getElementById('sumEventFees').textContent = fmt(d.totalEventFees || 0);
|
||||
}
|
||||
if (document.getElementById('sumExtraCharges')) {
|
||||
document.getElementById('sumExtraCharges').textContent = fmt(d.totalExtraCharges || 0);
|
||||
}
|
||||
document.getElementById('sumGrossCharges').textContent = fmt(d.grossCharges || d.totalCharges || 0);
|
||||
document.getElementById('sumDiscounts').textContent = fmt(d.totalDiscounts);
|
||||
document.getElementById('sumRefunds').textContent = fmt(d.totalRefunds);
|
||||
document.getElementById('sumExpenses').textContent = fmt(d.totalExpenses);
|
||||
@@ -111,14 +157,43 @@ function applySummaryData(d) {
|
||||
}
|
||||
document.getElementById('sumNet').textContent = fmt(d.netAmount);
|
||||
document.getElementById('sumCollected').textContent = fmt(d.amountCollected || d.totalPaid || 0);
|
||||
document.getElementById('sumOverpaid').textContent = fmt(d.totalOverpaid || 0);
|
||||
document.getElementById('sumUnpaid').textContent = fmt(d.totalUnpaid);
|
||||
document.getElementById('sumNetReceivable').textContent = fmt(d.netReceivable || 0);
|
||||
document.getElementById('summaryNetFormula').textContent = buildNetFormulaText(d);
|
||||
document.getElementById('summaryReconciliationText').textContent = buildReconciliationText(d);
|
||||
}
|
||||
|
||||
function buildSummaryParams() {
|
||||
const params = new URLSearchParams();
|
||||
const form = document.getElementById('summaryYearFilter');
|
||||
if (form) {
|
||||
new FormData(form).forEach((value, key) => {
|
||||
params.set(key, value);
|
||||
});
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
function updateSummaryActionLinks() {
|
||||
const params = buildSummaryParams().toString();
|
||||
const summaryHref = '<?= base_url('financial-report/downloadSummaryCsv') ?>' + (params ? ('?' + params) : '');
|
||||
const allDetailsHref = '<?= base_url('financial-report/downloadSummaryAllDetailsCsv') ?>' + (params ? ('?' + params) : '');
|
||||
const summaryLink = document.getElementById('downloadSummaryCsvLink');
|
||||
const allDetailsLink = document.getElementById('downloadSummaryAllDetailsCsvLink');
|
||||
if (summaryLink) summaryLink.href = summaryHref;
|
||||
if (allDetailsLink) allDetailsLink.href = allDetailsHref;
|
||||
}
|
||||
|
||||
// Auto-submit school year on change and hydrate via API
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const sel = document.querySelector('#summaryYearFilter select[name="school_year"]');
|
||||
if (sel) sel.addEventListener('change', function(){ loadSummary(); });
|
||||
if (sel) sel.addEventListener('change', function(){
|
||||
updateSummaryActionLinks();
|
||||
loadSummary();
|
||||
});
|
||||
applySummaryData(initialSummaryData);
|
||||
updateSummaryActionLinks();
|
||||
renderCharts(initialSummaryData);
|
||||
loadSummary();
|
||||
});
|
||||
@@ -126,9 +201,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
let __sumSeq = 0;
|
||||
function loadSummary(){
|
||||
const mySeq = ++__sumSeq;
|
||||
const sel = document.querySelector('#summaryYearFilter select[name="school_year"]');
|
||||
const params = new URLSearchParams();
|
||||
if (sel && sel.value) params.append('school_year', sel.value);
|
||||
const params = buildSummaryParams();
|
||||
const baseUrl = '<?= site_url('financial-report/financialReportSummary') ?>';
|
||||
const url = baseUrl + (params.toString() ? ('?' + params.toString() + '&format=json') : '?format=json');
|
||||
fetch(url, { headers: { 'Accept': 'application/json' }})
|
||||
@@ -148,13 +221,39 @@ function renderCharts(d){
|
||||
if (window._summaryChart) { window._summaryChart.destroy(); }
|
||||
if (window._collectedChart) { window._collectedChart.destroy(); }
|
||||
if (window._netExpenseChart) { window._netExpenseChart.destroy(); }
|
||||
const chartColors = {
|
||||
tuition: '#1f77b4',
|
||||
eventFees: '#ff7f0e',
|
||||
carryover: '#2ca02c',
|
||||
grossCharges: '#d62728',
|
||||
discounts: '#9467bd',
|
||||
expenses: '#20c997',
|
||||
netCharges: '#e377c2',
|
||||
collected: '#28a745',
|
||||
overpaymentCredits: '#dc3545',
|
||||
outstanding: '#ffc107',
|
||||
netReceivable: '#f4a261'
|
||||
};
|
||||
const summaryCtx = document.getElementById('summaryChart').getContext('2d');
|
||||
const summaryBarColors = [
|
||||
chartColors.tuition,
|
||||
chartColors.eventFees,
|
||||
chartColors.carryover,
|
||||
chartColors.grossCharges,
|
||||
chartColors.discounts,
|
||||
chartColors.expenses,
|
||||
chartColors.netCharges,
|
||||
chartColors.collected,
|
||||
chartColors.overpaymentCredits,
|
||||
chartColors.outstanding,
|
||||
chartColors.netReceivable
|
||||
];
|
||||
window._summaryChart = new Chart(summaryCtx, {
|
||||
type: 'bar',
|
||||
data: { labels: ['Charges','Event Fees','Paid','Unpaid','Discounts','Refunds','Expenses','Reimbursements','Net'],
|
||||
data: { labels: ['Tuition','Event Fees','Prior-Year Carryover','Gross Charges','Discounts','Expenses','Net Charges','Collected','Overpayment Credits','Outstanding','Net Receivable'],
|
||||
datasets: [{ label:'Amount (USD)', data:[
|
||||
d.totalCharges||0, d.totalEventFees||0, d.totalPaid||0, d.totalUnpaid||0, d.totalDiscounts||0, d.totalRefunds||0, d.totalExpenses||0, d.totalReimbursements||0, d.netAmount||0
|
||||
], backgroundColor: ['#007bff','#6610f2','#28a745','#ffc107','#17a2b8','#ffc107','#dc3545','#6f42c1','#20c997']}] },
|
||||
d.tuitionCharges||0, d.totalEventFees||0, d.totalExtraCharges||0, d.grossCharges||d.totalCharges||0, d.totalDiscounts||0, d.totalExpenses||0, d.netAmount||0, d.amountCollected||d.totalPaid||0, d.totalOverpaid||0, d.totalUnpaid||0, d.netReceivable||0
|
||||
], backgroundColor: summaryBarColors}] },
|
||||
options: { responsive:true, scales:{ y:{ beginAtZero:true }}}
|
||||
});
|
||||
|
||||
@@ -162,10 +261,10 @@ function renderCharts(d){
|
||||
window._collectedChart = new Chart(collectedCtx, {
|
||||
type: 'pie',
|
||||
data: {
|
||||
labels: ['Amount Collected (Paid)', 'Amount Outstanding (Unpaid)'],
|
||||
labels: ['Amount Collected (Paid)', 'Amount Unpaid (Net of Credits)', 'Overpayment Credits'],
|
||||
datasets: [{
|
||||
data: [ d.amountCollected || d.totalPaid || 0, d.totalUnpaid || 0 ],
|
||||
backgroundColor: ['#28a745', '#ffc107'],
|
||||
data: [ d.amountCollected || d.totalPaid || 0, d.netReceivable || 0, d.totalOverpaid || 0 ],
|
||||
backgroundColor: [chartColors.collected, chartColors.outstanding, chartColors.overpaymentCredits],
|
||||
borderWidth: 1
|
||||
}]
|
||||
},
|
||||
@@ -190,7 +289,7 @@ function renderCharts(d){
|
||||
labels: netExpenseLabels,
|
||||
datasets: [{
|
||||
data: netExpenseValues,
|
||||
backgroundColor: ['#20c997', '#dc3545'],
|
||||
backgroundColor: [chartColors.expenses, chartColors.netCharges],
|
||||
borderWidth: 1
|
||||
}]
|
||||
},
|
||||
@@ -202,7 +301,7 @@ function renderCharts(d){
|
||||
callbacks: {
|
||||
label: function(context) {
|
||||
if (context.dataIndex === 0) {
|
||||
return 'Expenses: ' + fmt(totalExpenses) + ' (' + expensePercent + '% of net amount)';
|
||||
return 'Expenses: ' + fmt(totalExpenses) + ' (' + expensePercent + '% of net charges)';
|
||||
}
|
||||
return 'Remaining Net: ' + fmt(remainingNet) + ' (' + remainingPercent + '%)';
|
||||
}
|
||||
|
||||
@@ -219,11 +219,12 @@
|
||||
<tr>
|
||||
<th>Paid Date</th>
|
||||
<th>Paid Amount</th>
|
||||
<th>Balance</th>
|
||||
<th>Invoice Balance</th>
|
||||
<th>Payment Method</th>
|
||||
<th>Check Number</th>
|
||||
<th>Installments</th>
|
||||
<th>Status</th>
|
||||
<th>Payment Status</th>
|
||||
<th>Invoice Status</th>
|
||||
<th>Check/Card File</th>
|
||||
<th>Action</th>
|
||||
</tr>
|
||||
@@ -242,7 +243,7 @@
|
||||
?>
|
||||
<td><?= esc($paidAt) ?></td>
|
||||
<td>$<?= number_format((float)($payment['paid_amount'] ?? 0), 2) ?></td>
|
||||
<td>$<?= number_format((float)($payment['balance'] ?? 0), 2) ?></td>
|
||||
<td>$<?= number_format((float)($payment['invoice_current_balance'] ?? 0), 2) ?></td>
|
||||
<td>
|
||||
<?php if ($method === 'cash'): ?>
|
||||
<span class="badge" style="background-color:#28a745;color:#fff;">Cash</span>
|
||||
@@ -255,8 +256,9 @@
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td><?= !empty($payment['check_number']) ? esc($payment['check_number']) : '-' ?></td>
|
||||
<td><?= esc($payment['number_of_installments'] ?? '') ?></td>
|
||||
<td><?= esc($payment['status'] ?? '') ?></td>
|
||||
<td><?= esc($payment['installment_seq'] ?? $payment['number_of_installments'] ?? '') ?></td>
|
||||
<td><?= esc($payment['payment_status'] ?? '') ?></td>
|
||||
<td><?= esc($payment['invoice_status'] ?? '') ?></td>
|
||||
<td>
|
||||
<?php if (!empty($payment['check_file'])): ?>
|
||||
<a href="#" data-bs-toggle="modal" data-bs-target="#checkModal<?= (int)$payment['id'] ?>">View</a> /
|
||||
|
||||
@@ -19,25 +19,29 @@
|
||||
<th>Date</th>
|
||||
<th>Invoice #</th>
|
||||
<th class="text-end">Paid Amount</th>
|
||||
<th class="text-end">Balance</th>
|
||||
<th class="text-end">Invoice Balance</th>
|
||||
<th>Method</th>
|
||||
<th>Status</th>
|
||||
<th>Payment Status</th>
|
||||
<th>Invoice Status</th>
|
||||
<th>School Year</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if (empty($payments)): ?>
|
||||
<tr>
|
||||
<td colspan="6" class="text-center text-muted py-4">No payment</td>
|
||||
<td colspan="8" class="text-center text-muted py-4">No payment</td>
|
||||
</tr>
|
||||
<?php else: ?>
|
||||
<?php foreach ($payments as $p): ?>
|
||||
<tr>
|
||||
<td><?= esc(!empty($p['payment_date']) ? local_date($p['payment_date'], 'm-d-Y') : '') ?></td>
|
||||
<td><?= esc($p['invoice_id'] ?? '') ?></td>
|
||||
<td><?= esc($p['invoice_number'] ?? ('#' . (int)($p['invoice_id'] ?? 0))) ?></td>
|
||||
<td class="text-end">$<?= number_format((float)($p['paid_amount'] ?? 0), 2) ?></td>
|
||||
<td class="text-end">$<?= number_format((float)($p['balance'] ?? 0), 2) ?></td>
|
||||
<td class="text-end">$<?= number_format((float)($p['invoice_current_balance'] ?? 0), 2) ?></td>
|
||||
<td><?= esc($p['payment_method'] ?? '') ?></td>
|
||||
<td><?= esc($p['status'] ?? '') ?></td>
|
||||
<td><?= esc($p['payment_status'] ?? '') ?></td>
|
||||
<td><?= esc($p['invoice_status'] ?? '') ?></td>
|
||||
<td><?= esc($p['school_year'] ?? '') ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php endif; ?>
|
||||
|
||||
@@ -373,8 +373,94 @@
|
||||
let tempBatchCounter = -1;
|
||||
|
||||
let csrfValue = cfg.csrfHash || '';
|
||||
const csrfCookieName = <?= json_encode(config('Security')->csrfCookieName ?? (config('Security')->cookieName ?? 'csrf_cookie_name')) ?>;
|
||||
let csrfRequestQueue = Promise.resolve();
|
||||
let dragPayload = null;
|
||||
|
||||
function getCookie(name) {
|
||||
const parts = document.cookie.split(';');
|
||||
for (let i = 0; i < parts.length; i += 1) {
|
||||
const part = parts[i].trim();
|
||||
if (part.startsWith(`${name}=`)) {
|
||||
return decodeURIComponent(part.slice(name.length + 1));
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function syncCsrfFromCookie() {
|
||||
if (!csrfCookieName) {
|
||||
return csrfValue;
|
||||
}
|
||||
const cookieValue = getCookie(csrfCookieName);
|
||||
if (cookieValue) {
|
||||
csrfValue = cookieValue;
|
||||
}
|
||||
return csrfValue;
|
||||
}
|
||||
|
||||
function updateCsrfToken(response, data = null) {
|
||||
const headerValue = response?.headers?.get?.('X-CSRF-HASH') || '';
|
||||
if (headerValue) {
|
||||
csrfValue = headerValue;
|
||||
return;
|
||||
}
|
||||
const bodyValue = data && typeof data === 'object' ? (data.csrf_hash || data.csrfHash || '') : '';
|
||||
if (bodyValue) {
|
||||
csrfValue = bodyValue;
|
||||
return;
|
||||
}
|
||||
syncCsrfFromCookie();
|
||||
}
|
||||
|
||||
function withSerializedCsrfRequest(task) {
|
||||
const run = csrfRequestQueue
|
||||
.catch(() => undefined)
|
||||
.then(() => task());
|
||||
csrfRequestQueue = run.then(() => undefined, () => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
async function postJson(url, form, fallbackError) {
|
||||
return withSerializedCsrfRequest(async () => {
|
||||
syncCsrfFromCookie();
|
||||
if (cfg.csrfToken) {
|
||||
form.set(cfg.csrfToken, csrfValue);
|
||||
}
|
||||
|
||||
const headers = { 'X-Requested-With': 'XMLHttpRequest' };
|
||||
if (csrfValue) {
|
||||
headers['X-CSRF-TOKEN'] = csrfValue;
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
body: form,
|
||||
});
|
||||
|
||||
const text = await response.text();
|
||||
let data = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : {};
|
||||
} catch (_) {
|
||||
data = {
|
||||
success: false,
|
||||
error: text || fallbackError || 'Unexpected response',
|
||||
};
|
||||
}
|
||||
|
||||
updateCsrfToken(response, data);
|
||||
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.error || fallbackError || 'Request failed.');
|
||||
}
|
||||
|
||||
return data;
|
||||
});
|
||||
}
|
||||
|
||||
function openReceiptModal(url) {
|
||||
if (!url) {
|
||||
return;
|
||||
@@ -470,23 +556,8 @@
|
||||
}
|
||||
const form = new FormData();
|
||||
form.append('expense_id', itemId);
|
||||
if (cfg.csrfToken) {
|
||||
form.append(cfg.csrfToken, csrfValue);
|
||||
}
|
||||
try {
|
||||
const response = await fetch(cfg.markDonationUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
||||
body: form,
|
||||
});
|
||||
const data = await response.json().catch(() => ({ success: false, error: 'Unexpected response' }));
|
||||
const newHash = response.headers.get('X-CSRF-HASH') || data.csrf_hash;
|
||||
if (newHash) {
|
||||
csrfValue = newHash;
|
||||
}
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.error || 'Unable to mark donation right now.');
|
||||
}
|
||||
await postJson(cfg.markDonationUrl, form, 'Unable to mark donation right now.');
|
||||
removeItemFromUI(itemId);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
@@ -737,23 +808,7 @@
|
||||
} else {
|
||||
form.append('admin_id', '');
|
||||
}
|
||||
if (cfg.csrfToken) {
|
||||
form.append(cfg.csrfToken, csrfValue);
|
||||
}
|
||||
|
||||
fetch(cfg.updateUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
||||
body: form,
|
||||
}).then(async (response) => {
|
||||
const data = await response.json().catch(() => ({ success: false, error: 'Unexpected response' }));
|
||||
const newHash = response.headers.get('X-CSRF-HASH') || data.csrf_hash;
|
||||
if (newHash) {
|
||||
csrfValue = newHash;
|
||||
}
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.error || 'Unable to update batch assignment.');
|
||||
}
|
||||
postJson(cfg.updateUrl, form, 'Unable to update batch assignment.').then((data) => {
|
||||
entry.batch_number = batchId;
|
||||
entry.batchId = batchId;
|
||||
entry.admin_id = (adminId || adminId === 0) ? adminId : null;
|
||||
@@ -791,25 +846,7 @@
|
||||
throw new Error('Batch creation endpoint is not configured.');
|
||||
}
|
||||
const form = new FormData();
|
||||
if (cfg.csrfToken) {
|
||||
form.append(cfg.csrfToken, csrfValue);
|
||||
}
|
||||
|
||||
const response = await fetch(cfg.createBatchUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
||||
body: form,
|
||||
});
|
||||
const data = await response.json().catch(() => ({ success: false, error: 'Unexpected response when creating batch.' }));
|
||||
const newHash = response.headers.get('X-CSRF-HASH') || data.csrf_hash;
|
||||
if (newHash) {
|
||||
csrfValue = newHash;
|
||||
}
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.error || 'Unable to create a new batch right now.');
|
||||
}
|
||||
|
||||
return data;
|
||||
return postJson(cfg.createBatchUrl, form, 'Unable to create a new batch right now.');
|
||||
}
|
||||
|
||||
async function uploadAdminCheckFile(batchId, adminId, input, statusEl, linkEl) {
|
||||
@@ -827,28 +864,13 @@
|
||||
form.append('batch_id', batchId);
|
||||
form.append('admin_id', adminId ?? 0);
|
||||
form.append('check_file', file);
|
||||
if (cfg.csrfToken) {
|
||||
form.append(cfg.csrfToken, csrfValue);
|
||||
}
|
||||
|
||||
input.disabled = true;
|
||||
const previous = statusEl.textContent;
|
||||
statusEl.textContent = 'Uploading...';
|
||||
|
||||
try {
|
||||
const response = await fetch(cfg.checkUploadUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
||||
body: form,
|
||||
});
|
||||
const data = await response.json().catch(() => ({ success: false, error: 'Unexpected response' }));
|
||||
const newHash = response.headers.get('X-CSRF-HASH') || data.csrf_hash;
|
||||
if (newHash) {
|
||||
csrfValue = newHash;
|
||||
}
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.error || 'Unable to upload check file right now.');
|
||||
}
|
||||
const data = await postJson(cfg.checkUploadUrl, form, 'Unable to upload check file right now.');
|
||||
const label = data.original_filename || 'View check';
|
||||
statusEl.textContent = `Uploaded: ${data.original_filename || 'file'}`;
|
||||
if (linkEl && data.url) {
|
||||
@@ -979,34 +1001,19 @@
|
||||
}
|
||||
const form = new FormData();
|
||||
form.append('batch_id', batchId);
|
||||
if (cfg.csrfToken) {
|
||||
form.append(cfg.csrfToken, csrfValue);
|
||||
}
|
||||
if (button) {
|
||||
button.disabled = true;
|
||||
button.textContent = 'Locking...';
|
||||
}
|
||||
try {
|
||||
const response = await fetch(cfg.lockBatchUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
||||
body: form,
|
||||
});
|
||||
const data = await response.json().catch(() => ({ success: false, error: 'Unexpected response' }));
|
||||
const newHash = response.headers.get('X-CSRF-HASH') || data.csrf_hash;
|
||||
if (newHash) {
|
||||
csrfValue = newHash;
|
||||
}
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.error || 'Unable to lock batch at the moment.');
|
||||
}
|
||||
await postJson(cfg.lockBatchUrl, form, 'Unable to lock batch at the moment.');
|
||||
markBatchCardLocked(card);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
alert(err.message || 'Unable to lock the batch. Please try again.');
|
||||
if (button) {
|
||||
button.disabled = false;
|
||||
button.textContent = 'Lock Batch';
|
||||
button.textContent = 'Submit Batch';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
<?= $this->extend('layout/management_layout') ?>
|
||||
<?= $this->section('content') ?>
|
||||
|
||||
<?php
|
||||
$source = $preview['source'] ?? [];
|
||||
$target = $preview['target'] ?? null;
|
||||
$overview = $preview['overview'] ?? [];
|
||||
$finance = $preview['finance'] ?? [];
|
||||
$blockers = $preview['blockers'] ?? [];
|
||||
$warnings = $preview['warnings'] ?? [];
|
||||
$carryForward = $preview['carry_forward'] ?? [];
|
||||
$status = (string) ($source['status'] ?? '');
|
||||
$batchStatus = (string) ($latestBatch['status'] ?? '');
|
||||
$money = static fn ($value): string => '$' . number_format((float) $value, 2);
|
||||
?>
|
||||
|
||||
<?php if (session()->getFlashdata('success')): ?>
|
||||
<div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
|
||||
<?php elseif (session()->getFlashdata('error')): ?>
|
||||
<div class="alert alert-danger"><?= esc(session()->getFlashdata('error')) ?></div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="container-fluid py-3">
|
||||
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
|
||||
<div>
|
||||
<h2 class="mb-1">Closing Preview: <?= esc($source['name'] ?? '') ?></h2>
|
||||
<div class="text-muted">
|
||||
Status: <span class="fw-semibold"><?= esc(ucfirst($status)) ?></span>
|
||||
<?php if ($target): ?>
|
||||
<span class="mx-2">Target: <span class="fw-semibold"><?= esc($target['name'] ?? '') ?></span></span>
|
||||
<?php endif; ?>
|
||||
<span>Generated: <?= esc($preview['generated_at'] ?? '') ?></span>
|
||||
</div>
|
||||
</div>
|
||||
<a class="btn btn-outline-secondary" href="<?= site_url('administrator/school-years') ?>">Back to Management</a>
|
||||
</div>
|
||||
|
||||
<form class="row g-2 align-items-end mb-4" method="get" action="<?= site_url('administrator/school-years/' . (int) ($source['id'] ?? 0) . '/closing/preview') ?>">
|
||||
<div class="col-md-4">
|
||||
<label class="form-label" for="target_school_year_id">Target school year</label>
|
||||
<select class="form-select" id="target_school_year_id" name="target_school_year_id">
|
||||
<option value="">Auto-select next draft year</option>
|
||||
<?php foreach (($schoolYears ?? []) as $year): ?>
|
||||
<?php if ((int) ($year['id'] ?? 0) !== (int) ($source['id'] ?? 0)): ?>
|
||||
<option value="<?= (int) $year['id'] ?>" <?= $target && (int) $target['id'] === (int) $year['id'] ? 'selected' : '' ?>>
|
||||
<?= esc($year['name'] ?? '') ?> (<?= esc($year['status'] ?? '') ?>)
|
||||
</option>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<button class="btn btn-primary" type="submit">Refresh Preview</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-md-3">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<div class="text-muted small">Students</div>
|
||||
<div class="fs-5 fw-semibold"><?= esc((string) ($overview['students'] ?? 0)) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<div class="text-muted small">Families</div>
|
||||
<div class="fs-5 fw-semibold"><?= esc((string) ($overview['families'] ?? 0)) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<div class="text-muted small">Invoices</div>
|
||||
<div class="fs-5 fw-semibold"><?= esc((string) ($overview['invoices'] ?? 0)) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<div class="text-muted small">Outstanding</div>
|
||||
<div class="fs-5 fw-semibold"><?= esc($money($overview['total_outstanding'] ?? 0)) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-lg-6">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<h5>Blocking Issues</h5>
|
||||
<?php if ($blockers === []): ?>
|
||||
<p class="text-muted mb-0">No blocking issues found.</p>
|
||||
<?php else: ?>
|
||||
<ul class="mb-0">
|
||||
<?php foreach ($blockers as $finding): ?>
|
||||
<li><strong><?= esc($finding['title']) ?>:</strong> <?= esc($finding['detail']) ?></li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<h5>Warnings</h5>
|
||||
<?php if ($warnings === []): ?>
|
||||
<p class="text-muted mb-0">No warnings found.</p>
|
||||
<?php else: ?>
|
||||
<ul class="mb-0">
|
||||
<?php foreach ($warnings as $finding): ?>
|
||||
<li><strong><?= esc($finding['title']) ?>:</strong> <?= esc($finding['detail']) ?></li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-lg-5">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<h5>Finance Summary</h5>
|
||||
<dl class="row mb-0">
|
||||
<dt class="col-7">Total invoiced</dt>
|
||||
<dd class="col-5 text-end"><?= esc($money($finance['total_invoiced'] ?? 0)) ?></dd>
|
||||
<dt class="col-7">Total paid</dt>
|
||||
<dd class="col-5 text-end"><?= esc($money($finance['total_paid'] ?? 0)) ?></dd>
|
||||
<dt class="col-7">Positive balances</dt>
|
||||
<dd class="col-5 text-end"><?= esc($money($finance['positive_balance'] ?? 0)) ?></dd>
|
||||
<dt class="col-7">Credits</dt>
|
||||
<dd class="col-5 text-end"><?= esc($money($finance['credit_balance'] ?? 0)) ?></dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-7">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<h5>Closing Progress</h5>
|
||||
<ol class="mb-0">
|
||||
<li>Preview generated</li>
|
||||
<li class="<?= $blockers === [] ? '' : 'text-muted' ?>">Validation <?= $blockers === [] ? 'passed' : 'has blockers' ?></li>
|
||||
<li class="<?= $batchStatus !== '' ? '' : 'text-muted' ?>">Closing batch <?= $batchStatus !== '' ? esc($batchStatus) : 'not created' ?></li>
|
||||
<li class="<?= in_array($batchStatus, ['executed', 'completed'], true) ? '' : 'text-muted' ?>">Carry-forward completed</li>
|
||||
<li class="<?= $status === 'closed' ? '' : 'text-muted' ?>">Year closed</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="border rounded bg-white p-3 mb-4">
|
||||
<h5>Carry-Forward Families</h5>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm align-middle">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Family</th>
|
||||
<th class="text-end">Source Balance</th>
|
||||
<th class="text-end">Credits</th>
|
||||
<th class="text-end">Adjustments</th>
|
||||
<th class="text-end">Net Carry-Forward</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if ($carryForward === []): ?>
|
||||
<tr><td colspan="5" class="text-muted">No carry-forward balances found.</td></tr>
|
||||
<?php endif; ?>
|
||||
<?php foreach ($carryForward as $row): ?>
|
||||
<tr>
|
||||
<td><?= esc($row['family']) ?></td>
|
||||
<td class="text-end"><?= esc($money($row['source_balance'])) ?></td>
|
||||
<td class="text-end"><?= esc($money($row['credit_amount'])) ?></td>
|
||||
<td class="text-end"><?= esc($money($row['adjustment_amount'])) ?></td>
|
||||
<td class="text-end"><?= esc($money($row['carry_forward_amount'])) ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex flex-wrap gap-2 mb-4">
|
||||
<?php if ($status === 'active' && $target && $blockers === []): ?>
|
||||
<form action="<?= site_url('administrator/school-years/' . (int) $source['id'] . '/closing/start') ?>" method="post">
|
||||
<?= csrf_field() ?>
|
||||
<input type="hidden" name="target_school_year_id" value="<?= (int) $target['id'] ?>">
|
||||
<button class="btn btn-warning" type="submit">Begin Closing</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($status === 'closing' && $batchStatus === 'started'): ?>
|
||||
<form action="<?= site_url('administrator/school-years/' . (int) $source['id'] . '/closing/execute') ?>" method="post">
|
||||
<?= csrf_field() ?>
|
||||
<button class="btn btn-primary" type="submit">Execute Carry-Forward</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($status === 'closing' && $batchStatus === 'executed'): ?>
|
||||
<form action="<?= site_url('administrator/school-years/' . (int) $source['id'] . '/closing/complete') ?>" method="post">
|
||||
<?= csrf_field() ?>
|
||||
<button class="btn btn-success" type="submit">Complete Closing</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($status === 'closing' && ! in_array($batchStatus, ['executed', 'completed'], true)): ?>
|
||||
<form action="<?= site_url('administrator/school-years/' . (int) $source['id'] . '/closing/cancel') ?>" method="post">
|
||||
<?= csrf_field() ?>
|
||||
<button class="btn btn-outline-secondary" type="submit">Cancel Closing</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?= $this->endSection() ?>
|
||||
@@ -0,0 +1,336 @@
|
||||
<?= $this->extend('layout/management_layout') ?>
|
||||
<?= $this->section('content') ?>
|
||||
|
||||
<?php
|
||||
$statusClasses = [
|
||||
'draft' => 'bg-info text-dark',
|
||||
'active' => 'bg-success',
|
||||
'closing' => 'bg-warning text-dark',
|
||||
'closed' => 'bg-secondary',
|
||||
'archived' => 'bg-dark',
|
||||
];
|
||||
$formatDate = static fn ($value): string => $value ? esc((string) $value) : 'Not set';
|
||||
?>
|
||||
|
||||
<?php if (session()->getFlashdata('success')): ?>
|
||||
<div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
|
||||
<?php elseif (session()->getFlashdata('error')): ?>
|
||||
<div class="alert alert-danger"><?= esc(session()->getFlashdata('error')) ?></div>
|
||||
<?php endif; ?>
|
||||
|
||||
<div class="container-fluid py-3">
|
||||
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
|
||||
<div>
|
||||
<h2 class="mb-1">School Year Management</h2>
|
||||
<div class="text-muted">
|
||||
Active year:
|
||||
<?php if (! empty($activeYear)): ?>
|
||||
<span class="badge bg-success"><?= esc($activeYear['name']) ?></span>
|
||||
<?php else: ?>
|
||||
<span class="badge bg-danger">None</span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn btn-success" type="button" data-bs-toggle="collapse" data-bs-target="#schoolYearCreateForm">
|
||||
Add School Year
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-md-3">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<div class="text-muted small">Active Year</div>
|
||||
<div class="fs-5 fw-semibold"><?= esc($activeYear['name'] ?? 'None') ?></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<div class="text-muted small">Next Draft</div>
|
||||
<div class="fs-5 fw-semibold"><?= esc($nextDraftYear['name'] ?? 'None') ?></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<div class="text-muted small">Currently Closing</div>
|
||||
<div class="fs-5 fw-semibold"><?= esc($closingYear['name'] ?? 'None') ?></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<div class="border rounded bg-white p-3 h-100">
|
||||
<div class="text-muted small">Archived Years</div>
|
||||
<div class="fs-5 fw-semibold"><?= esc((string) ($archivedCount ?? 0)) ?></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="collapse mb-4" id="schoolYearCreateForm">
|
||||
<div class="border rounded bg-white p-3">
|
||||
<form action="<?= site_url('administrator/school-years/store') ?>" method="post" class="row g-3 align-items-end">
|
||||
<?= csrf_field() ?>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label" for="new_school_year_name">School Year</label>
|
||||
<input class="form-control" id="new_school_year_name" name="name" placeholder="2026-2027" required pattern="\d{4}-\d{4}">
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label" for="new_school_year_starts_on">Starts On</label>
|
||||
<input class="form-control" id="new_school_year_starts_on" name="starts_on" type="date">
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label" for="new_school_year_ends_on">Ends On</label>
|
||||
<input class="form-control" id="new_school_year_ends_on" name="ends_on" type="date">
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label" for="new_registration_starts_on">Registration Starts</label>
|
||||
<input class="form-control" id="new_registration_starts_on" name="registration_starts_on" type="date">
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<label class="form-label" for="new_registration_ends_on">Registration Ends</label>
|
||||
<input class="form-control" id="new_registration_ends_on" name="registration_ends_on" type="date">
|
||||
</div>
|
||||
<div class="col-md-2 d-flex gap-2">
|
||||
<button class="btn btn-primary" type="submit">Save Draft</button>
|
||||
<button class="btn btn-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#schoolYearCreateForm">Cancel</button>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label" for="new_school_year_description">Description</label>
|
||||
<textarea class="form-control" id="new_school_year_description" name="description" rows="2"></textarea>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table id="schoolYearsTable" class="table table-striped table-hover align-middle">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>School Year</th>
|
||||
<th>Dates</th>
|
||||
<th>Status</th>
|
||||
<th>Students</th>
|
||||
<th>Families</th>
|
||||
<th>Financial Balance</th>
|
||||
<th>Last Transition</th>
|
||||
<th>Updated</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach (($schoolYears ?? []) as $year): ?>
|
||||
<?php
|
||||
$id = (int) ($year['id'] ?? 0);
|
||||
$status = (string) ($year['status'] ?? 'draft');
|
||||
$readonly = in_array($status, ['closed', 'archived'], true);
|
||||
$transition = $latestTransitions[$id] ?? null;
|
||||
?>
|
||||
<tr>
|
||||
<td class="fw-semibold"><?= esc($year['name'] ?? '') ?></td>
|
||||
<td>
|
||||
<div><?= $formatDate($year['starts_on'] ?? null) ?></div>
|
||||
<div class="text-muted small"><?= $formatDate($year['ends_on'] ?? null) ?></div>
|
||||
</td>
|
||||
<td>
|
||||
<span class="badge <?= esc($statusClasses[$status] ?? 'bg-secondary') ?>">
|
||||
<?= esc(ucfirst($status)) ?>
|
||||
</span>
|
||||
</td>
|
||||
<td class="text-muted">-</td>
|
||||
<td class="text-muted">-</td>
|
||||
<td class="text-muted">Preview</td>
|
||||
<td>
|
||||
<?php if ($transition): ?>
|
||||
<div><?= esc($transition['action'] ?? '') ?></div>
|
||||
<div class="text-muted small"><?= esc($transition['created_at'] ?? '') ?></div>
|
||||
<?php else: ?>
|
||||
<span class="text-muted">-</span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
<td><?= esc($year['updated_at'] ?? '') ?></td>
|
||||
<td>
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
|
||||
Actions
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end">
|
||||
<?php if (! $readonly && $status !== 'closing'): ?>
|
||||
<li>
|
||||
<button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#editSchoolYearModal<?= $id ?>">
|
||||
Edit metadata
|
||||
</button>
|
||||
</li>
|
||||
<?php endif; ?>
|
||||
<?php if ($status === 'draft'): ?>
|
||||
<li>
|
||||
<button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#activateSchoolYearModal<?= $id ?>">
|
||||
Activate
|
||||
</button>
|
||||
</li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li>
|
||||
<form action="<?= site_url('administrator/school-years/' . $id . '/delete-draft') ?>" method="post" onsubmit="return confirm('Delete this unused draft school year?');">
|
||||
<?= csrf_field() ?>
|
||||
<button class="dropdown-item text-danger" type="submit">Delete draft</button>
|
||||
</form>
|
||||
</li>
|
||||
<?php elseif ($status === 'active'): ?>
|
||||
<li>
|
||||
<a class="dropdown-item" href="<?= site_url('administrator/school-years/' . $id . '/closing/preview') ?>">Preview closing</a>
|
||||
</li>
|
||||
<?php elseif ($status === 'closing'): ?>
|
||||
<li>
|
||||
<a class="dropdown-item" href="<?= site_url('administrator/school-years/' . $id . '/closing/preview') ?>">View closing</a>
|
||||
</li>
|
||||
<li>
|
||||
<form action="<?= site_url('administrator/school-years/' . $id . '/closing/cancel') ?>" method="post" onsubmit="return confirm('Cancel closing for this school year?');">
|
||||
<?= csrf_field() ?>
|
||||
<button class="dropdown-item" type="submit">Cancel closing</button>
|
||||
</form>
|
||||
</li>
|
||||
<?php elseif ($status === 'closed'): ?>
|
||||
<li>
|
||||
<a class="dropdown-item" href="<?= site_url('administrator/school-years/' . $id . '/closing/preview') ?>">View closing report</a>
|
||||
</li>
|
||||
<li>
|
||||
<button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#reopenSchoolYearModal<?= $id ?>">
|
||||
Reopen
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<form action="<?= site_url('administrator/school-years/' . $id . '/archive') ?>" method="post" onsubmit="return confirm('Archive this closed school year?');">
|
||||
<?= csrf_field() ?>
|
||||
<button class="dropdown-item" type="submit">Archive</button>
|
||||
</form>
|
||||
</li>
|
||||
<?php else: ?>
|
||||
<li>
|
||||
<a class="dropdown-item" href="<?= site_url('administrator/school-years/' . $id . '/closing/preview') ?>">View audit trail</a>
|
||||
</li>
|
||||
<?php endif; ?>
|
||||
</ul>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php foreach (($schoolYears ?? []) as $year): ?>
|
||||
<?php
|
||||
$id = (int) ($year['id'] ?? 0);
|
||||
$status = (string) ($year['status'] ?? 'draft');
|
||||
$readonly = in_array($status, ['closed', 'archived', 'closing'], true);
|
||||
?>
|
||||
<?php if (! $readonly): ?>
|
||||
<div class="modal fade" id="editSchoolYearModal<?= $id ?>" tabindex="-1" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<form class="modal-content" action="<?= site_url('administrator/school-years/' . $id . '/update') ?>" method="post">
|
||||
<?= csrf_field() ?>
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Edit School Year Metadata</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="row">
|
||||
<div class="col-md-4 mb-3">
|
||||
<label class="form-label" for="school_year_name_<?= $id ?>">School Year</label>
|
||||
<input class="form-control" id="school_year_name_<?= $id ?>" name="name" value="<?= esc($year['name'] ?? '') ?>" required pattern="\d{4}-\d{4}">
|
||||
</div>
|
||||
<div class="col-md-4 mb-3">
|
||||
<label class="form-label" for="school_year_starts_on_<?= $id ?>">Starts On</label>
|
||||
<input class="form-control" id="school_year_starts_on_<?= $id ?>" name="starts_on" type="date" value="<?= esc($year['starts_on'] ?? '') ?>">
|
||||
</div>
|
||||
<div class="col-md-4 mb-3">
|
||||
<label class="form-label" for="school_year_ends_on_<?= $id ?>">Ends On</label>
|
||||
<input class="form-control" id="school_year_ends_on_<?= $id ?>" name="ends_on" type="date" value="<?= esc($year['ends_on'] ?? '') ?>">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label" for="registration_starts_on_<?= $id ?>">Registration Starts</label>
|
||||
<input class="form-control" id="registration_starts_on_<?= $id ?>" name="registration_starts_on" type="date" value="<?= esc($year['registration_starts_on'] ?? '') ?>">
|
||||
</div>
|
||||
<div class="col-md-6 mb-3">
|
||||
<label class="form-label" for="registration_ends_on_<?= $id ?>">Registration Ends</label>
|
||||
<input class="form-control" id="registration_ends_on_<?= $id ?>" name="registration_ends_on" type="date" value="<?= esc($year['registration_ends_on'] ?? '') ?>">
|
||||
</div>
|
||||
</div>
|
||||
<label class="form-label" for="description_<?= $id ?>">Description</label>
|
||||
<textarea class="form-control" id="description_<?= $id ?>" name="description" rows="3"><?= esc($year['description'] ?? '') ?></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="submit" class="btn btn-primary">Save Changes</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($status === 'draft'): ?>
|
||||
<div class="modal fade" id="activateSchoolYearModal<?= $id ?>" tabindex="-1" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<form class="modal-content" action="<?= site_url('administrator/school-years/' . $id . '/activate') ?>" method="post">
|
||||
<?= csrf_field() ?>
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Activate <?= esc($year['name'] ?? '') ?></h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p class="mb-2">The selected school year will become active.</p>
|
||||
<?php if (! empty($activeYear)): ?>
|
||||
<p class="mb-3">Current active year <strong><?= esc($activeYear['name']) ?></strong> will move to <strong>closing</strong>.</p>
|
||||
<?php endif; ?>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" value="1" name="confirm_activation" id="confirm_activation_<?= $id ?>" required>
|
||||
<label class="form-check-label" for="confirm_activation_<?= $id ?>">
|
||||
I understand activation does not complete closing for the previous year.
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="submit" class="btn btn-success">Activate</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if ($status === 'closed'): ?>
|
||||
<div class="modal fade" id="reopenSchoolYearModal<?= $id ?>" tabindex="-1" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<form class="modal-content" action="<?= site_url('administrator/school-years/' . $id . '/reopen') ?>" method="post">
|
||||
<?= csrf_field() ?>
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Reopen <?= esc($year['name'] ?? '') ?></h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<label class="form-label" for="reopen_reason_<?= $id ?>">Reason</label>
|
||||
<textarea class="form-control" id="reopen_reason_<?= $id ?>" name="reason" rows="3" required></textarea>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
||||
<button type="submit" class="btn btn-warning">Reopen</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
|
||||
<?= $this->endSection() ?>
|
||||
|
||||
<?= $this->section('scripts') ?>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
if (window.jQuery && window.jQuery.fn && window.jQuery.fn.DataTable) {
|
||||
window.jQuery('#schoolYearsTable').DataTable({
|
||||
pageLength: 25,
|
||||
order: [[0, 'desc']]
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<?= $this->endSection() ?>
|
||||
@@ -101,9 +101,10 @@
|
||||
<!-- Tooltip activation script (include once near bottom of page) -->
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
if (!window.bootstrap || !bootstrap.Tooltip) return;
|
||||
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
|
||||
tooltipTriggerList.forEach(function(tooltipTriggerEl) {
|
||||
new bootstrap.Tooltip(tooltipTriggerEl);
|
||||
bootstrap.Tooltip.getOrCreateInstance(tooltipTriggerEl);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,492 @@
|
||||
# Payment Data Repair Plan
|
||||
|
||||
## Scope
|
||||
|
||||
This plan fixes the payment table, invoice/payment display logic, and manual payment write flow.
|
||||
|
||||
Reviewed inputs:
|
||||
|
||||
- `invoices(2).sql`
|
||||
- `payments(1).sql`
|
||||
- `PaymentController(2).php`
|
||||
- `PaymentTransactionController(1).php`
|
||||
|
||||
## Current findings
|
||||
|
||||
| Check | Result |
|
||||
|---|---:|
|
||||
| Invoice rows | 126 |
|
||||
| Payment rows | 321 |
|
||||
| Invoice `paid_amount` vs `SUM(payments.paid_amount)` mismatches | 0 |
|
||||
| Payment rows where `payments.total_amount` differs from linked invoice total | 106 |
|
||||
| Invoices affected by stale `payments.total_amount` | 66 |
|
||||
| Payment rows with negative `payments.balance` | 5 |
|
||||
| Payment rows whose `semester` / `school_year` differs from linked invoice | 26 |
|
||||
| Invoice IDs with no payment rows | 46, 76, 77, 108, 112, 122 |
|
||||
|
||||
Main conclusion: payment rows are not missing. The system is reading and storing payment context inconsistently. The payment table is being treated as both a transaction ledger and a cached invoice snapshot, which is why the UI looks wrong.
|
||||
|
||||
---
|
||||
|
||||
## Priority 1 — Protect production before repair
|
||||
|
||||
- [ ] Take a database backup.
|
||||
- [ ] Export `invoices`, `payments`, `discount_usages`, `refunds`, `balance_transfers`, and any `payment_transactions` table.
|
||||
- [ ] Run all reconciliation SQL in read-only mode first.
|
||||
- [ ] Apply data repair only after confirming the result count of each query.
|
||||
|
||||
Recommended backup command:
|
||||
|
||||
```bash
|
||||
mysqldump -u <user> -p <database> invoices payments discount_usages refunds balance_transfers payment_transactions > payment_repair_backup.sql
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Priority 2 — Add missing schema support
|
||||
|
||||
The PHP controller writes `installment_seq`, but the uploaded `payments` schema only has `number_of_installments`.
|
||||
|
||||
Add a dedicated installment sequence column:
|
||||
|
||||
```sql
|
||||
ALTER TABLE payments
|
||||
ADD COLUMN installment_seq INT NULL AFTER number_of_installments;
|
||||
|
||||
UPDATE payments
|
||||
SET installment_seq = number_of_installments
|
||||
WHERE installment_seq IS NULL;
|
||||
```
|
||||
|
||||
Change `payment_date` from `DATE` to `DATETIME` so multiple same-day payments can be sorted correctly:
|
||||
|
||||
```sql
|
||||
ALTER TABLE payments
|
||||
MODIFY payment_date DATETIME NOT NULL;
|
||||
```
|
||||
|
||||
Add indexes:
|
||||
|
||||
```sql
|
||||
CREATE INDEX idx_payments_invoice_id ON payments(invoice_id);
|
||||
CREATE INDEX idx_payments_parent_year ON payments(parent_id, school_year, semester);
|
||||
CREATE UNIQUE INDEX uq_payments_transaction_id ON payments(transaction_id);
|
||||
CREATE INDEX idx_invoices_parent_year ON invoices(parent_id, school_year, semester);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Priority 3 — Repair existing payment school year and semester
|
||||
|
||||
Payments should inherit their term from the linked invoice. The current data has payments marked `Spring` while their invoice is `Fall`.
|
||||
|
||||
Preview first:
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
p.id AS payment_id,
|
||||
p.invoice_id,
|
||||
p.parent_id,
|
||||
p.school_year AS payment_school_year,
|
||||
p.semester AS payment_semester,
|
||||
i.school_year AS invoice_school_year,
|
||||
i.semester AS invoice_semester
|
||||
FROM payments p
|
||||
JOIN invoices i ON i.id = p.invoice_id
|
||||
WHERE p.school_year <> i.school_year
|
||||
OR p.semester <> i.semester
|
||||
ORDER BY p.id;
|
||||
```
|
||||
|
||||
Repair:
|
||||
|
||||
```sql
|
||||
UPDATE payments p
|
||||
JOIN invoices i ON i.id = p.invoice_id
|
||||
SET
|
||||
p.school_year = i.school_year,
|
||||
p.semester = i.semester
|
||||
WHERE
|
||||
p.school_year <> i.school_year
|
||||
OR p.semester <> i.semester;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Priority 4 — Stop trusting stale copied fields
|
||||
|
||||
Do not use these fields as authoritative in the UI:
|
||||
|
||||
- `payments.total_amount`
|
||||
- `payments.balance`
|
||||
- `payments.status` as invoice status
|
||||
|
||||
Use:
|
||||
|
||||
- `payments.paid_amount` as the actual transaction amount.
|
||||
- `invoices.total_amount` as the invoice total.
|
||||
- `InvoiceLedgerService` for current invoice balance.
|
||||
- Invoice status from recalculation, not from the latest payment row.
|
||||
|
||||
The payment history table should display:
|
||||
|
||||
```text
|
||||
invoice_number
|
||||
payment_date
|
||||
paid_amount
|
||||
payment_method
|
||||
check_number
|
||||
transaction_id
|
||||
installment_seq
|
||||
balance_after_payment
|
||||
invoice_total
|
||||
invoice_current_balance
|
||||
invoice_status
|
||||
school_year
|
||||
semester
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Priority 5 — Fix `manualPayUpdate()` term assignment
|
||||
|
||||
Current bug: the controller locks the invoice and reads the invoice school year, but then passes `$this->schoolYear` and `$this->semester` into `processPayment()`. That stores payment rows under the active config term instead of the invoice term.
|
||||
|
||||
Change the invoice lock query:
|
||||
|
||||
```php
|
||||
$row = $this->db->query(
|
||||
'SELECT id, parent_id, total_amount, school_year, semester FROM invoices WHERE id = ? FOR UPDATE',
|
||||
[$invoiceId]
|
||||
)->getRowArray();
|
||||
|
||||
$parentId = (int) ($row['parent_id'] ?? 0);
|
||||
$invYear = (string) ($row['school_year'] ?? $this->schoolYear);
|
||||
$invSemester = (string) ($row['semester'] ?? $this->semester);
|
||||
```
|
||||
|
||||
Then pass the invoice term into `processPayment()`:
|
||||
|
||||
```php
|
||||
$ok = $this->processPayment(
|
||||
$invoiceId,
|
||||
$amount,
|
||||
$paymentMethod,
|
||||
$checkFile,
|
||||
$transactionId,
|
||||
$paymentDate,
|
||||
$invYear,
|
||||
$invSemester,
|
||||
$checkNumber,
|
||||
$installmentSeq,
|
||||
(array) $this->invoiceModel->find($invoiceId),
|
||||
$currentBalance
|
||||
);
|
||||
```
|
||||
|
||||
Do not use the current configuration term when recording a payment for an existing invoice. The invoice owns the term.
|
||||
|
||||
---
|
||||
|
||||
## Priority 6 — Replace weak parent payment queries
|
||||
|
||||
Current parent payment lookup is too broad and does not include enough invoice context.
|
||||
|
||||
Replace simple payment-only queries with invoice-joined queries.
|
||||
|
||||
Example:
|
||||
|
||||
```php
|
||||
$selectedYear = $this->request->getGet('school_year') ?? $this->schoolYear;
|
||||
$selectedSemester = $this->request->getGet('semester') ?? null;
|
||||
|
||||
$paymentsQuery = $this->paymentModel
|
||||
->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',
|
||||
'payments.balance AS balance_after_payment',
|
||||
'payments.status AS payment_status',
|
||||
'invoices.total_amount AS invoice_total',
|
||||
'invoices.balance AS invoice_current_balance',
|
||||
'invoices.status AS invoice_status',
|
||||
'invoices.school_year',
|
||||
'invoices.semester',
|
||||
])
|
||||
->join('invoices', 'invoices.id = payments.invoice_id', 'inner')
|
||||
->where('payments.parent_id', $parentId)
|
||||
->where('invoices.school_year', $selectedYear);
|
||||
|
||||
if ($selectedSemester !== null && $selectedSemester !== '') {
|
||||
$paymentsQuery->where('invoices.semester', $selectedSemester);
|
||||
}
|
||||
|
||||
$payments = $paymentsQuery
|
||||
->orderBy('payments.payment_date', 'DESC')
|
||||
->orderBy('payments.id', 'DESC')
|
||||
->paginate(10);
|
||||
```
|
||||
|
||||
Apply this to:
|
||||
|
||||
- `getByParent()`
|
||||
- `manualPaySearch()`
|
||||
- Any dashboard or parent profile payment history endpoint
|
||||
- Any admin finance page reading payment history
|
||||
|
||||
---
|
||||
|
||||
## Priority 7 — Normalize payment status
|
||||
|
||||
Payment status and invoice status must not mean the same thing.
|
||||
|
||||
Payment statuses should be transaction-level:
|
||||
|
||||
```text
|
||||
Recorded
|
||||
Voided
|
||||
Refunded
|
||||
Failed
|
||||
Reversed
|
||||
Chargeback
|
||||
```
|
||||
|
||||
Invoice statuses should be computed:
|
||||
|
||||
```text
|
||||
Unpaid
|
||||
Partially Paid
|
||||
Paid
|
||||
Overpaid
|
||||
Cancelled
|
||||
```
|
||||
|
||||
After the UI stops depending on `payments.status` as invoice status, normalize existing successful payment rows:
|
||||
|
||||
```sql
|
||||
UPDATE payments
|
||||
SET status = 'Recorded'
|
||||
WHERE LOWER(status) IN ('paid', 'partially paid', 'payment recorded');
|
||||
```
|
||||
|
||||
Update `FinancialStatus` to include transaction statuses separately from invoice statuses.
|
||||
|
||||
---
|
||||
|
||||
## Priority 8 — Decide what to do with `payment_transactions`
|
||||
|
||||
`PaymentTransactionController` writes to a separate transaction model, but manual payments are recorded directly into `payments`.
|
||||
|
||||
Pick one architecture:
|
||||
|
||||
### Preferred
|
||||
|
||||
Use `payments` as the single payment transaction ledger.
|
||||
|
||||
Then:
|
||||
|
||||
- [ ] Retire payment transaction pages/routes if unused.
|
||||
- [ ] Do not build UI reports from `payment_transactions`.
|
||||
- [ ] Keep gateway attempts in a separate `payment_attempts` or `online_payment_transactions` table only if needed.
|
||||
|
||||
### Alternative
|
||||
|
||||
If `payment_transactions` must stay:
|
||||
|
||||
- [ ] Create a transaction row every time a payment row is inserted.
|
||||
- [ ] Do it inside the same DB transaction.
|
||||
- [ ] Never show `payment_transactions` without joining back to `payments`.
|
||||
|
||||
Preferred option is cleaner. Two ledgers become two lies unless aggressively synchronized.
|
||||
|
||||
---
|
||||
|
||||
## Priority 9 — Recalculate invoice ledger
|
||||
|
||||
After schema and controller fixes, recalculate every invoice through `InvoiceLedgerService`.
|
||||
|
||||
Required behavior:
|
||||
|
||||
- [ ] Sum successful payments from `payments`.
|
||||
- [ ] Subtract discounts from `discount_usages`.
|
||||
- [ ] Apply refunds/credits consistently.
|
||||
- [ ] Include additional/event charges if they belong in invoice total.
|
||||
- [ ] Update cached `invoices.paid_amount`, `invoices.balance`, and `invoices.status`.
|
||||
- [ ] Never calculate invoice balance directly inside controllers.
|
||||
|
||||
Suggested maintenance command:
|
||||
|
||||
```php
|
||||
foreach ($invoiceModel->findAll() as $invoice) {
|
||||
$invoiceLedgerService->recalculateInvoice((int) $invoice['id']);
|
||||
}
|
||||
```
|
||||
|
||||
Run this from a CLI command, not from a browser request.
|
||||
|
||||
---
|
||||
|
||||
## Priority 10 — Reconciliation SQL
|
||||
|
||||
Run these checks after repair.
|
||||
|
||||
### Stale payment totals
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
p.id AS payment_id,
|
||||
p.invoice_id,
|
||||
p.parent_id,
|
||||
p.total_amount AS payment_total_amount,
|
||||
i.total_amount AS invoice_total_amount,
|
||||
p.paid_amount,
|
||||
p.balance,
|
||||
p.payment_date
|
||||
FROM payments p
|
||||
JOIN invoices i ON i.id = p.invoice_id
|
||||
WHERE p.total_amount <> i.total_amount
|
||||
ORDER BY p.invoice_id, p.id;
|
||||
```
|
||||
|
||||
Expected after UI fix: rows may still exist historically, but the UI must not rely on `payments.total_amount`.
|
||||
|
||||
### Term mismatch
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
p.id AS payment_id,
|
||||
p.invoice_id,
|
||||
p.parent_id,
|
||||
p.school_year AS payment_school_year,
|
||||
p.semester AS payment_semester,
|
||||
i.school_year AS invoice_school_year,
|
||||
i.semester AS invoice_semester
|
||||
FROM payments p
|
||||
JOIN invoices i ON i.id = p.invoice_id
|
||||
WHERE p.school_year <> i.school_year
|
||||
OR p.semester <> i.semester
|
||||
ORDER BY p.id;
|
||||
```
|
||||
|
||||
Expected: zero rows.
|
||||
|
||||
### Negative payment balance snapshots
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
id,
|
||||
parent_id,
|
||||
invoice_id,
|
||||
total_amount,
|
||||
paid_amount,
|
||||
balance,
|
||||
status,
|
||||
payment_date
|
||||
FROM payments
|
||||
WHERE balance < 0
|
||||
ORDER BY invoice_id, id;
|
||||
```
|
||||
|
||||
Expected: zero rows after balance snapshot repair, or ignored if `payments.balance` is deprecated.
|
||||
|
||||
### Invoices with no payment rows
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
i.id,
|
||||
i.parent_id,
|
||||
i.invoice_number,
|
||||
i.total_amount,
|
||||
i.paid_amount,
|
||||
i.balance,
|
||||
i.has_discount,
|
||||
i.status
|
||||
FROM invoices i
|
||||
LEFT JOIN payments p ON p.invoice_id = i.id
|
||||
WHERE p.id IS NULL
|
||||
ORDER BY i.id;
|
||||
```
|
||||
|
||||
Expected: only invoices fully covered by discounts, credits, cancellations, or legitimate zero-payment states.
|
||||
|
||||
### Invoice paid amount consistency
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
i.id AS invoice_id,
|
||||
i.parent_id,
|
||||
i.invoice_number,
|
||||
i.paid_amount AS invoice_paid_amount,
|
||||
COALESCE(SUM(p.paid_amount), 0) AS payment_sum
|
||||
FROM invoices i
|
||||
LEFT JOIN payments p ON p.invoice_id = i.id
|
||||
GROUP BY i.id, i.parent_id, i.invoice_number, i.paid_amount
|
||||
HAVING ROUND(i.paid_amount, 2) <> ROUND(payment_sum, 2)
|
||||
ORDER BY i.id;
|
||||
```
|
||||
|
||||
Expected: zero rows, unless invoice paid amount intentionally includes imported legacy payments that are not in `payments`.
|
||||
|
||||
---
|
||||
|
||||
## Priority 11 — Tests to add
|
||||
|
||||
### Unit tests
|
||||
|
||||
- [ ] Payment creation uses invoice `school_year` and `semester`, not config term.
|
||||
- [ ] Payment amount cannot exceed current ledger balance.
|
||||
- [ ] Card payment must equal full current balance.
|
||||
- [ ] Editing a payment recalculates invoice balance.
|
||||
- [ ] `installment_seq` increments only successful payments.
|
||||
- [ ] Voided/refunded/failed payments are excluded from balance.
|
||||
- [ ] `payments.total_amount` is never used as current invoice total in DTOs.
|
||||
|
||||
### Integration tests
|
||||
|
||||
- [ ] Parent payment history returns payments joined to invoice number.
|
||||
- [ ] Parent payment history filters by invoice school year.
|
||||
- [ ] Parent payment history filters by invoice semester.
|
||||
- [ ] Admin finance table shows transaction amount and current invoice balance correctly.
|
||||
- [ ] Manual payment insert, invoice recalculation, and notification event are atomic.
|
||||
|
||||
### Data repair tests
|
||||
|
||||
- [ ] Term mismatch query returns zero rows after repair.
|
||||
- [ ] Negative payment balance query returns zero rows or deprecated field is hidden.
|
||||
- [ ] Invoice paid amount consistency query returns zero rows.
|
||||
- [ ] Invoices with no payments are manually classified as discount-only, cancelled, imported, or broken.
|
||||
|
||||
---
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
The fix is complete only when:
|
||||
|
||||
- [ ] Existing payments are visible in parent and admin payment history.
|
||||
- [ ] Payment history shows transaction amount, not stale invoice total.
|
||||
- [ ] Payment rows inherit school year and semester from invoice.
|
||||
- [ ] No payment row has mismatched invoice term.
|
||||
- [ ] No new payment insert depends on global config term for existing invoices.
|
||||
- [ ] `installment_seq` exists and is populated.
|
||||
- [ ] Invoice balances are recalculated by `InvoiceLedgerService`.
|
||||
- [ ] `payment_transactions` is either retired or explicitly separated as gateway-attempt history.
|
||||
- [ ] Reconciliation SQL has been run and saved as evidence.
|
||||
|
||||
---
|
||||
|
||||
## Do not do this
|
||||
|
||||
- Do not manually edit invoice balances row by row.
|
||||
- Do not use `payments.total_amount` as invoice total.
|
||||
- Do not use `payments.status` as invoice status.
|
||||
- Do not filter payment history only by `payments.school_year` if invoice term exists.
|
||||
- Do not keep two independent payment ledgers unless one is clearly marked as gateway attempts.
|
||||
- Do not trust the latest payment row balance as the current invoice balance.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,68 @@
|
||||
# School Year and Semester Schema Audit
|
||||
|
||||
Source: `scool_view2.sql`
|
||||
Tables found: 73
|
||||
|
||||
## Result
|
||||
|
||||
The schema is not fully fixed.
|
||||
|
||||
## Required financial tables
|
||||
|
||||
Confirmed with `school_year`:
|
||||
- payment_notification_logs
|
||||
- payment_transactions
|
||||
- reimbursement_batch_items
|
||||
|
||||
Absent from this dump and therefore not verifiable:
|
||||
- discount_usages
|
||||
- event_charges
|
||||
- invoice_event
|
||||
- payment_error
|
||||
|
||||
## School-year defects
|
||||
|
||||
- `archived_paypal_transactions.school_year` is `VARCHAR(20)` instead of `VARCHAR(9)`.
|
||||
- Tables with `school_year` but no direct school-year index:
|
||||
- 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
|
||||
|
||||
## Tables where `semester` should be removed
|
||||
|
||||
- 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
|
||||
|
||||
## Tables requiring business-rule confirmation before removing `semester`
|
||||
|
||||
- archived_paypal_transactions
|
||||
- discount_vouchers
|
||||
- payment_transactions
|
||||
- reimbursement_batch_items
|
||||
- scan_log
|
||||
|
||||
## Notes
|
||||
|
||||
`semester` should remain on semester-owned academic and operational records such as exams, quizzes, grades, class sections, attendance, semester reports, and semester-specific charges or payments.
|
||||
|
||||
Child tables should not duplicate `semester` when it can be obtained reliably through their parent record, unless immutable historical snapshots are an explicit requirement.
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
|
||||
$targets = [
|
||||
'app/Models/UserModel.php',
|
||||
'app/Models/RoleModel.php',
|
||||
'app/Models/PermissionModel.php',
|
||||
'app/Models/RolePermissionModel.php',
|
||||
'app/Models/UserRoleModel.php',
|
||||
'app/Models/SettingsModel.php',
|
||||
'app/Models/ConfigurationModel.php',
|
||||
'app/Models/ParentModel.php',
|
||||
'app/Models/TeacherModel.php',
|
||||
'app/Models/StaffModel.php',
|
||||
];
|
||||
|
||||
$patterns = [
|
||||
'/->where\(\s*[\'"][^\'"]*school_year[\'"]/',
|
||||
'/\b(users|roles|permissions|role_permissions|user_roles|configuration|settings|parents|teachers|staff)\.school_year\b/i',
|
||||
];
|
||||
|
||||
$errors = [];
|
||||
|
||||
foreach ($targets as $relativePath) {
|
||||
$path = $root . DIRECTORY_SEPARATOR . $relativePath;
|
||||
|
||||
if (! is_file($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$lines = file($path, FILE_IGNORE_NEW_LINES);
|
||||
|
||||
foreach ($lines as $index => $line) {
|
||||
foreach ($patterns as $pattern) {
|
||||
if (preg_match($pattern, $line) === 1) {
|
||||
$errors[] = sprintf(
|
||||
'%s:%d: suspicious school-year filter on a global/identity model: %s',
|
||||
$relativePath,
|
||||
$index + 1,
|
||||
trim($line)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($errors !== []) {
|
||||
fwrite(STDERR, implode(PHP_EOL, $errors) . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
echo 'No suspicious global/identity school-year filters found.' . PHP_EOL;
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"advisories": {
|
||||
"phpoffice/math": [
|
||||
{
|
||||
"advisoryId": "PKSA-jw72-bn8m-h7rc",
|
||||
"packageName": "phpoffice/math",
|
||||
"affectedVersions": "<=0.2.0",
|
||||
"title": "PHPOffice Math allows XXE when processing an XML file in the MathML format ",
|
||||
"cve": "CVE-2025-48882",
|
||||
"link": "https://github.com/advisories/GHSA-42hm-pq2f-3r7m",
|
||||
"reportedAt": "2025-05-29T17:27:39+00:00",
|
||||
"sources": [
|
||||
{
|
||||
"name": "GitHub",
|
||||
"remoteId": "GHSA-42hm-pq2f-3r7m"
|
||||
}
|
||||
],
|
||||
"severity": "high"
|
||||
}
|
||||
],
|
||||
"phpunit/phpunit": [
|
||||
{
|
||||
"advisoryId": "PKSA-z3gr-8qht-p93v",
|
||||
"packageName": "phpunit/phpunit",
|
||||
"affectedVersions": ">=0,<8.5.52|>=9.0.0,<9.6.33|>=10.0.0,<10.5.62|>=11.0.0,<11.5.50|>=12.0.0,<12.5.8",
|
||||
"title": "Unsafe Deserialization in PHPT Code Coverage Handling",
|
||||
"cve": "CVE-2026-24765",
|
||||
"link": "https://github.com/sebastianbergmann/phpunit/security/advisories/GHSA-vvj3-c3rp-c85p",
|
||||
"reportedAt": "2026-01-27T05:21:14+00:00",
|
||||
"sources": [
|
||||
{
|
||||
"name": "GitHub",
|
||||
"remoteId": "GHSA-vvj3-c3rp-c85p"
|
||||
},
|
||||
{
|
||||
"name": "FriendsOfPHP/security-advisories",
|
||||
"remoteId": "phpunit/phpunit/CVE-2026-24765.yaml"
|
||||
}
|
||||
],
|
||||
"severity": "high"
|
||||
}
|
||||
]
|
||||
},
|
||||
"abandoned": {
|
||||
"paypal/rest-api-sdk-php": "paypal/paypal-server-sdk"
|
||||
},
|
||||
"filter": []
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user