Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 76ec8d5728 | |||
| 618296f0c1 | |||
| b9572a7698 | |||
| c7f67da9bf | |||
| ed95286050 | |||
| ec9fca8c45 | |||
| ed11cccecc |
@@ -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
|
||||||
+7
-10
@@ -743,11 +743,6 @@ $routes->get('payments/getByParent/(:num)', 'View\PaymentController::getByParent
|
|||||||
$routes->get('payments/create', 'View\PaymentController::create');
|
$routes->get('payments/create', 'View\PaymentController::create');
|
||||||
$routes->post('payments/updateBalance/(:num)', 'View\PaymentController::updateBalance/$1');
|
$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 for payment pages
|
||||||
$routes->get('payments/view/(:num)', 'View\PaymentController::viewPayment/$1');
|
$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']);
|
$routes->get('payment/get_enrolled_students/(:num)', 'View\PaymentController::getEnrolledStudents/$1', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||||
@@ -1074,12 +1069,14 @@ $routes->match(['get', 'post'], 'whatsapp/update-membership', 'View\WhatsappCont
|
|||||||
|
|
||||||
|
|
||||||
//Attendance
|
//Attendance
|
||||||
$routes->get('admin/teacher-attendance', 'View\AttendanceController::index', ['filter' => 'auth:admin']);
|
$staffAttendanceAccess = 'auth:admin|administrator|administrative staff|principal|vice principal';
|
||||||
$routes->post('admin/teacher-attendance/save', 'View\AttendanceController::save', ['filter' => 'auth:admin']);
|
|
||||||
|
$routes->get('admin/teacher-attendance', 'View\AttendanceController::index', ['filter' => $staffAttendanceAccess]);
|
||||||
|
$routes->post('admin/teacher-attendance/save', 'View\AttendanceController::save', ['filter' => $staffAttendanceAccess]);
|
||||||
// NEW: monthly overview (all sections)
|
// NEW: monthly overview (all sections)
|
||||||
$routes->get('admin/teacher-attendance/month', 'View\AttendanceController::month', ['filter' => 'auth:admin']);
|
$routes->get('admin/teacher-attendance/month', 'View\AttendanceController::month', ['filter' => $staffAttendanceAccess]);
|
||||||
$routes->get('admin/teacher-attendance/month.csv', 'View\AttendanceController::monthCsv', ['filter' => 'auth:admin']);
|
$routes->get('admin/teacher-attendance/month.csv', 'View\AttendanceController::monthCsv', ['filter' => $staffAttendanceAccess]);
|
||||||
$routes->get('api/admin/teacher-attendance/month', 'View\AttendanceController::monthData', ['filter' => 'auth:admin']);
|
$routes->get('api/admin/teacher-attendance/month', 'View\AttendanceController::monthData', ['filter' => $staffAttendanceAccess]);
|
||||||
|
|
||||||
|
|
||||||
$routes->post('attendance/record', 'View\AttendanceTrackingController::record');
|
$routes->post('attendance/record', 'View\AttendanceTrackingController::record');
|
||||||
|
|||||||
@@ -150,10 +150,12 @@ class FamilyAdminController extends BaseController
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Recent payments (limit 10)
|
// Recent payments (limit 10)
|
||||||
$payRows = $db->table('payments')
|
$payRows = $db->table('payments p')
|
||||||
->select('id, parent_id, invoice_id, paid_amount, balance, payment_method, payment_date, status')
|
->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')
|
||||||
->whereIn('parent_id', $parentIds)
|
->join('invoices i', 'i.id = p.invoice_id', 'inner')
|
||||||
->orderBy('payment_date', 'DESC')
|
->whereIn('p.parent_id', $parentIds)
|
||||||
|
->orderBy('p.payment_date', 'DESC')
|
||||||
|
->orderBy('p.id', 'DESC')
|
||||||
->limit(10)
|
->limit(10)
|
||||||
->get()->getResultArray();
|
->get()->getResultArray();
|
||||||
$fam['payments'] = $payRows;
|
$fam['payments'] = $payRows;
|
||||||
@@ -395,10 +397,12 @@ class FamilyAdminController extends BaseController
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Payments
|
// Payments
|
||||||
$payRows = $db->table('payments')
|
$payRows = $db->table('payments p')
|
||||||
->select('id, parent_id, invoice_id, paid_amount, balance, payment_method, payment_date, status')
|
->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')
|
||||||
->whereIn('parent_id', $parentIds)
|
->join('invoices i', 'i.id = p.invoice_id', 'inner')
|
||||||
->orderBy('payment_date', 'DESC')
|
->whereIn('p.parent_id', $parentIds)
|
||||||
|
->orderBy('p.payment_date', 'DESC')
|
||||||
|
->orderBy('p.id', 'DESC')
|
||||||
->limit(10)
|
->limit(10)
|
||||||
->get()->getResultArray();
|
->get()->getResultArray();
|
||||||
$family['payments'] = $payRows;
|
$family['payments'] = $payRows;
|
||||||
|
|||||||
@@ -658,10 +658,10 @@ public function financialReport()
|
|||||||
}, $discountDetailsBuilder->orderBy('du.id', 'ASC')->get()->getResultArray());
|
}, $discountDetailsBuilder->orderBy('du.id', 'ASC')->get()->getResultArray());
|
||||||
|
|
||||||
$paymentDetailsBuilder = $db->table('payments p')
|
$paymentDetailsBuilder = $db->table('payments p')
|
||||||
->select("p.id, p.invoice_id, p.parent_id, p.paid_amount, p.payment_method, p.payment_date, p.status, p.transaction_id, p.check_number, i.invoice_number, CONCAT(COALESCE(u.firstname, ''), ' ', COALESCE(u.lastname, '')) AS parent_name")
|
->select("p.id, p.invoice_id, p.parent_id, p.paid_amount, p.payment_method, p.payment_date, p.status AS payment_status, p.transaction_id, p.check_number, i.invoice_number, i.balance AS invoice_current_balance, i.status AS invoice_status, i.school_year, CONCAT(COALESCE(u.firstname, ''), ' ', COALESCE(u.lastname, '')) AS parent_name")
|
||||||
->join('invoices i', 'i.id = p.invoice_id', 'left')
|
->join('invoices i', 'i.id = p.invoice_id', 'inner')
|
||||||
->join('users u', 'u.id = p.parent_id', 'left')
|
->join('users u', 'u.id = p.parent_id', 'left')
|
||||||
->where('p.school_year', $schoolYear)
|
->where('i.school_year', $schoolYear)
|
||||||
->groupStart()
|
->groupStart()
|
||||||
->whereNotIn('p.status', $paymentExclude)
|
->whereNotIn('p.status', $paymentExclude)
|
||||||
->orWhere('p.status IS NULL', null, false)
|
->orWhere('p.status IS NULL', null, false)
|
||||||
@@ -677,9 +677,12 @@ public function financialReport()
|
|||||||
'Parent' => trim((string)($row['parent_name'] ?? '')),
|
'Parent' => trim((string)($row['parent_name'] ?? '')),
|
||||||
'Invoice #' => (string)($row['invoice_number'] ?? ''),
|
'Invoice #' => (string)($row['invoice_number'] ?? ''),
|
||||||
'Paid Amount' => (float)($row['paid_amount'] ?? 0),
|
'Paid Amount' => (float)($row['paid_amount'] ?? 0),
|
||||||
|
'Invoice Balance' => (float)($row['invoice_current_balance'] ?? 0),
|
||||||
'Payment Method' => (string)($row['payment_method'] ?? ''),
|
'Payment Method' => (string)($row['payment_method'] ?? ''),
|
||||||
'Payment Date' => (string)($row['payment_date'] ?? ''),
|
'Payment Date' => (string)($row['payment_date'] ?? ''),
|
||||||
'Status' => (string)($row['status'] ?? ''),
|
'Payment Status' => (string)($row['payment_status'] ?? ''),
|
||||||
|
'Invoice Status' => (string)($row['invoice_status'] ?? ''),
|
||||||
|
'School Year' => (string)($row['school_year'] ?? ''),
|
||||||
'Transaction ID' => (string)($row['transaction_id'] ?? ''),
|
'Transaction ID' => (string)($row['transaction_id'] ?? ''),
|
||||||
'Check Number' => (string)($row['check_number'] ?? ''),
|
'Check Number' => (string)($row['check_number'] ?? ''),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -85,7 +85,6 @@ class PaymentController extends ResourceController
|
|||||||
'payment_date' => $this->request->getPost('payment_date'),
|
'payment_date' => $this->request->getPost('payment_date'),
|
||||||
'payment_type' => $this->request->getPost('payment_type'),
|
'payment_type' => $this->request->getPost('payment_type'),
|
||||||
'status' => 'Pending',
|
'status' => 'Pending',
|
||||||
'semester' => $this->request->getPost('semester'),
|
|
||||||
'school_year' => $this->request->getPost('school_year'),
|
'school_year' => $this->request->getPost('school_year'),
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -99,7 +98,8 @@ class PaymentController extends ResourceController
|
|||||||
// API: Get payments by parent ID
|
// API: Get payments by parent ID
|
||||||
public function getByParentAPI($parentId)
|
public function getByParentAPI($parentId)
|
||||||
{
|
{
|
||||||
$payments = $this->paymentModel->getPaymentsByParentId($parentId);
|
$selectedYear = $this->getSelectedPaymentHistoryYear();
|
||||||
|
$payments = $this->paymentModel->getPaymentsByParentId((int) $parentId, $selectedYear);
|
||||||
if ($payments) {
|
if ($payments) {
|
||||||
return $this->respond($payments);
|
return $this->respond($payments);
|
||||||
} else {
|
} else {
|
||||||
@@ -110,13 +110,8 @@ class PaymentController extends ResourceController
|
|||||||
// View: Get payments by parent ID (for web views)
|
// View: Get payments by parent ID (for web views)
|
||||||
public function getByParent($parentId)
|
public function getByParent($parentId)
|
||||||
{
|
{
|
||||||
// Fetch payments with invoice number (if available)
|
$selectedYear = $this->getSelectedPaymentHistoryYear();
|
||||||
$payments = $this->paymentModel
|
$payments = $this->paymentModel->getPaymentsByParentId((int) $parentId, $selectedYear);
|
||||||
->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();
|
|
||||||
|
|
||||||
// Parent display name
|
// Parent display name
|
||||||
$parent = $this->userModel->select('firstname, lastname')->find((int)$parentId) ?: [];
|
$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
|
// View: Create a new payment plan
|
||||||
public function create()
|
public function create()
|
||||||
{
|
{
|
||||||
@@ -346,12 +348,12 @@ class PaymentController extends ResourceController
|
|||||||
->where('parent_id', $parentId)
|
->where('parent_id', $parentId)
|
||||||
->findAll();
|
->findAll();
|
||||||
|
|
||||||
// Payments (paginated)
|
// Payments (paginated). Join invoices so history is filtered by invoice term
|
||||||
$payments = $this->paymentModel
|
// and displays current invoice state instead of stale payment snapshots.
|
||||||
->where('parent_id', $parentId)
|
$selectedYear = $this->getSelectedPaymentHistoryYear();
|
||||||
->orderBy('payment_date', 'DESC')
|
$paymentHistory = $this->paymentModel->parentPaymentHistoryQuery($parentId, $selectedYear);
|
||||||
->paginate(10);
|
$payments = $paymentHistory->paginate(10);
|
||||||
$pager = $this->paymentModel->pager;
|
$pager = $paymentHistory->pager;
|
||||||
|
|
||||||
// Invoices
|
// Invoices
|
||||||
$rawInvoices = $this->invoiceModel
|
$rawInvoices = $this->invoiceModel
|
||||||
@@ -972,8 +974,7 @@ class PaymentController extends ResourceController
|
|||||||
$checkFile,
|
$checkFile,
|
||||||
$transactionId,
|
$transactionId,
|
||||||
$paymentDate,
|
$paymentDate,
|
||||||
$this->schoolYear,
|
$invYear,
|
||||||
$this->semester,
|
|
||||||
$checkNumber,
|
$checkNumber,
|
||||||
$installmentSeq,
|
$installmentSeq,
|
||||||
(array) $this->invoiceModel->find($invoiceId),
|
(array) $this->invoiceModel->find($invoiceId),
|
||||||
@@ -1015,7 +1016,7 @@ class PaymentController extends ResourceController
|
|||||||
$rowParentDisc = $this->db->table('discount_usages')
|
$rowParentDisc = $this->db->table('discount_usages')
|
||||||
->selectSum('discount_amount', 'sum_disc')
|
->selectSum('discount_amount', 'sum_disc')
|
||||||
->where('parent_id', $parentId)
|
->where('parent_id', $parentId)
|
||||||
->where('school_year', $this->schoolYear)
|
->where('school_year', $invYear)
|
||||||
->get()->getRowArray();
|
->get()->getRowArray();
|
||||||
if ($rowParentDisc && isset($rowParentDisc['sum_disc'])) {
|
if ($rowParentDisc && isset($rowParentDisc['sum_disc'])) {
|
||||||
$parentYearDiscountTotal = (float)$rowParentDisc['sum_disc'];
|
$parentYearDiscountTotal = (float)$rowParentDisc['sum_disc'];
|
||||||
@@ -1270,7 +1271,6 @@ class PaymentController extends ResourceController
|
|||||||
$transactionId = null,
|
$transactionId = null,
|
||||||
$paymentDate = null,
|
$paymentDate = null,
|
||||||
$schoolYear = null,
|
$schoolYear = null,
|
||||||
$semester = null,
|
|
||||||
$checkNumber = null,
|
$checkNumber = null,
|
||||||
?int $installmentSeq = null,
|
?int $installmentSeq = null,
|
||||||
?array $invoice = null,
|
?array $invoice = null,
|
||||||
@@ -1315,8 +1315,7 @@ class PaymentController extends ResourceController
|
|||||||
'check_file' => $checkFile,
|
'check_file' => $checkFile,
|
||||||
'check_number' => (strtolower($paymentMethod) === 'check') ? $checkNumber : null,
|
'check_number' => (strtolower($paymentMethod) === 'check') ? $checkNumber : null,
|
||||||
'updated_by' => session()->get('user_id'),
|
'updated_by' => session()->get('user_id'),
|
||||||
'school_year' => $schoolYear ?? $this->schoolYear,
|
'school_year' => $schoolYear ?? ($invoice['school_year'] ?? $this->schoolYear),
|
||||||
'semester' => $semester ?? $this->semester,
|
|
||||||
];
|
];
|
||||||
|
|
||||||
if (!$this->paymentModel->insert($paymentData)) {
|
if (!$this->paymentModel->insert($paymentData)) {
|
||||||
|
|||||||
@@ -106,14 +106,12 @@ class WhatsappController extends BaseController
|
|||||||
$existing = $this->linkModel->where([
|
$existing = $this->linkModel->where([
|
||||||
'class_section_id' => $sectionId,
|
'class_section_id' => $sectionId,
|
||||||
'school_year' => $this->schoolYear,
|
'school_year' => $this->schoolYear,
|
||||||
'semester' => $this->semester,
|
|
||||||
])->first();
|
])->first();
|
||||||
|
|
||||||
$payload = [
|
$payload = [
|
||||||
'class_section_id' => $sectionId,
|
'class_section_id' => $sectionId,
|
||||||
'class_section_name' => $sectionName,
|
'class_section_name' => $sectionName,
|
||||||
'school_year' => $this->schoolYear,
|
'school_year' => $this->schoolYear,
|
||||||
'semester' => $this->semester,
|
|
||||||
'invite_link' => trim($inviteLink),
|
'invite_link' => trim($inviteLink),
|
||||||
'active' => $active,
|
'active' => $active,
|
||||||
];
|
];
|
||||||
@@ -434,8 +432,6 @@ class WhatsappController extends BaseController
|
|||||||
sp.secondparent_lastname AS sp_lastname,
|
sp.secondparent_lastname AS sp_lastname,
|
||||||
sp.secondparent_email AS sp_email,
|
sp.secondparent_email AS sp_email,
|
||||||
sp.secondparent_phone AS sp_phone,
|
sp.secondparent_phone AS sp_phone,
|
||||||
sp.school_year AS sp_school_year,
|
|
||||||
sp.semester AS sp_semester,
|
|
||||||
|
|
||||||
u.id AS u_id,
|
u.id AS u_id,
|
||||||
u.firstname AS u_firstname,
|
u.firstname AS u_firstname,
|
||||||
@@ -448,14 +444,6 @@ class WhatsappController extends BaseController
|
|||||||
|
|
||||||
$b->join('users u', 'u.id = sp.firstparent_id', 'left');
|
$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();
|
$rows = $b->get()->getResultArray();
|
||||||
|
|
||||||
// Flatten into a single contacts list (primary + second parent as separate rows)
|
// 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('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
|
$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(
|
$pb->join(
|
||||||
'parents sp',
|
'parents sp',
|
||||||
"sp.firstparent_id = u.id
|
'sp.firstparent_id = u.id',
|
||||||
AND sp.school_year = sc.school_year",
|
|
||||||
'left'
|
'left'
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1202,7 +1189,7 @@ class WhatsappController extends BaseController
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Class mode:
|
* 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)
|
* - Map to primaries (users) and second-parents (parents)
|
||||||
* - Return one bundle **per primary parent** (so each parent gets their own email)
|
* - 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')
|
$stuRows = $this->db->table('student_class')
|
||||||
->select('student_id')
|
->select('student_id')
|
||||||
->where('school_year', $this->schoolYear)
|
->where('school_year', $this->schoolYear)
|
||||||
->where('semester', $this->semester)
|
|
||||||
->where('class_section_id', $classSectionId)
|
->where('class_section_id', $classSectionId)
|
||||||
->get()->getResultArray();
|
->get()->getResultArray();
|
||||||
if (empty($stuRows)) return [];
|
if (empty($stuRows)) return [];
|
||||||
@@ -1302,7 +1288,7 @@ class WhatsappController extends BaseController
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* All mode:
|
* 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
|
* - Reuse class bundles per section and flatten
|
||||||
*/
|
*/
|
||||||
private function bundlesForAllParentsAllClasses(array $linkBySection): array
|
private function bundlesForAllParentsAllClasses(array $linkBySection): array
|
||||||
@@ -1310,7 +1296,6 @@ class WhatsappController extends BaseController
|
|||||||
$secRows = $this->db->table('student_class')
|
$secRows = $this->db->table('student_class')
|
||||||
->select('DISTINCT class_section_id', false)
|
->select('DISTINCT class_section_id', false)
|
||||||
->where('school_year', $this->schoolYear)
|
->where('school_year', $this->schoolYear)
|
||||||
->where('semester', $this->semester)
|
|
||||||
->orderBy('class_section_id', 'ASC')
|
->orderBy('class_section_id', 'ASC')
|
||||||
->get()->getResultArray();
|
->get()->getResultArray();
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ class AddBatchNumberToReimbursements extends Migration
|
|||||||
{
|
{
|
||||||
public function up()
|
public function up()
|
||||||
{
|
{
|
||||||
|
if (! $this->db->tableExists('reimbursements') || $this->db->fieldExists('batch_number', 'reimbursements')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
$fields = [
|
$fields = [
|
||||||
'batch_number' => [
|
'batch_number' => [
|
||||||
'type' => 'INT',
|
'type' => 'INT',
|
||||||
@@ -24,7 +28,8 @@ class AddBatchNumberToReimbursements extends Migration
|
|||||||
|
|
||||||
public function down()
|
public function down()
|
||||||
{
|
{
|
||||||
$this->forge->dropColumn('reimbursements', 'batch_number');
|
if ($this->db->tableExists('reimbursements') && $this->db->fieldExists('batch_number', 'reimbursements')) {
|
||||||
|
$this->forge->dropColumn('reimbursements', 'batch_number');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+20
-12
@@ -8,25 +8,33 @@ class AddYearlyBatchNumberToReimbursementBatches extends Migration
|
|||||||
{
|
{
|
||||||
public function up()
|
public function up()
|
||||||
{
|
{
|
||||||
$fields = [
|
if (! $this->db->tableExists('reimbursement_batches')) {
|
||||||
'yearly_batch_number' => [
|
return;
|
||||||
'type' => 'INT',
|
}
|
||||||
'constraint' => 11,
|
|
||||||
'unsigned' => true,
|
|
||||||
'default' => 0,
|
|
||||||
'null' => false,
|
|
||||||
'after' => 'title',
|
|
||||||
],
|
|
||||||
];
|
|
||||||
|
|
||||||
$this->forge->addColumn('reimbursement_batches', $fields);
|
if (! $this->db->fieldExists('yearly_batch_number', 'reimbursement_batches')) {
|
||||||
|
$fields = [
|
||||||
|
'yearly_batch_number' => [
|
||||||
|
'type' => 'INT',
|
||||||
|
'constraint' => 11,
|
||||||
|
'unsigned' => true,
|
||||||
|
'default' => 0,
|
||||||
|
'null' => false,
|
||||||
|
'after' => 'title',
|
||||||
|
],
|
||||||
|
];
|
||||||
|
|
||||||
|
$this->forge->addColumn('reimbursement_batches', $fields);
|
||||||
|
}
|
||||||
|
|
||||||
$this->fillExistingBatchNumbers();
|
$this->fillExistingBatchNumbers();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function down()
|
public function down()
|
||||||
{
|
{
|
||||||
$this->forge->dropColumn('reimbursement_batches', 'yearly_batch_number');
|
if ($this->db->tableExists('reimbursement_batches') && $this->db->fieldExists('yearly_batch_number', 'reimbursement_batches')) {
|
||||||
|
$this->forge->dropColumn('reimbursement_batches', 'yearly_batch_number');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function fillExistingBatchNumbers(): void
|
private function fillExistingBatchNumbers(): void
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ class CreateReimbursementBatchAdminFiles extends Migration
|
|||||||
{
|
{
|
||||||
public function up()
|
public function up()
|
||||||
{
|
{
|
||||||
|
if ($this->db->tableExists('reimbursement_batch_admin_files')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
$fields = [
|
$fields = [
|
||||||
'id' => [
|
'id' => [
|
||||||
'type' => 'INT',
|
'type' => 'INT',
|
||||||
|
|||||||
@@ -9,7 +9,11 @@ class FinancialSystemLedgerCleanup extends Migration
|
|||||||
public function up()
|
public function up()
|
||||||
{
|
{
|
||||||
$this->addInstallmentSequenceColumn();
|
$this->addInstallmentSequenceColumn();
|
||||||
|
$this->backfillInstallmentSequence();
|
||||||
|
$this->ensurePaymentDateHasTime();
|
||||||
$this->ensureIndexes();
|
$this->ensureIndexes();
|
||||||
|
$this->repairPaymentInvoiceTerms();
|
||||||
|
$this->normalizePaymentStatuses();
|
||||||
$this->ensureConfigurationDefaults();
|
$this->ensureConfigurationDefaults();
|
||||||
$this->archivePaypalTables();
|
$this->archivePaypalTables();
|
||||||
$this->refreshFinancialNavItems();
|
$this->refreshFinancialNavItems();
|
||||||
@@ -24,6 +28,7 @@ class FinancialSystemLedgerCleanup extends Migration
|
|||||||
}
|
}
|
||||||
|
|
||||||
$this->dropIndexIfExists('payments', 'idx_payments_invoice_id');
|
$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', 'idx_payments_parent_year_semester');
|
||||||
$this->dropIndexIfExists('payments', 'uniq_payments_transaction_id');
|
$this->dropIndexIfExists('payments', 'uniq_payments_transaction_id');
|
||||||
$this->dropIndexIfExists('invoices', 'idx_invoices_parent_year_semester');
|
$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
|
protected function ensureIndexes(): void
|
||||||
{
|
{
|
||||||
$this->addIndexIfMissing('payments', 'idx_payments_invoice_id', ['invoice_id']);
|
$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('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_invoice_id', ['invoice_id']);
|
||||||
$this->addIndexIfMissing('discount_usages', 'idx_discount_usages_parent_year_semester', ['parent_id', 'school_year', 'semester']);
|
$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
|
protected function ensureConfigurationDefaults(): void
|
||||||
{
|
{
|
||||||
if (!$this->db->tableExists('configuration')) {
|
if (!$this->db->tableExists('configuration')) {
|
||||||
|
|||||||
@@ -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`');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,8 @@ final class FinancialStatus
|
|||||||
public const INVOICE_UNPAID = 'unpaid';
|
public const INVOICE_UNPAID = 'unpaid';
|
||||||
public const INVOICE_PARTIALLY_PAID = 'partially_paid';
|
public const INVOICE_PARTIALLY_PAID = 'partially_paid';
|
||||||
public const INVOICE_PAID = 'paid';
|
public const INVOICE_PAID = 'paid';
|
||||||
|
public const INVOICE_OVERPAID = 'overpaid';
|
||||||
|
public const INVOICE_CANCELLED = 'cancelled';
|
||||||
|
|
||||||
public const PAYMENT_RECORDED = 'recorded';
|
public const PAYMENT_RECORDED = 'recorded';
|
||||||
public const PAYMENT_VOIDED = 'voided';
|
public const PAYMENT_VOIDED = 'voided';
|
||||||
@@ -18,6 +20,23 @@ final class FinancialStatus
|
|||||||
public const PAYMENT_CANCELED = 'canceled';
|
public const PAYMENT_CANCELED = 'canceled';
|
||||||
public const PAYMENT_CANCELLED = 'cancelled';
|
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_PENDING = 'pending';
|
||||||
public const REFUND_APPROVED = 'approved';
|
public const REFUND_APPROVED = 'approved';
|
||||||
public const REFUND_REJECTED = 'rejected';
|
public const REFUND_REJECTED = 'rejected';
|
||||||
@@ -55,6 +74,8 @@ final class FinancialStatus
|
|||||||
return match (self::normalize($status)) {
|
return match (self::normalize($status)) {
|
||||||
'paid', 'full' => self::INVOICE_PAID,
|
'paid', 'full' => self::INVOICE_PAID,
|
||||||
'partially paid', 'partially_paid', 'partial' => self::INVOICE_PARTIALLY_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,
|
default => self::INVOICE_UNPAID,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ class AttendanceDataModel extends Model
|
|||||||
'date',
|
'date',
|
||||||
'status',
|
'status',
|
||||||
'reason',
|
'reason',
|
||||||
'reported',
|
|
||||||
'is_reported',
|
'is_reported',
|
||||||
'is_notified',
|
'is_notified',
|
||||||
'semester',
|
'semester',
|
||||||
|
|||||||
@@ -7,6 +7,6 @@ class ClassPrepAdjustmentModel extends Model
|
|||||||
{
|
{
|
||||||
protected $table = 'class_prep_adjustments';
|
protected $table = 'class_prep_adjustments';
|
||||||
protected $allowedFields = [
|
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 = [
|
protected $allowedFields = [
|
||||||
'class_section_id',
|
'class_section_id',
|
||||||
'class_section',
|
'class_section',
|
||||||
'school_year',
|
|
||||||
'prep_data',
|
'prep_data',
|
||||||
'created_at',
|
'created_at',
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -19,8 +19,6 @@ class ContactUsModel extends Model
|
|||||||
'reciever_id',
|
'reciever_id',
|
||||||
'subject',
|
'subject',
|
||||||
'message',
|
'message',
|
||||||
'semester',
|
|
||||||
'school_year',
|
|
||||||
'created_at',
|
'created_at',
|
||||||
'updated_at'
|
'updated_at'
|
||||||
];
|
];
|
||||||
@@ -35,8 +33,6 @@ class ContactUsModel extends Model
|
|||||||
'reciever_id' => 'required|integer',
|
'reciever_id' => 'required|integer',
|
||||||
'subject' => 'required|string|max_length[255]',
|
'subject' => 'required|string|max_length[255]',
|
||||||
'message' => 'required|string',
|
'message' => 'required|string',
|
||||||
'semester' => 'required|string|max_length[255]',
|
|
||||||
'school_year' => 'permit_empty|string|max_length[9]'
|
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $validationMessages = [];
|
protected $validationMessages = [];
|
||||||
@@ -51,10 +47,7 @@ class ContactUsModel extends Model
|
|||||||
*/
|
*/
|
||||||
public function getMessagesBySemesterAndYear($semester, $school_year)
|
public function getMessagesBySemesterAndYear($semester, $school_year)
|
||||||
{
|
{
|
||||||
return $this->where([
|
return $this->findAll();
|
||||||
'semester' => $semester,
|
|
||||||
'school_year' => $school_year
|
|
||||||
])->findAll();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -92,4 +85,4 @@ class ContactUsModel extends Model
|
|||||||
{
|
{
|
||||||
return $this->update($id, $data);
|
return $this->update($id, $data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,19 @@ use CodeIgniter\Model;
|
|||||||
class EmailTemplateModel extends Model {
|
class EmailTemplateModel extends Model {
|
||||||
protected $table = 'email_templates';
|
protected $table = 'email_templates';
|
||||||
protected $primaryKey = 'id';
|
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 {
|
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 {
|
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',
|
'cellphone',
|
||||||
'email',
|
'email',
|
||||||
'relation',
|
'relation',
|
||||||
'semester',
|
|
||||||
'school_year',
|
|
||||||
'created_at',
|
'created_at',
|
||||||
'updated_at'
|
'updated_at'
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ class EnrollmentModel extends Model
|
|||||||
/**
|
/**
|
||||||
* Get all enrolled students (full student info) for a given parent.
|
* 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.*')
|
$builder = $this->select('students.*')
|
||||||
->join('students', 'students.id = enrollments.student_id')
|
->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.
|
* 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')
|
$builder = $this->db->table('enrollments')
|
||||||
->select('students.id, students.firstname, students.lastname, students.grade_level')
|
->select('students.id, students.firstname, students.lastname, students.grade_level')
|
||||||
|
|||||||
@@ -28,7 +28,6 @@ class EventChargesModel extends Model
|
|||||||
'external_parent_email',
|
'external_parent_email',
|
||||||
'semester',
|
'semester',
|
||||||
'school_year',
|
'school_year',
|
||||||
'created_by',
|
|
||||||
'updated_by',
|
'updated_by',
|
||||||
'created_at',
|
'created_at',
|
||||||
'updated_at'
|
'updated_at'
|
||||||
|
|||||||
@@ -32,7 +32,6 @@ class ExamDraftModel extends Model
|
|||||||
];
|
];
|
||||||
|
|
||||||
protected $allowedFields = [
|
protected $allowedFields = [
|
||||||
'teacher_id',
|
|
||||||
'author_id',
|
'author_id',
|
||||||
'class_section_id',
|
'class_section_id',
|
||||||
'semester',
|
'semester',
|
||||||
@@ -40,20 +39,14 @@ class ExamDraftModel extends Model
|
|||||||
'exam_type',
|
'exam_type',
|
||||||
'draft_title',
|
'draft_title',
|
||||||
'author_comment',
|
'author_comment',
|
||||||
'description',
|
|
||||||
'teacher_file',
|
|
||||||
'teacher_filename',
|
|
||||||
'author_file',
|
'author_file',
|
||||||
'author_filename',
|
'author_filename',
|
||||||
'status',
|
'status',
|
||||||
'acceptance_type',
|
'acceptance_type',
|
||||||
'review_revision',
|
'review_revision',
|
||||||
'reviewer_id',
|
'reviewer_id',
|
||||||
'admin_id',
|
|
||||||
'is_legacy',
|
'is_legacy',
|
||||||
'reviewer_comment',
|
|
||||||
'reviewer_comments',
|
'reviewer_comments',
|
||||||
'admin_comments',
|
|
||||||
'reviewed_at',
|
'reviewed_at',
|
||||||
'final_file',
|
'final_file',
|
||||||
'final_filename',
|
'final_filename',
|
||||||
@@ -87,11 +80,9 @@ class ExamDraftModel extends Model
|
|||||||
* @var array<string, string>
|
* @var array<string, string>
|
||||||
*/
|
*/
|
||||||
protected array $casts = [
|
protected array $casts = [
|
||||||
'teacher_id' => 'int',
|
|
||||||
'author_id' => 'int',
|
'author_id' => 'int',
|
||||||
'class_section_id' => 'int',
|
'class_section_id' => 'int',
|
||||||
'reviewer_id' => '?int',
|
'reviewer_id' => '?int',
|
||||||
'admin_id' => '?int',
|
|
||||||
'review_revision' => 'int',
|
'review_revision' => 'int',
|
||||||
'version' => 'int',
|
'version' => 'int',
|
||||||
'previous_draft_id' => '?int',
|
'previous_draft_id' => '?int',
|
||||||
|
|||||||
@@ -12,9 +12,10 @@ class ExamModel extends Model
|
|||||||
|
|
||||||
protected $allowedFields = [
|
protected $allowedFields = [
|
||||||
'student_id',
|
'student_id',
|
||||||
'school_id',
|
'student_school_id',
|
||||||
'class_section_id',
|
'class_section_id',
|
||||||
'exam_name',
|
'exam_name',
|
||||||
|
'school_year',
|
||||||
'created_at'
|
'created_at'
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -24,4 +25,4 @@ class ExamModel extends Model
|
|||||||
protected $updatedField = ''; // Set this if you later add an `updated_at` column
|
protected $updatedField = ''; // Set this if you later add an `updated_at` column
|
||||||
|
|
||||||
protected $returnType = 'array'; // You can change this to 'object' if preferred
|
protected $returnType = 'array'; // You can change this to 'object' if preferred
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ class FinalExamModel extends Model
|
|||||||
'class_section_id',
|
'class_section_id',
|
||||||
'updated_by',
|
'updated_by',
|
||||||
'score',
|
'score',
|
||||||
'comment',
|
|
||||||
'semester',
|
'semester',
|
||||||
'school_year',
|
'school_year',
|
||||||
'created_at',
|
'created_at',
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ class FinalScoreModel extends Model
|
|||||||
'student_id',
|
'student_id',
|
||||||
'school_id',
|
'school_id',
|
||||||
'class_section_id',
|
'class_section_id',
|
||||||
'teacher_id',
|
'updated_by',
|
||||||
'score',
|
'score',
|
||||||
'score_letter',
|
'score_letter',
|
||||||
'comment',
|
'comment',
|
||||||
@@ -37,4 +37,4 @@ class FinalScoreModel extends Model
|
|||||||
// Return the score, or null if no result is found
|
// Return the score, or null if no result is found
|
||||||
return $result ? $result['score'] : null;
|
return $result ? $result['score'] : null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,10 +30,6 @@ protected $table = 'inventory_items';
|
|||||||
'sku',
|
'sku',
|
||||||
'notes',
|
'notes',
|
||||||
|
|
||||||
// academic tags
|
|
||||||
'semester',
|
|
||||||
'school_year',
|
|
||||||
|
|
||||||
// audit
|
// audit
|
||||||
'updated_by',
|
'updated_by',
|
||||||
|
|
||||||
@@ -50,7 +46,5 @@ protected $table = 'inventory_items';
|
|||||||
'name' => 'required|min_length[2]',
|
'name' => 'required|min_length[2]',
|
||||||
'quantity' => 'permit_empty|integer',
|
'quantity' => 'permit_empty|integer',
|
||||||
'unit_price' => 'permit_empty|decimal',
|
'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',
|
'student_lastname',
|
||||||
'school_id',
|
'school_id',
|
||||||
'enrolled',
|
'enrolled',
|
||||||
'school_year',
|
|
||||||
'semester',
|
|
||||||
'created_at',
|
'created_at',
|
||||||
'updated_at'
|
'updated_at'
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -13,8 +13,6 @@ class IpAttemptModel extends Model
|
|||||||
'ip_address',
|
'ip_address',
|
||||||
'attempts',
|
'attempts',
|
||||||
'last_attempt_at',
|
'last_attempt_at',
|
||||||
'semester',
|
|
||||||
'school_year',
|
|
||||||
'blocked_until'
|
'blocked_until'
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -48,4 +46,4 @@ class IpAttemptModel extends Model
|
|||||||
{
|
{
|
||||||
return $this->insert($data);
|
return $this->insert($data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ class LoginActivityModel extends Model
|
|||||||
'logout_time',
|
'logout_time',
|
||||||
'ip_address',
|
'ip_address',
|
||||||
'user_agent',
|
'user_agent',
|
||||||
'school_year',
|
|
||||||
'semester',
|
'semester',
|
||||||
'created_at',
|
'created_at',
|
||||||
'updated_at'
|
'updated_at'
|
||||||
@@ -35,4 +34,4 @@ class LoginActivityModel extends Model
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
?>
|
?>
|
||||||
|
|||||||
@@ -21,8 +21,7 @@ class MessageModel extends Model
|
|||||||
'priority',
|
'priority',
|
||||||
'attachment',
|
'attachment',
|
||||||
'status',
|
'status',
|
||||||
'semester', // Added field
|
'semester'
|
||||||
'school_year' // Added field
|
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $useTimestamps = false; // Since you're manually handling date fields
|
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)
|
public function getMessagesBySemesterAndYear($semester, $school_year = null)
|
||||||
{
|
{
|
||||||
$builder = $this->where('semester', $semester);
|
return $this->where('semester', $semester)
|
||||||
if ($school_year) {
|
->orderBy('sent_datetime', 'DESC')
|
||||||
$builder->where('school_year', $school_year);
|
->findAll();
|
||||||
}
|
|
||||||
return $builder->orderBy('sent_datetime', 'DESC')->findAll();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ class NotificationModel extends Model
|
|||||||
'status',
|
'status',
|
||||||
'action_url',
|
'action_url',
|
||||||
'attachment_path',
|
'attachment_path',
|
||||||
'semester',
|
'expires_at',
|
||||||
'school_year',
|
'sent_at',
|
||||||
'scheduled_at'
|
'scheduled_at'
|
||||||
];
|
];
|
||||||
protected $useTimestamps = true;
|
protected $useTimestamps = true;
|
||||||
|
|||||||
@@ -15,7 +15,5 @@ class ParentModel extends Model
|
|||||||
'secondparent_email',
|
'secondparent_email',
|
||||||
'secondparent_phone',
|
'secondparent_phone',
|
||||||
'firstparent_id',
|
'firstparent_id',
|
||||||
'semester',
|
|
||||||
'school_year',
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
+283
-66
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
namespace App\Models;
|
namespace App\Models;
|
||||||
|
|
||||||
|
use CodeIgniter\Database\ConnectionInterface;
|
||||||
use CodeIgniter\Model;
|
use CodeIgniter\Model;
|
||||||
|
use CodeIgniter\Validation\ValidationInterface;
|
||||||
|
|
||||||
class PaymentModel extends Model
|
class PaymentModel extends Model
|
||||||
{
|
{
|
||||||
@@ -10,12 +12,22 @@ class PaymentModel extends Model
|
|||||||
protected $primaryKey = 'id';
|
protected $primaryKey = 'id';
|
||||||
protected $returnType = 'array';
|
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 = [
|
protected $allowedFields = [
|
||||||
'parent_id',
|
'parent_id',
|
||||||
'invoice_id',
|
'invoice_id',
|
||||||
|
|
||||||
|
// Legacy invoice snapshot fields. Do not use these as source of truth.
|
||||||
'total_amount',
|
'total_amount',
|
||||||
|
|
||||||
|
// Actual payment fields.
|
||||||
'paid_amount',
|
'paid_amount',
|
||||||
'balance',
|
'balance',
|
||||||
|
'balance_amount',
|
||||||
|
'balance_after_payment',
|
||||||
'number_of_installments',
|
'number_of_installments',
|
||||||
'installment_seq',
|
'installment_seq',
|
||||||
'transaction_id',
|
'transaction_id',
|
||||||
@@ -24,26 +36,44 @@ class PaymentModel extends Model
|
|||||||
'payment_method',
|
'payment_method',
|
||||||
'payment_date',
|
'payment_date',
|
||||||
'school_year',
|
'school_year',
|
||||||
'semester',
|
|
||||||
'status',
|
'status',
|
||||||
'updated_by'
|
'updated_by',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $useTimestamps = false;
|
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 = [
|
protected $validationRules = [
|
||||||
'parent_id' => 'required|integer',
|
'parent_id' => 'required|integer',
|
||||||
'invoice_id' => 'required|integer',
|
'invoice_id' => 'required|integer',
|
||||||
'total_amount' => 'required|decimal',
|
|
||||||
'paid_amount' => 'required|decimal',
|
// Legacy snapshot. Optional because invoice total belongs to invoices table.
|
||||||
'balance' => 'required|decimal',
|
'total_amount' => 'permit_empty|decimal',
|
||||||
'number_of_installments' => 'required|integer',
|
|
||||||
'payment_method' => 'required|max_length[50]', // ✅ Removed 'string'
|
'paid_amount' => 'required|decimal|greater_than[0]',
|
||||||
'payment_date' => 'required|valid_date[Y-m-d H:i:s]',
|
|
||||||
'status' => 'required|max_length[50]', // ✅ Removed 'string'
|
// 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]',
|
'check_number' => 'permit_empty|max_length[100]',
|
||||||
|
'updated_by' => 'permit_empty|integer',
|
||||||
];
|
];
|
||||||
|
|
||||||
protected $validationMessages = [
|
protected $validationMessages = [
|
||||||
@@ -56,112 +86,225 @@ class PaymentModel extends Model
|
|||||||
'integer' => 'Invoice ID must be an integer.',
|
'integer' => 'Invoice ID must be an integer.',
|
||||||
],
|
],
|
||||||
'total_amount' => [
|
'total_amount' => [
|
||||||
'required' => 'Total amount is required.',
|
|
||||||
'decimal' => 'Total amount must be a valid decimal.',
|
'decimal' => 'Total amount must be a valid decimal.',
|
||||||
],
|
],
|
||||||
'paid_amount' => [
|
'paid_amount' => [
|
||||||
'required' => 'Paid amount is required.',
|
'required' => 'Paid amount is required.',
|
||||||
'decimal' => 'Paid amount must be a valid decimal.',
|
'decimal' => 'Paid amount must be a valid decimal.',
|
||||||
|
'greater_than' => 'Paid amount must be greater than zero.',
|
||||||
],
|
],
|
||||||
'balance' => [
|
'balance' => [
|
||||||
'required' => 'Balance is required.',
|
|
||||||
'decimal' => 'Balance must be a valid decimal.',
|
'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' => [
|
'payment_date' => [
|
||||||
'required' => 'Payment date is required.',
|
'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' => [
|
'payment_method' => [
|
||||||
'required' => 'Payment method is required.',
|
'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' => [
|
'status' => [
|
||||||
'required' => 'Status is required.',
|
'required' => 'Status is required.',
|
||||||
'max_length' => 'Status must not exceed 50 characters.',
|
'max_length' => 'Status must not exceed 50 characters.',
|
||||||
],
|
],
|
||||||
'number_of_installments' => [
|
'number_of_installments' => [
|
||||||
'required' => 'Number of installments is required.',
|
|
||||||
'integer' => 'Number of installments must be an integer.',
|
'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' => [
|
'check_number' => [
|
||||||
'max_length' => 'Check number must not exceed 100 characters.',
|
'max_length' => 'Check number must not exceed 100 characters.',
|
||||||
]
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
private array $paymentColumns = [];
|
||||||
* Get payments by parent ID.
|
|
||||||
*
|
private array $excludedPaymentStatuses = [
|
||||||
* @param int $parentId
|
'void',
|
||||||
* @return array
|
'voided',
|
||||||
*/
|
'refunded',
|
||||||
public function getPaymentsByParentId(int $parentId): array
|
'failed',
|
||||||
|
'chargeback',
|
||||||
|
'declined',
|
||||||
|
'reversed',
|
||||||
|
'canceled',
|
||||||
|
'cancelled',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function __construct(?ConnectionInterface $db = null, ?ValidationInterface $validation = null)
|
||||||
{
|
{
|
||||||
return $this->where('parent_id', $parentId)
|
parent::__construct($db, $validation);
|
||||||
->orderBy('payment_date', 'DESC')
|
|
||||||
->findAll();
|
$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
|
* The source of truth for invoice total/status/balance is invoices, not payments.
|
||||||
* @return float
|
*/
|
||||||
|
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
|
public function getTotalPaidByParentId(int $parentId, string $schoolYear): float
|
||||||
{
|
{
|
||||||
$db = \Config\Database::connect();
|
$result = $this->db->table('payments p')
|
||||||
|
->selectSum('p.paid_amount', 'total_paid')
|
||||||
$result = $db->table('payments')
|
->join('invoices i', 'i.id = p.invoice_id', 'inner')
|
||||||
->selectSum('paid_amount', 'total_paid')
|
->where('p.parent_id', $parentId)
|
||||||
->where('parent_id', $parentId)
|
->where('i.school_year', $schoolYear)
|
||||||
->where('school_year', $schoolYear)
|
->where($this->successfulPaymentWhereSql('p.status'), null, false)
|
||||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
|
||||||
->get()
|
->get()
|
||||||
->getRowArray();
|
->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
|
* This should not be used for new payment recording.
|
||||||
* @param float $amountPaid
|
* New payments should be inserted as immutable payment rows and invoices recalculated by InvoiceLedgerService.
|
||||||
* @return bool
|
|
||||||
*/
|
*/
|
||||||
public function updateBalance(int $paymentId, float $amountPaid): bool
|
public function updateBalance(int $paymentId, float $amountPaid): bool
|
||||||
{
|
{
|
||||||
|
if ($amountPaid <= 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$payment = $this->find($paymentId);
|
$payment = $this->find($paymentId);
|
||||||
if (!$payment) {
|
if (!$payment) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$newBalance = $payment['balance'] - $amountPaid;
|
$updateData = [
|
||||||
|
'paid_amount' => round((float) ($payment['paid_amount'] ?? 0) + $amountPaid, 2),
|
||||||
|
];
|
||||||
|
|
||||||
return $this->update($paymentId, [
|
$balanceField = $this->getPaymentBalanceField();
|
||||||
'paid_amount' => $payment['paid_amount'] + $amountPaid,
|
if ($balanceField !== null && array_key_exists($balanceField, $payment)) {
|
||||||
'balance' => $newBalance
|
$updateData[$balanceField] = max(
|
||||||
]);
|
0.00,
|
||||||
|
round((float) ($payment[$balanceField] ?? 0) - $amountPaid, 2)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->update($paymentId, $updateData);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get payments by school year.
|
* Get payments by school year.
|
||||||
*
|
*
|
||||||
* @param string $schoolYear
|
* Uses invoice school year when possible because payment.school_year may have old bad data.
|
||||||
* @return array
|
|
||||||
*/
|
*/
|
||||||
public function getPaymentsByYear(string $schoolYear): array
|
public function getPaymentsByYear(string $schoolYear): array
|
||||||
{
|
{
|
||||||
return $this->where('school_year', $schoolYear)
|
$paymentBalanceSelect = $this->getPaymentBalanceSelectExpression('payments');
|
||||||
->orderBy('payment_date', 'DESC')
|
|
||||||
|
$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();
|
->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
|
public function generateNewTransactionId(): string
|
||||||
{
|
{
|
||||||
@@ -173,41 +316,115 @@ class PaymentModel extends Model
|
|||||||
->first();
|
->first();
|
||||||
|
|
||||||
if ($latest && isset($latest['transaction_id'])) {
|
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;
|
$newNumber = $lastNumber + 1;
|
||||||
} else {
|
} else {
|
||||||
$newNumber = 1;
|
$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
|
public function getPaymentsByInvoice($invoiceIds): array
|
||||||
{
|
{
|
||||||
// Normalize input
|
|
||||||
if (!is_array($invoiceIds)) {
|
if (!is_array($invoiceIds)) {
|
||||||
$invoiceIds = [$invoiceIds];
|
$invoiceIds = [$invoiceIds];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$invoiceIds = array_values(array_filter(array_map('intval', $invoiceIds)));
|
||||||
|
|
||||||
if (empty($invoiceIds)) {
|
if (empty($invoiceIds)) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Subquery: latest payment_date per invoice (Full/Partial only)
|
|
||||||
$latestSub = $this->db->table('payments')
|
$latestSub = $this->db->table('payments')
|
||||||
->select('invoice_id, MAX(payment_date) AS max_date')
|
->select('invoice_id, MAX(id) AS max_id')
|
||||||
->whereIn('status', ['Full', 'Paid', 'Partially Paid'])
|
->whereIn('invoice_id', $invoiceIds)
|
||||||
|
->where('paid_amount >', 0)
|
||||||
|
->where($this->successfulPaymentWhereSql('status'), null, false)
|
||||||
->groupBy('invoice_id')
|
->groupBy('invoice_id')
|
||||||
->getCompiledSelect();
|
->getCompiledSelect();
|
||||||
|
|
||||||
// Main query: join payments to the latest per invoice
|
return $this->db->table('payments p')
|
||||||
$rows = $this->db->table('payments p')
|
->select([
|
||||||
->select('p.invoice_id, p.paid_amount AS last_paid_amount, p.payment_date AS last_payment_date, p.status AS last_payment_status')
|
'p.invoice_id',
|
||||||
->join("($latestSub) latest", 'latest.invoice_id = p.invoice_id AND latest.max_date = p.payment_date', 'inner', false) // <-- escape=false
|
'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.invoice_id', $invoiceIds)
|
||||||
->whereIn('p.status', ['Full', 'Paid', 'Partially Paid'])
|
|
||||||
->get()
|
->get()
|
||||||
->getResultArray();
|
->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_method',
|
||||||
'payment_status',
|
'payment_status',
|
||||||
'transaction_fee',
|
'transaction_fee',
|
||||||
'payment_reference',
|
|
||||||
'semester',
|
'semester',
|
||||||
'school_year',
|
'school_year'
|
||||||
'is_full_payment', // Flag to track full payment status
|
|
||||||
'created_at',
|
|
||||||
'updated_at'
|
|
||||||
];
|
];
|
||||||
|
|
||||||
// Set automatic timestamps
|
protected $useTimestamps = false;
|
||||||
protected $useTimestamps = true;
|
|
||||||
protected $createdField = 'created_at';
|
|
||||||
protected $updatedField = 'updated_at';
|
|
||||||
|
|
||||||
// Validation rules
|
// Validation rules
|
||||||
protected $validationRules = [
|
protected $validationRules = [
|
||||||
@@ -38,8 +31,8 @@ class PaymentTransactionModel extends Model
|
|||||||
'amount' => 'required|decimal',
|
'amount' => 'required|decimal',
|
||||||
'payment_method' => 'required|string|max_length[50]',
|
'payment_method' => 'required|string|max_length[50]',
|
||||||
'payment_status' => 'required|string|max_length[50]',
|
'payment_status' => 'required|string|max_length[50]',
|
||||||
'payment_reference' => 'permit_empty|string|max_length[255]',
|
'semester' => 'permit_empty|string|max_length[30]',
|
||||||
'is_full_payment' => 'required|in_list[0,1]', // 0 for installment, 1 for full payment
|
'school_year' => 'permit_empty|string|max_length[9]',
|
||||||
];
|
];
|
||||||
|
|
||||||
// Custom error messages
|
// Custom error messages
|
||||||
@@ -64,13 +57,6 @@ class PaymentTransactionModel extends Model
|
|||||||
'required' => 'The payment status is required.',
|
'required' => 'The payment status is required.',
|
||||||
'max_length' => 'The payment status must not exceed 50 characters.',
|
'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)
|
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)
|
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 = [
|
protected $allowedFields = [
|
||||||
'student_id',
|
'student_id',
|
||||||
'level',
|
'level',
|
||||||
'school_year',
|
|
||||||
'created_by',
|
'created_by',
|
||||||
'updated_by',
|
'updated_by',
|
||||||
'created_at',
|
'created_at',
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ class PreferencesModel extends Model
|
|||||||
// Allowed fields to enable mass assignment
|
// Allowed fields to enable mass assignment
|
||||||
protected $allowedFields = [
|
protected $allowedFields = [
|
||||||
'user_id', // Foreign key linking preferences to a user
|
'user_id', // Foreign key linking preferences to a user
|
||||||
'receive_email_notifications', // Email notifications preference
|
'notification_email', // Email notifications preference
|
||||||
'receive_sms_notifications', // SMS notifications preference
|
'notification_sms', // SMS notifications preference
|
||||||
'theme', // Theme preference (e.g., light or dark)
|
'theme', // Theme preference (e.g., light or dark)
|
||||||
'language', // Language preference
|
'language', // Language preference
|
||||||
'timezone', // Timezone preference
|
'timezone', // Timezone preference
|
||||||
@@ -22,11 +22,6 @@ class PreferencesModel extends Model
|
|||||||
'menu_custom_bg', // Custom menu background color
|
'menu_custom_bg', // Custom menu background color
|
||||||
'menu_custom_text', // Custom menu text color
|
'menu_custom_text', // Custom menu text color
|
||||||
'menu_custom_mode', // Custom menu mode: light|dark
|
'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
|
'created_at', // Timestamp of when the record was created
|
||||||
'updated_at' // Timestamp of when the record was last updated
|
'updated_at' // Timestamp of when the record was last updated
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ class SectionModel extends Model
|
|||||||
protected $allowedFields = [
|
protected $allowedFields = [
|
||||||
'section_name',
|
'section_name',
|
||||||
'description',
|
'description',
|
||||||
'created_at',
|
|
||||||
'updated_at',
|
'updated_at',
|
||||||
'updated_by'
|
'updated_by'
|
||||||
];
|
];
|
||||||
@@ -55,4 +54,4 @@ class SectionModel extends Model
|
|||||||
{
|
{
|
||||||
return $this->delete($sectionId);
|
return $this->delete($sectionId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,8 +21,6 @@ class StaffModel extends Model
|
|||||||
'phone',
|
'phone',
|
||||||
'role_name',
|
'role_name',
|
||||||
'active_role',
|
'active_role',
|
||||||
'status',
|
|
||||||
'school_year',
|
|
||||||
'created_at',
|
'created_at',
|
||||||
'updated_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.
|
* Ensures created_at is only set on insert and updated_at can be provided by caller.
|
||||||
*/
|
*/
|
||||||
public function upsert(array $data): bool
|
public function upsert(array $data): bool
|
||||||
@@ -53,27 +51,9 @@ class StaffModel extends Model
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If school_year not provided, try to keep existing or fall back to current year string
|
unset($data['school_year'], $data['status']);
|
||||||
$schoolYear = $data['school_year'] ?? null;
|
|
||||||
|
|
||||||
if ($schoolYear === null) {
|
$existing = $this->where('user_id', $data['user_id'])->first();
|
||||||
// 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();
|
$now = utc_now();
|
||||||
|
|
||||||
@@ -100,4 +80,3 @@ class StaffModel extends Model
|
|||||||
return $this->insert($data) !== false;
|
return $this->insert($data) !== false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ class StudentClassModel extends Model
|
|||||||
|
|
||||||
protected $allowedFields = [
|
protected $allowedFields = [
|
||||||
'student_id',
|
'student_id',
|
||||||
'school_id',
|
|
||||||
'class_section_id',
|
'class_section_id',
|
||||||
'school_year',
|
'school_year',
|
||||||
'is_event_only',
|
'is_event_only',
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ class StudentModel extends Model
|
|||||||
'photo_consent',
|
'photo_consent',
|
||||||
'is_new',
|
'is_new',
|
||||||
'parent_id',
|
'parent_id',
|
||||||
'school_year',
|
|
||||||
'registration_date',
|
'registration_date',
|
||||||
'tuition_paid',
|
'tuition_paid',
|
||||||
'year_of_registration',
|
'year_of_registration',
|
||||||
@@ -122,7 +121,9 @@ class StudentModel extends Model
|
|||||||
|
|
||||||
// school_year filter (skip if null or "all")
|
// school_year filter (skip if null or "all")
|
||||||
if ($schoolYear !== null && strtolower($schoolYear) !== '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
|
return $builder
|
||||||
@@ -171,12 +172,13 @@ class StudentModel extends Model
|
|||||||
users.cellphone as phone,
|
users.cellphone as phone,
|
||||||
students.registration_grade,
|
students.registration_grade,
|
||||||
classSection.class_section_name as current_class,
|
classSection.class_section_name as current_class,
|
||||||
"' . $schoolYear . '" as school_year,
|
student_class.school_year,
|
||||||
"' . $semester . '" as semester
|
"' . $semester . '" as semester
|
||||||
')
|
')
|
||||||
->join('users', 'users.id = students.parent_id', 'left')
|
->join('users', 'users.id = students.parent_id', 'left')
|
||||||
->join('student_class', 'student_class.student_id = students.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()
|
->get()
|
||||||
->getResultArray();
|
->getResultArray();
|
||||||
}
|
}
|
||||||
@@ -199,7 +201,7 @@ class StudentModel extends Model
|
|||||||
')
|
')
|
||||||
->join('student_class', 'students.id = student_class.student_id', 'left')
|
->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('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)
|
->where('teacher_class.teacher_id', $teacherId)
|
||||||
->get()
|
->get()
|
||||||
->getResultArray();
|
->getResultArray();
|
||||||
|
|||||||
@@ -28,7 +28,6 @@ class UserModel extends Model
|
|||||||
'failed_attempts',
|
'failed_attempts',
|
||||||
'last_failed_at',
|
'last_failed_at',
|
||||||
'semester',
|
'semester',
|
||||||
'school_year',
|
|
||||||
'status',
|
'status',
|
||||||
'is_suspended',
|
'is_suspended',
|
||||||
'is_verified',
|
'is_verified',
|
||||||
@@ -237,13 +236,23 @@ class UserModel extends Model
|
|||||||
|
|
||||||
public function getUsersByRoleAndSchoolYear(string $roleName, string $schoolYear): array
|
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('user_roles', 'user_roles.user_id = users.id')
|
||||||
->join('roles', 'roles.id = user_roles.role_id')
|
->join('roles', 'roles.id = user_roles.role_id')
|
||||||
->where('roles.name', $roleName)
|
->where('roles.name', $roleName)
|
||||||
->where('users.school_year', $schoolYear)
|
->where('user_roles.deleted_at', null);
|
||||||
->where('user_roles.deleted_at', null)
|
|
||||||
->findAll();
|
if ($this->userRolesHaveSchoolYear()) {
|
||||||
|
$builder->where('user_roles.school_year', $schoolYear);
|
||||||
|
} elseif ($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
|
public function countAdminsBySchoolYear(string $schoolYear): int
|
||||||
@@ -260,8 +269,8 @@ class UserModel extends Model
|
|||||||
)
|
)
|
||||||
->join('user_roles ur', 'ur.user_id = u.id', 'inner')
|
->join('user_roles ur', 'ur.user_id = u.id', 'inner')
|
||||||
->join('roles r', 'r.id = ur.role_id', 'inner')
|
->join('roles r', 'r.id = ur.role_id', 'inner')
|
||||||
->where('u.school_year', $schoolYear)
|
|
||||||
->where('r.is_active', 1)
|
->where('r.is_active', 1)
|
||||||
|
->where('LOWER(r.name) NOT IN ("guest","teacher","teacher_assistant","parent")', null, false)
|
||||||
->groupBy('u.id')
|
->groupBy('u.id')
|
||||||
->having('is_admin', 1);
|
->having('is_admin', 1);
|
||||||
|
|
||||||
@@ -407,4 +416,19 @@ class UserModel extends Model
|
|||||||
->orderBy($sort === 'roles' ? 'roles' : $sort, $order)
|
->orderBy($sort === 'roles' ? 'roles' : $sort, $order)
|
||||||
->findAll();
|
->findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function userRolesHaveSchoolYear(): bool
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return in_array('school_year', $this->db->getFieldNames('user_roles'), true);
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function roleUsesTeacherAssignments(string $roleName): bool
|
||||||
|
{
|
||||||
|
$role = strtolower(trim($roleName));
|
||||||
|
return $role === 'ta' || str_contains($role, 'teacher');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,8 +13,6 @@ class UserRoleModel extends Model
|
|||||||
protected $allowedFields = [
|
protected $allowedFields = [
|
||||||
'user_id',
|
'user_id',
|
||||||
'role_id',
|
'role_id',
|
||||||
'semester',
|
|
||||||
'school_year',
|
|
||||||
'created_at',
|
'created_at',
|
||||||
'updated_at',
|
'updated_at',
|
||||||
'updated_by',
|
'updated_by',
|
||||||
@@ -99,4 +97,4 @@ public function getRolesByUserId(int $userId): array
|
|||||||
'updated_by' => session()->get('user_id')
|
'updated_by' => session()->get('user_id')
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ class WhatsappGroupLinkModel extends Model
|
|||||||
'class_section_id',
|
'class_section_id',
|
||||||
'class_section_name',
|
'class_section_name',
|
||||||
'school_year',
|
'school_year',
|
||||||
'semester',
|
|
||||||
'invite_link',
|
'invite_link',
|
||||||
'active',
|
'active',
|
||||||
];
|
];
|
||||||
@@ -22,9 +21,9 @@ class WhatsappGroupLinkModel extends Model
|
|||||||
*
|
*
|
||||||
* @param int $sectionId Class/section code (not PK).
|
* @param int $sectionId Class/section code (not PK).
|
||||||
* @param string $year School year, e.g. "2025-2026".
|
* @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 $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(
|
public function getLinkForSection(
|
||||||
int $sectionId,
|
int $sectionId,
|
||||||
@@ -40,17 +39,6 @@ class WhatsappGroupLinkModel extends Model
|
|||||||
->where('class_section_id', $sectionId)
|
->where('class_section_id', $sectionId)
|
||||||
->where('school_year', $year);
|
->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) {
|
if ($onlyActive) {
|
||||||
$b = $b->where('active', 1);
|
$b = $b->where('active', 1);
|
||||||
}
|
}
|
||||||
@@ -70,7 +58,7 @@ class WhatsappGroupLinkModel extends Model
|
|||||||
* @param string $year
|
* @param string $year
|
||||||
* @param string $sem
|
* @param string $sem
|
||||||
* @param bool|null $onlyActive true: active only, false: inactive only, null: both
|
* @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(
|
public function getAllForTerm(
|
||||||
string $year,
|
string $year,
|
||||||
@@ -84,17 +72,6 @@ class WhatsappGroupLinkModel extends Model
|
|||||||
$b = $this->asArray()
|
$b = $this->asArray()
|
||||||
->where('school_year', $year);
|
->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) {
|
if ($onlyActive === true) {
|
||||||
$b = $b->where('active', 1);
|
$b = $b->where('active', 1);
|
||||||
} elseif ($onlyActive === false) {
|
} elseif ($onlyActive === false) {
|
||||||
@@ -122,7 +99,6 @@ class WhatsappGroupLinkModel extends Model
|
|||||||
'class_section_id' => $sectionId,
|
'class_section_id' => $sectionId,
|
||||||
'class_section_name' => $sectionName,
|
'class_section_name' => $sectionName,
|
||||||
'school_year' => trim($year),
|
'school_year' => trim($year),
|
||||||
'semester' => trim($sem),
|
|
||||||
'invite_link' => trim($inviteLink),
|
'invite_link' => trim($inviteLink),
|
||||||
'active' => $active ? 1 : 0,
|
'active' => $active ? 1 : 0,
|
||||||
];
|
];
|
||||||
@@ -131,7 +107,6 @@ class WhatsappGroupLinkModel extends Model
|
|||||||
$existing = $this->asArray()
|
$existing = $this->asArray()
|
||||||
->where('class_section_id', $sectionId)
|
->where('class_section_id', $sectionId)
|
||||||
->where('school_year', $payload['school_year'])
|
->where('school_year', $payload['school_year'])
|
||||||
->where('semester', $payload['semester'])
|
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
if ($existing) {
|
if ($existing) {
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ class WhatsappInviteLogModel extends Model
|
|||||||
/**
|
/**
|
||||||
* Log a successful send.
|
* 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([
|
return (bool) $this->insert([
|
||||||
'parent_id' => $parentId,
|
'parent_id' => $parentId,
|
||||||
@@ -58,7 +58,7 @@ class WhatsappInviteLogModel extends Model
|
|||||||
/**
|
/**
|
||||||
* Log a failure with error message.
|
* 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([
|
return (bool) $this->insert([
|
||||||
'parent_id' => $parentId,
|
'parent_id' => $parentId,
|
||||||
|
|||||||
@@ -262,9 +262,9 @@ $show_actions = false; // notified page hides actions by design
|
|||||||
|
|
||||||
// Initialize Bootstrap tooltips (for "View full" note)
|
// Initialize Bootstrap tooltips (for "View full" note)
|
||||||
document.addEventListener('DOMContentLoaded', function () {
|
document.addEventListener('DOMContentLoaded', function () {
|
||||||
if (window.bootstrap) {
|
if (window.bootstrap && bootstrap.Tooltip) {
|
||||||
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="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">
|
<table class="table table-sm table-striped table-hover align-middle fc-table-stack">
|
||||||
<thead class="table-light">
|
<thead class="table-light">
|
||||||
<tr>
|
<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>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<?php $imap = $f['invoice_map'] ?? []; ?>
|
<?php $imap = $f['invoice_map'] ?? []; ?>
|
||||||
<?php foreach ($f['payments'] as $p): ?>
|
<?php foreach ($f['payments'] as $p): ?>
|
||||||
<tr>
|
<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="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="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="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>
|
</tr>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
@@ -263,19 +263,20 @@
|
|||||||
<table class="table table-sm table-striped table-hover align-middle">
|
<table class="table table-sm table-striped table-hover align-middle">
|
||||||
<thead class="table-light">
|
<thead class="table-light">
|
||||||
<tr>
|
<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>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<?php $imap = $f['invoice_map'] ?? []; ?>
|
<?php $imap = $f['invoice_map'] ?? []; ?>
|
||||||
<?php foreach ($f['payments'] as $p): ?>
|
<?php foreach ($f['payments'] as $p): ?>
|
||||||
<tr>
|
<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['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($p['payment_method'] ?? '') ?></td>
|
||||||
<td><?= esc(!empty($p['payment_date']) ? local_date($p['payment_date'], 'm-d-Y') : '') ?></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>
|
</tr>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
@@ -41,8 +41,6 @@
|
|||||||
|
|
||||||
<!-- Bootstrap Bundle JS (for modal, tooltips, etc.) -->
|
<!-- 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>
|
<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) -->
|
<!-- ✅ Your validation logic (depends on jQuery & Select2) -->
|
||||||
<script type="module" src="/public/assets/js/validate_student.js"></script>
|
<script type="module" src="/public/assets/js/validate_student.js"></script>
|
||||||
<script src="<?= base_url('assets/js/modal_validation.js') ?>"></script>
|
<script src="<?= base_url('assets/js/modal_validation.js') ?>"></script>
|
||||||
|
|||||||
@@ -250,18 +250,19 @@ html, body { overflow-x: hidden; }
|
|||||||
</div>
|
</div>
|
||||||
</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>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
if (!window.bootstrap || !bootstrap.Tooltip) return;
|
||||||
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
|
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
|
||||||
tooltipTriggerList.forEach(function(tooltipTriggerEl) {
|
tooltipTriggerList.forEach(function(tooltipTriggerEl) {
|
||||||
new bootstrap.Tooltip(tooltipTriggerEl);
|
bootstrap.Tooltip.getOrCreateInstance(tooltipTriggerEl);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
</script>
|
</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 -->
|
<!-- Additional JS Libraries -->
|
||||||
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
|
<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>
|
<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>
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>
|
||||||
|
|
||||||
<!-- ✅ Custom JS -->
|
<!-- ✅ 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/modal_validation.js') ?>"></script>
|
||||||
<script src="<?= base_url('assets/js/validation.js') ?>" defer></script>
|
<script src="<?= base_url('assets/js/validation.js') ?>" defer></script>
|
||||||
|
|
||||||
@@ -45,4 +44,4 @@
|
|||||||
<?= $this->renderSection('scripts') ?>
|
<?= $this->renderSection('scripts') ?>
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -118,11 +118,6 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<br>
|
<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 -->
|
<!-- JavaScript for Phone and Email Validation -->
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
@@ -283,4 +278,4 @@
|
|||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<?= $this->endSection() ?>
|
<?= $this->endSection() ?>
|
||||||
|
|||||||
@@ -21,15 +21,17 @@
|
|||||||
<th>Date</th>
|
<th>Date</th>
|
||||||
<th>Invoice</th>
|
<th>Invoice</th>
|
||||||
<th class="text-end">Paid</th>
|
<th class="text-end">Paid</th>
|
||||||
<th class="text-end">Balance</th>
|
<th class="text-end">Invoice Balance</th>
|
||||||
<th>Method</th>
|
<th>Method</th>
|
||||||
<th>Status</th>
|
<th>Payment Status</th>
|
||||||
|
<th>Invoice Status</th>
|
||||||
|
<th>School Year</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<?php if (empty($payments)): ?>
|
<?php if (empty($payments)): ?>
|
||||||
<tr>
|
<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>
|
</tr>
|
||||||
<?php else: ?>
|
<?php else: ?>
|
||||||
<?php foreach ($payments as $p): ?>
|
<?php foreach ($payments as $p): ?>
|
||||||
@@ -40,9 +42,11 @@
|
|||||||
<?= $inv !== '' ? esc($inv) : ('#' . (int)($p['invoice_id'] ?? 0)) ?>
|
<?= $inv !== '' ? esc($inv) : ('#' . (int)($p['invoice_id'] ?? 0)) ?>
|
||||||
</td>
|
</td>
|
||||||
<td class="text-end">$<?= number_format((float)($p['paid_amount'] ?? 0), 2) ?></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['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>
|
</tr>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
|||||||
@@ -219,11 +219,12 @@
|
|||||||
<tr>
|
<tr>
|
||||||
<th>Paid Date</th>
|
<th>Paid Date</th>
|
||||||
<th>Paid Amount</th>
|
<th>Paid Amount</th>
|
||||||
<th>Balance</th>
|
<th>Invoice Balance</th>
|
||||||
<th>Payment Method</th>
|
<th>Payment Method</th>
|
||||||
<th>Check Number</th>
|
<th>Check Number</th>
|
||||||
<th>Installments</th>
|
<th>Installments</th>
|
||||||
<th>Status</th>
|
<th>Payment Status</th>
|
||||||
|
<th>Invoice Status</th>
|
||||||
<th>Check/Card File</th>
|
<th>Check/Card File</th>
|
||||||
<th>Action</th>
|
<th>Action</th>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -242,7 +243,7 @@
|
|||||||
?>
|
?>
|
||||||
<td><?= esc($paidAt) ?></td>
|
<td><?= esc($paidAt) ?></td>
|
||||||
<td>$<?= number_format((float)($payment['paid_amount'] ?? 0), 2) ?></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>
|
<td>
|
||||||
<?php if ($method === 'cash'): ?>
|
<?php if ($method === 'cash'): ?>
|
||||||
<span class="badge" style="background-color:#28a745;color:#fff;">Cash</span>
|
<span class="badge" style="background-color:#28a745;color:#fff;">Cash</span>
|
||||||
@@ -255,8 +256,9 @@
|
|||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</td>
|
</td>
|
||||||
<td><?= !empty($payment['check_number']) ? esc($payment['check_number']) : '-' ?></td>
|
<td><?= !empty($payment['check_number']) ? esc($payment['check_number']) : '-' ?></td>
|
||||||
<td><?= esc($payment['number_of_installments'] ?? '') ?></td>
|
<td><?= esc($payment['installment_seq'] ?? $payment['number_of_installments'] ?? '') ?></td>
|
||||||
<td><?= esc($payment['status'] ?? '') ?></td>
|
<td><?= esc($payment['payment_status'] ?? '') ?></td>
|
||||||
|
<td><?= esc($payment['invoice_status'] ?? '') ?></td>
|
||||||
<td>
|
<td>
|
||||||
<?php if (!empty($payment['check_file'])): ?>
|
<?php if (!empty($payment['check_file'])): ?>
|
||||||
<a href="#" data-bs-toggle="modal" data-bs-target="#checkModal<?= (int)$payment['id'] ?>">View</a> /
|
<a href="#" data-bs-toggle="modal" data-bs-target="#checkModal<?= (int)$payment['id'] ?>">View</a> /
|
||||||
|
|||||||
@@ -19,25 +19,29 @@
|
|||||||
<th>Date</th>
|
<th>Date</th>
|
||||||
<th>Invoice #</th>
|
<th>Invoice #</th>
|
||||||
<th class="text-end">Paid Amount</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>Method</th>
|
||||||
<th>Status</th>
|
<th>Payment Status</th>
|
||||||
|
<th>Invoice Status</th>
|
||||||
|
<th>School Year</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
<?php if (empty($payments)): ?>
|
<?php if (empty($payments)): ?>
|
||||||
<tr>
|
<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>
|
</tr>
|
||||||
<?php else: ?>
|
<?php else: ?>
|
||||||
<?php foreach ($payments as $p): ?>
|
<?php foreach ($payments as $p): ?>
|
||||||
<tr>
|
<tr>
|
||||||
<td><?= esc(!empty($p['payment_date']) ? local_date($p['payment_date'], 'm-d-Y') : '') ?></td>
|
<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['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['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>
|
</tr>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
|||||||
@@ -101,9 +101,10 @@
|
|||||||
<!-- Tooltip activation script (include once near bottom of page) -->
|
<!-- Tooltip activation script (include once near bottom of page) -->
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
if (!window.bootstrap || !bootstrap.Tooltip) return;
|
||||||
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
|
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
|
||||||
tooltipTriggerList.forEach(function(tooltipTriggerEl) {
|
tooltipTriggerList.forEach(function(tooltipTriggerEl) {
|
||||||
new bootstrap.Tooltip(tooltipTriggerEl);
|
bootstrap.Tooltip.getOrCreateInstance(tooltipTriggerEl);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -25,6 +25,26 @@ class TestableFinancialSystemLedgerCleanup extends FinancialSystemLedgerCleanup
|
|||||||
$this->calls[] = 'ensureIndexes';
|
$this->calls[] = 'ensureIndexes';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function backfillInstallmentSequence(): void
|
||||||
|
{
|
||||||
|
$this->calls[] = 'backfillInstallmentSequence';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function ensurePaymentDateHasTime(): void
|
||||||
|
{
|
||||||
|
$this->calls[] = 'ensurePaymentDateHasTime';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function repairPaymentInvoiceTerms(): void
|
||||||
|
{
|
||||||
|
$this->calls[] = 'repairPaymentInvoiceTerms';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function normalizePaymentStatuses(): void
|
||||||
|
{
|
||||||
|
$this->calls[] = 'normalizePaymentStatuses';
|
||||||
|
}
|
||||||
|
|
||||||
protected function ensureConfigurationDefaults(): void
|
protected function ensureConfigurationDefaults(): void
|
||||||
{
|
{
|
||||||
$this->calls[] = 'ensureConfigurationDefaults';
|
$this->calls[] = 'ensureConfigurationDefaults';
|
||||||
@@ -61,7 +81,11 @@ class FinancialSystemLedgerCleanupTest extends CIUnitTestCase
|
|||||||
|
|
||||||
$this->assertSame([
|
$this->assertSame([
|
||||||
'addInstallmentSequenceColumn',
|
'addInstallmentSequenceColumn',
|
||||||
|
'backfillInstallmentSequence',
|
||||||
|
'ensurePaymentDateHasTime',
|
||||||
'ensureIndexes',
|
'ensureIndexes',
|
||||||
|
'repairPaymentInvoiceTerms',
|
||||||
|
'normalizePaymentStatuses',
|
||||||
'ensureConfigurationDefaults',
|
'ensureConfigurationDefaults',
|
||||||
'archivePaypalTables',
|
'archivePaypalTables',
|
||||||
'refreshFinancialNavItems',
|
'refreshFinancialNavItems',
|
||||||
|
|||||||
@@ -11,9 +11,14 @@ class PaymentModelMetadataTest extends CIUnitTestCase
|
|||||||
{
|
{
|
||||||
$model = new PaymentModel();
|
$model = new PaymentModel();
|
||||||
$fields = self::getPrivateProperty($model, 'allowedFields');
|
$fields = self::getPrivateProperty($model, 'allowedFields');
|
||||||
|
$columns = self::getPrivateProperty($model, 'paymentColumns');
|
||||||
|
|
||||||
$this->assertContains('installment_seq', $fields);
|
foreach (['installment_seq', 'transaction_id', 'check_file'] as $field) {
|
||||||
$this->assertContains('transaction_id', $fields);
|
if (in_array($field, $columns, true)) {
|
||||||
$this->assertContains('check_file', $fields);
|
$this->assertContains($field, $fields);
|
||||||
|
} else {
|
||||||
|
$this->assertNotContains($field, $fields);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user