Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e06ccc9cc0 | |||
| c7f67da9bf | |||
| ed95286050 | |||
| ec9fca8c45 | |||
| ed11cccecc | |||
| 6e8da3cc2c | |||
| 384ae8b719 | |||
| 654453222f | |||
| a18e8b92a6 | |||
| 6444b61416 | |||
| 090cb88573 | |||
| 95bcefc3a9 | |||
| f24f4311e8 | |||
| 89913d7473 | |||
| 079c869477 | |||
| 9ee75fe4cc | |||
| fcfa56b3f5 |
@@ -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
|
||||
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
namespace App\Commands;
|
||||
|
||||
use App\Libraries\InvoiceLedgerService;
|
||||
use App\Models\InvoiceModel;
|
||||
use CodeIgniter\CLI\BaseCommand;
|
||||
use CodeIgniter\CLI\CLI;
|
||||
|
||||
class RecalculateInvoices extends BaseCommand
|
||||
{
|
||||
protected $group = 'Financial';
|
||||
protected $name = 'financial:recalculate-invoices';
|
||||
protected $description = 'Audits invoice totals against the centralized ledger and optionally writes the corrected values.';
|
||||
protected $usage = 'financial:recalculate-invoices [--commit] [--invoice-id=123] [--parent-id=456] [--school-year=2025-2026] [--semester=Fall]';
|
||||
protected $options = [
|
||||
'--commit' => 'Persist recalculated totals. Without this flag the command runs in dry-run mode.',
|
||||
'--invoice-id' => 'Only process a single invoice ID.',
|
||||
'--parent-id' => 'Only process invoices for one parent.',
|
||||
'--school-year' => 'Only process invoices for the specified school year.',
|
||||
'--semester' => 'Only process invoices for the specified semester.',
|
||||
];
|
||||
|
||||
public function run(array $params)
|
||||
{
|
||||
$options = $this->parseOptions($params);
|
||||
$invoiceModel = new InvoiceModel();
|
||||
$ledgerService = new InvoiceLedgerService();
|
||||
$invoiceIds = $this->loadInvoiceIds($invoiceModel, $options);
|
||||
|
||||
if ($invoiceIds === []) {
|
||||
CLI::write('No invoices matched the provided filters.', 'yellow');
|
||||
return;
|
||||
}
|
||||
|
||||
$commit = !empty($options['commit']);
|
||||
CLI::write(($commit ? 'Applying' : 'Dry-run auditing') . ' ' . count($invoiceIds) . ' invoice(s)...', 'yellow');
|
||||
|
||||
$changed = 0;
|
||||
$unchanged = 0;
|
||||
$errors = 0;
|
||||
|
||||
foreach ($invoiceIds as $invoiceId) {
|
||||
$invoice = $invoiceModel->find($invoiceId);
|
||||
if (!$invoice) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$calculation = $ledgerService->calculateInvoice($invoiceId);
|
||||
$diffs = $this->diffInvoice($invoice, $calculation);
|
||||
|
||||
if ($diffs === []) {
|
||||
$unchanged++;
|
||||
CLI::write('Invoice #' . $invoiceId . ' unchanged.', 'green');
|
||||
continue;
|
||||
}
|
||||
|
||||
$changed++;
|
||||
CLI::write('Invoice #' . $invoiceId . ' requires recalculation:', 'light_yellow');
|
||||
foreach ($diffs as $label => $values) {
|
||||
CLI::write(sprintf(
|
||||
' %s: %s -> %s',
|
||||
$label,
|
||||
(string) $values['from'],
|
||||
(string) $values['to']
|
||||
));
|
||||
}
|
||||
|
||||
if ($commit) {
|
||||
$ledgerService->recalculateInvoice($invoiceId);
|
||||
CLI::write(' saved', 'blue');
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$errors++;
|
||||
CLI::error('Invoice #' . $invoiceId . ' failed: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
CLI::newLine();
|
||||
CLI::write('Processed: ' . count($invoiceIds), 'white');
|
||||
CLI::write('Changed: ' . $changed, $changed > 0 ? 'yellow' : 'white');
|
||||
CLI::write('Unchanged: ' . $unchanged, 'green');
|
||||
CLI::write('Errors: ' . $errors, $errors > 0 ? 'red' : 'white');
|
||||
|
||||
if (!$commit) {
|
||||
CLI::write('Dry-run complete. Re-run with --commit to persist corrections.', 'light_blue');
|
||||
}
|
||||
}
|
||||
|
||||
protected function parseOptions(array $params): array
|
||||
{
|
||||
$options = [
|
||||
'commit' => false,
|
||||
'invoice-id' => null,
|
||||
'parent-id' => null,
|
||||
'school-year' => null,
|
||||
'semester' => null,
|
||||
];
|
||||
|
||||
foreach ($params as $param) {
|
||||
$value = trim((string) $param);
|
||||
if ($value === '--commit') {
|
||||
$options['commit'] = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!str_starts_with($value, '--') || !str_contains($value, '=')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$key, $raw] = explode('=', substr($value, 2), 2);
|
||||
if (array_key_exists($key, $options)) {
|
||||
$options[$key] = $raw;
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
protected function loadInvoiceIds(InvoiceModel $invoiceModel, array $options): array
|
||||
{
|
||||
$builder = $invoiceModel->select('id')->orderBy('id', 'ASC');
|
||||
|
||||
if (!empty($options['invoice-id'])) {
|
||||
$builder->where('id', (int) $options['invoice-id']);
|
||||
}
|
||||
|
||||
if (!empty($options['parent-id'])) {
|
||||
$builder->where('parent_id', (int) $options['parent-id']);
|
||||
}
|
||||
|
||||
if (!empty($options['school-year'])) {
|
||||
$builder->where('school_year', (string) $options['school-year']);
|
||||
}
|
||||
|
||||
if (!empty($options['semester'])) {
|
||||
$builder->where('semester', (string) $options['semester']);
|
||||
}
|
||||
|
||||
return array_map(
|
||||
static fn (array $row): int => (int) ($row['id'] ?? 0),
|
||||
$builder->findAll()
|
||||
);
|
||||
}
|
||||
|
||||
protected function diffInvoice(array $invoice, array $calculation): array
|
||||
{
|
||||
$fields = [
|
||||
'total_amount' => 'total_amount',
|
||||
'paid_amount' => 'paid_amount',
|
||||
'balance' => 'balance',
|
||||
'status' => 'status',
|
||||
'has_discount' => 'has_discount',
|
||||
];
|
||||
$diffs = [];
|
||||
|
||||
foreach ($fields as $invoiceKey => $calcKey) {
|
||||
$current = (string) ($invoice[$invoiceKey] ?? '');
|
||||
$recalculated = (string) ($calculation[$calcKey] ?? '');
|
||||
if ($current !== $recalculated) {
|
||||
$diffs[$invoiceKey] = [
|
||||
'from' => $current,
|
||||
'to' => $recalculated,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $diffs;
|
||||
}
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Commands;
|
||||
|
||||
use CodeIgniter\CLI\BaseCommand;
|
||||
use CodeIgniter\CLI\CLI;
|
||||
use App\Models\PayPalPaymentModel;
|
||||
use App\Models\PaymentModel;
|
||||
use App\Models\UserModel;
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\InvoiceModel;
|
||||
use App\Models\StudentModel;
|
||||
use App\Models\EnrollmentModel;
|
||||
|
||||
class SyncPaypalPayments extends BaseCommand
|
||||
{
|
||||
protected $group = 'Payments';
|
||||
protected $name = 'payments:sync-paypal';
|
||||
protected $description = 'Sync PayPal payments to internal payments table from paypal_payments';
|
||||
protected $configModel;
|
||||
protected $semester;
|
||||
protected $schoolYear;
|
||||
protected $paypalModel;
|
||||
protected $paymentModel;
|
||||
protected $userModel;
|
||||
protected $invoiceModel;
|
||||
protected $studentModel;
|
||||
protected $enrollmentModel;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->configModel = new ConfigurationModel();
|
||||
$this->paypalModel = new PayPalPaymentModel();
|
||||
$this->paymentModel = new PaymentModel();
|
||||
$this->userModel = new UserModel();
|
||||
$this->invoiceModel = new InvoiceModel();
|
||||
$this->studentModel = new StudentModel();
|
||||
$this->enrollmentModel = new EnrollmentModel();
|
||||
}
|
||||
|
||||
public function run(array $params)
|
||||
{
|
||||
$this->semester = (string) ($this->configModel->getConfig('semester') ?? '');
|
||||
$this->schoolYear = (string) ($this->configModel->getConfig('school_year') ?? '');
|
||||
|
||||
$dryRun = CLI::getOption('dry-run');
|
||||
$reportOnly = CLI::getOption('report-only');
|
||||
$mode = $reportOnly ? 'REPORT-ONLY' : ($dryRun ? 'DRY-RUN' : 'LIVE');
|
||||
|
||||
$paypalEntries = $this->paypalModel
|
||||
->where('status', 'COMPLETED')
|
||||
->where('synced', 0)
|
||||
->where('sync_attempts <', 3)
|
||||
->where('transaction_id IS NOT NULL')
|
||||
->findAll();
|
||||
|
||||
$syncedCount = 0;
|
||||
$failed = [];
|
||||
|
||||
foreach ($paypalEntries as $entry) {
|
||||
$parentId = null;
|
||||
$invoiceId = 0;
|
||||
|
||||
$users = $this->userModel->getUsersBySchoolId($entry['parent_school_id']);
|
||||
$user = $users[0] ?? null;
|
||||
|
||||
// Always increment sync_attempts unless report-only
|
||||
if (!$reportOnly) {
|
||||
$this->paypalModel->update($entry['id'], [
|
||||
'sync_attempts' => $entry['sync_attempts'] + 1
|
||||
]);
|
||||
}
|
||||
|
||||
if ($user) {
|
||||
$parentId = $user['id'];
|
||||
|
||||
$invoice = $this->invoiceModel->getInvoicesByParentId($parentId, $this->schoolYear);
|
||||
|
||||
if (!$reportOnly && !$dryRun) {
|
||||
if ($invoice) {
|
||||
$invoiceId = $invoice['id'];
|
||||
|
||||
$success = $this->processPayment(
|
||||
$invoiceId,
|
||||
$entry['amount'],
|
||||
'PayPal',
|
||||
null,
|
||||
$entry['transaction_id'],
|
||||
date('Y-m-d', strtotime($entry['created_at'])),
|
||||
$this->schoolYear,
|
||||
$this->semester
|
||||
);
|
||||
|
||||
if (!$success) {
|
||||
$failed[] = $entry['transaction_id'];
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
$this->paymentModel->insert([
|
||||
'parent_id' => $parentId,
|
||||
'invoice_id' => 0,
|
||||
'total_amount' => $entry['amount'],
|
||||
'paid_amount' => $entry['amount'],
|
||||
'balance' => 0.00,
|
||||
'number_of_installments' => 1,
|
||||
'transaction_id' => $entry['transaction_id'],
|
||||
'payment_method' => 'PayPal',
|
||||
'payment_date' => date('Y-m-d', strtotime($entry['created_at'])),
|
||||
'school_year' => $this->schoolYear,
|
||||
'semester' => $this->semester,
|
||||
'status' => 'Completed',
|
||||
'updated_by' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
// Mark as synced only in LIVE mode
|
||||
$this->paypalModel->update($entry['id'], ['synced' => 1]);
|
||||
}
|
||||
|
||||
$syncedCount++;
|
||||
} else {
|
||||
log_message('error', "[PAYPAL SYNC FAILED] No user found for parent_school_id: {$entry['parent_school_id']}");
|
||||
$failed[] = $entry['transaction_id'];
|
||||
}
|
||||
}
|
||||
|
||||
// === Logging ===
|
||||
log_message('info', "[$mode] PAYPAL SYNC: $syncedCount processed.");
|
||||
if (!empty($failed)) {
|
||||
log_message('error', "[$mode] PAYPAL SYNC Failed: " . implode(', ', $failed));
|
||||
}
|
||||
|
||||
// === CLI Output ===
|
||||
CLI::write("[$mode] $syncedCount PayPal payments processed.", 'green');
|
||||
if (!empty($failed)) {
|
||||
CLI::error("[$mode] Failed transactions: " . implode(', ', $failed));
|
||||
}
|
||||
|
||||
// === Email Report: Only if there's any update ===
|
||||
if ($syncedCount > 0 || !empty($failed)) {
|
||||
helper('email');
|
||||
$email = \Config\Services::email();
|
||||
$email->setTo('support@alrahmaisgl.org');
|
||||
$email->setFrom('no-parentsreply@alrahmaisgl.org', 'PayPal Sync Report');
|
||||
$email->setSubject("[$mode] PayPal Sync Report - " . date('Y-m-d H:i'));
|
||||
|
||||
$body = "PayPal Sync Mode: $mode\n\n";
|
||||
$body .= "$syncedCount PayPal payments processed.\n\n";
|
||||
|
||||
if (!empty($failed)) {
|
||||
$body .= count($failed) . " failed transactions:\n";
|
||||
$body .= implode("\n", $failed);
|
||||
} else {
|
||||
$body .= "No failed transactions.\n";
|
||||
}
|
||||
|
||||
$email->setMessage(nl2br($body));
|
||||
|
||||
if ($email->send()) {
|
||||
CLI::write("[$mode] Email report sent successfully.", 'yellow');
|
||||
} else {
|
||||
CLI::error("[$mode] Failed to send email report.");
|
||||
log_message('error', 'Email send error: ' . $email->printDebugger(['headers']));
|
||||
}
|
||||
} else {
|
||||
log_message('info', "[$mode] No PayPal sync updates. Email not sent.");
|
||||
CLI::write("[$mode] No changes to report. Email not sent.", 'blue');
|
||||
}
|
||||
}
|
||||
|
||||
private function processPayment($invoiceId, $amount, $paymentMethod, $checkFile = null, $transactionId = null, $paymentDate = null, $schoolYear = null, $semester = null)
|
||||
{
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$transactionId = $transactionId ?? 'INV-' . $invoiceId . '-' . time();
|
||||
$paymentDate = $paymentDate ?? date('Y-m-d');
|
||||
|
||||
$newPaid = $invoice['paid_amount'] + $amount;
|
||||
$newBalance = $invoice['balance'] - $amount;
|
||||
|
||||
$invoiceUpdateData = [
|
||||
'paid_amount' => $newPaid,
|
||||
'balance' => $newBalance,
|
||||
'status' => ($newBalance <= 0) ? 'Paid' : $invoice['status'],
|
||||
];
|
||||
|
||||
if (!$this->invoiceModel->update($invoiceId, $invoiceUpdateData)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->paymentModel->insert([
|
||||
'parent_id' => $invoice['parent_id'],
|
||||
'invoice_id' => $invoiceId,
|
||||
'total_amount' => $invoice['total_amount'],
|
||||
'paid_amount' => $amount,
|
||||
'balance' => $newBalance,
|
||||
'number_of_installments' => 1,
|
||||
'transaction_id' => $transactionId,
|
||||
'payment_method' => $paymentMethod,
|
||||
'payment_date' => $paymentDate,
|
||||
'status' => ($newBalance <= 0) ? 'Full' : 'Partial',
|
||||
'check_file' => $checkFile,
|
||||
'updated_by' => null, // Avoid using session()->get() in CLI
|
||||
'school_year' => $schoolYear,
|
||||
'semester' => $semester
|
||||
]);
|
||||
|
||||
$this->updateEnrollmentStatusIfPaid($invoiceId, $schoolYear);
|
||||
return true;
|
||||
}
|
||||
|
||||
private function updateEnrollmentStatusIfPaid($invoiceId, $schoolYear)
|
||||
{
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice || $invoice['balance'] > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$students = $this->studentModel->where('parent_id', $invoice['parent_id'])
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
|
||||
foreach ($students as $student) {
|
||||
$this->enrollmentModel->set(['enrollment_status' => 'enrolled'])
|
||||
->where('student_id', $student['id'])
|
||||
->update();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,11 +16,11 @@ class Commands extends BaseService
|
||||
\App\Commands\CleanupPasswordResets::class,
|
||||
\App\Commands\ConfigUpdate::class,
|
||||
\App\Commands\DeleteInactiveUsers::class,
|
||||
\App\Commands\RecalculateInvoices::class,
|
||||
\App\Commands\SendAbsenteesSummary::class,
|
||||
\App\Commands\SendLatesSummary::class,
|
||||
\App\Commands\SendMonthlyPaymentNotifications::class,
|
||||
\App\Commands\SendTestPaymentNotification::class,
|
||||
\App\Commands\SyncPaypalPayments::class,
|
||||
\App\Commands\RecalculateAttendance::class,
|
||||
];
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ class Filters extends BaseConfig
|
||||
'cleanupScheduler' => \App\Filters\CleanupScheduler::class,
|
||||
'permission' => \App\Filters\PermissionFilter::class,
|
||||
'timezone' => \App\Filters\TimezoneFilter::class,
|
||||
'schoolYear' => \App\Filters\RequireSchoolYearFilter::class,
|
||||
];
|
||||
|
||||
|
||||
@@ -47,10 +48,6 @@ class Filters extends BaseConfig
|
||||
'sanitizeinput',
|
||||
'invalidchars',
|
||||
'csrf' => ['except' => [
|
||||
// Webhooks / integrations
|
||||
'api/paypal-webhook',
|
||||
'index.php/api/paypal-webhook',
|
||||
|
||||
// WhatsApp membership management (legacy allowances retained)
|
||||
'whatsapp/update-membership',
|
||||
'index.php/whatsapp/update-membership',
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Config;
|
||||
|
||||
use CodeIgniter\Config\BaseConfig;
|
||||
|
||||
class PaypalConfig extends BaseConfig
|
||||
{
|
||||
// PayPal API Credentials
|
||||
public $paypalClientId = 'YOUR_PAYPAL_CLIENT_ID';
|
||||
public $paypalSecret = 'YOUR_PAYPAL_SECRET';
|
||||
public $paypalMode = 'sandbox'; // Change to 'live' when moving to production
|
||||
}
|
||||
+85
-80
@@ -257,15 +257,17 @@ $routes->post('administrator/sections/auto-distribute', 'View\StudentController:
|
||||
$routes->get('administrator/sections/promotion-totals', 'View\StudentController::promotionTotalsApi');
|
||||
|
||||
|
||||
$routes->get('refunds/list', 'View\RefundController::listRefunds');
|
||||
$routes->post('refunds/request', 'View\RefundController::requestRefund');
|
||||
$routes->post('refunds/approve/(:num)', 'View\RefundController::approveRefund/$1');
|
||||
$routes->post('refunds/pay/(:num)', 'View\RefundController::payRefund/$1');
|
||||
$routes->post('refunds/updateStatus/(:num)', 'View\RefundController::updateStatus/$1');
|
||||
$routes->post('refunds/processRefunds', 'View\RefundController::processRefunds');
|
||||
$routes->post('refunds/updateStatus', 'View\RefundController::updateStatus');
|
||||
$routes->post('refunds/updatePayment', 'View\RefundController::updatePayment');
|
||||
$routes->post('refunds/recalculateOverpayments', 'View\RefundController::recalculateOverpayments');
|
||||
$routes->get('refunds/list', 'View\RefundController::listRefunds', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('refunds/request', 'View\RefundController::requestRefund', ['filter' => 'auth:create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->post('refunds/approve/(:num)', 'View\RefundController::approveRefund/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/pay/(:num)', 'View\RefundController::payRefund/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/updateStatus/(:num)', 'View\RefundController::updateStatus/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/processRefunds', 'View\RefundController::processRefunds', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/updateStatus', 'View\RefundController::updateStatus', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/updatePayment', 'View\RefundController::updatePayment', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/recalculateOverpayments', 'View\RefundController::recalculateOverpayments', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('refunds/file/(:num)', 'View\RefundController::serveRefundFile/$1', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('refunds/file/(:num)/(:segment)', 'View\RefundController::serveRefundFile/$1/$2', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||
|
||||
|
||||
|
||||
@@ -528,10 +530,17 @@ $routes->post('grading/decisions/generate', 'View\GradingController::generateAll
|
||||
$routes->get('grading/below-60/decisions', 'View\GradingController::belowSixtyDecisions', ['filter' => 'auth:read']);
|
||||
$routes->post('grading/below-60/decisions/save', 'View\GradingController::saveBelowSixtyDecision', ['filter' => 'auth:read']);
|
||||
$routes->get('grading/below-60/decisions/student-details', 'View\GradingController::studentDecisionDetails', ['filter' => 'auth:read']);
|
||||
$routes->get('grading/below-60/decisions/email/preview', 'View\GradingController::previewDecisionEmail', ['filter' => 'auth:read']);
|
||||
$routes->get('grading/below-60/decisions/email/edit', 'View\GradingController::editDecisionEmail', ['filter' => 'auth:read']);
|
||||
$routes->post('grading/below-60/decisions/email', 'View\GradingController::sendDecisionEmail', ['filter' => 'auth:read']);
|
||||
$routes->get(
|
||||
'grading/below-60/decisions/email/preview',
|
||||
'View\GradingController::previewBelowSixtyDecisionEmail',
|
||||
['filter' => 'auth:read']
|
||||
);
|
||||
|
||||
$routes->post(
|
||||
'grading/below-60/decisions/email',
|
||||
'View\GradingController::sendBelowSixtyDecisionEmail',
|
||||
['filter' => 'auth:read']
|
||||
);
|
||||
|
||||
// Final part
|
||||
$routes->get('grading/(:segment)/(:num)/(:num)', 'View\GradingController::show/$1/$2/$3');
|
||||
@@ -579,19 +588,19 @@ $routes->post('invoices/updateStatus/(:num)', 'View\InvoiceController::updateSta
|
||||
// app/Config/Routes.php
|
||||
$routes->group('payment', ['filter' => 'auth'], static function ($routes) {
|
||||
// Read
|
||||
$routes->get('manual_pay', 'View\PaymentController::manualPaySearch', ['filter' => 'auth:read']);
|
||||
$routes->get('manual_pay_suggest', 'View\PaymentController::manualPaySuggest', ['filter' => 'auth:read']);
|
||||
$routes->get('manual_pay', 'View\PaymentController::manualPaySearch', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('manual_pay_suggest', 'View\PaymentController::manualPaySuggest', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||
|
||||
// Create
|
||||
$routes->post('manual_pay', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:create']);
|
||||
$routes->post('manual_pay', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:create_payment|create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
|
||||
// Update
|
||||
$routes->post('manual_pay_edit', 'View\PaymentController::manualPayEdit', ['filter' => 'auth:update']);
|
||||
$routes->post('manual_pay_update', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:update']);
|
||||
$routes->post('manual_pay_edit', 'View\PaymentController::manualPayEdit', ['filter' => 'auth:update_payment|update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('manual_pay_update', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:create_payment|create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
|
||||
// Read (serve files)
|
||||
$routes->get('serveCheckFile/(:any)/(:any)', 'View\PaymentController::serveCheckFile/$1/$2', ['filter' => 'auth:read']);
|
||||
$routes->get('serveCheckFile/(:any)', 'View\PaymentController::serveCheckFile/$1', ['filter' => 'auth:read']);
|
||||
$routes->get('file/(:num)/(:segment)', 'View\PaymentController::servePaymentFile/$1/$2', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('file/(:num)', 'View\PaymentController::servePaymentFile/$1', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||
});
|
||||
|
||||
|
||||
@@ -634,9 +643,14 @@ $routes->group('admin', ['filter' => 'auth'], static function ($routes) {
|
||||
$routes->post('admin/broadcast-email/upload-image', 'View\BroadcastEmailController::uploadImage');
|
||||
|
||||
|
||||
$routes->get('payment/financial_report', 'View\FinancialController::financialReport');
|
||||
$routes->get('financial-report/financialReportSummary', 'View\FinancialController::financialReportSummary');
|
||||
$routes->get('payment/download_csv', 'View\FinancialController::downloadCsv');
|
||||
$routes->get('payment/financial_report', 'View\FinancialController::financialReport', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('financial-report/financialReportSummary', 'View\FinancialController::financialReportSummary', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('financial-report/downloadSummaryCsv', 'View\FinancialController::downloadSummaryCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('financial-report/downloadSummaryAllDetailsCsv', 'View\FinancialController::downloadSummaryAllDetailsCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('payment/download_csv', 'View\FinancialController::downloadCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('administrator/tuition-forecast', 'View\TuitionForecastController::index', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->post('administrator/tuition-forecast/calculate', 'View\TuitionForecastController::calculate', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('administrator/tuition-forecast/export', 'View\TuitionForecastController::exportCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('reports/downloadFinancialReport', 'View\FinancialController::downloadFinancialReport');
|
||||
// Financial APIs (JSON)
|
||||
$routes->get('api/financial/report', 'View\FinancialController::financialReportData', ['filter' => 'auth']);
|
||||
@@ -647,27 +661,27 @@ $routes->get('payment/unpaid-parents', 'View\FinancialController::unpaidParents'
|
||||
$routes->get('api/financial/unpaid-parents', 'View\FinancialController::unpaidParents', ['filter' => 'auth:view_invoice']);
|
||||
|
||||
|
||||
$routes->get('expenses/index', 'View\ExpenseController::index');
|
||||
$routes->get('expenses/create', 'View\ExpenseController::create');
|
||||
$routes->post('expenses/store', 'View\ExpenseController::store');
|
||||
$routes->post('expenses/updateStatus', 'View\ExpenseController::updateStatus');
|
||||
$routes->get('expenses/index', 'View\ExpenseController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('expenses/create', 'View\ExpenseController::create', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('expenses/store', 'View\ExpenseController::store', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->post('expenses/updateStatus', 'View\ExpenseController::updateStatus', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
|
||||
$routes->get('reimbursements/index', 'View\ReimbursementController::index');
|
||||
$routes->get('reimbursements/create', 'View\ReimbursementController::create');
|
||||
$routes->post('reimbursements/store', 'View\ReimbursementController::store');
|
||||
$routes->get('reimbursements/under-processing', 'View\ReimbursementController::underProcessing');
|
||||
$routes->post('reimbursements/mark-donation', 'View\ReimbursementController::markDonation');
|
||||
$routes->post('reimbursements/batch/create', 'View\ReimbursementController::createBatch');
|
||||
$routes->post('reimbursements/batch/update', 'View\ReimbursementController::updateBatchAssignment');
|
||||
$routes->post('reimbursements/batch/lock', 'View\ReimbursementController::lockBatch');
|
||||
$routes->post('reimbursements/batch/admin-file/upload', 'View\ReimbursementController::uploadBatchAdminFile');
|
||||
$routes->get('reimbursements/batch/admin-file/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1');
|
||||
$routes->get('reimbursements/batch/admin-file/(:segment)/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1/$2');
|
||||
$routes->post('reimbursements/batch/send', 'View\ReimbursementController::sendBatchEmail');
|
||||
$routes->get('reimbursements/batch/export', 'View\ReimbursementController::exportBatch');
|
||||
$routes->post('reimbursements/process', 'View\ReimbursementController::process');
|
||||
$routes->get('reimbursements/export', 'View\ReimbursementController::export');
|
||||
$routes->get('reimbursements', 'View\ReimbursementController::index');
|
||||
$routes->get('reimbursements/index', 'View\ReimbursementController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('reimbursements/create', 'View\ReimbursementController::create', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('reimbursements/store', 'View\ReimbursementController::store', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->get('reimbursements/under-processing', 'View\ReimbursementController::underProcessing', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('reimbursements/mark-donation', 'View\ReimbursementController::markDonation', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('reimbursements/batch/create', 'View\ReimbursementController::createBatch', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->post('reimbursements/batch/update', 'View\ReimbursementController::updateBatchAssignment', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('reimbursements/batch/lock', 'View\ReimbursementController::lockBatch', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('reimbursements/batch/admin-file/upload', 'View\ReimbursementController::uploadBatchAdminFile', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('reimbursements/batch/admin-file/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('reimbursements/batch/admin-file/(:segment)/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1/$2', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('reimbursements/batch/send', 'View\ReimbursementController::sendBatchEmail', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('reimbursements/batch/export', 'View\ReimbursementController::exportBatch', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('reimbursements/process', 'View\ReimbursementController::process', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('reimbursements/export', 'View\ReimbursementController::export', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('reimbursements', 'View\ReimbursementController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
|
||||
// Health check (upload dirs + DB timezone columns)
|
||||
$routes->get('admin/health', 'View\HealthController::index');
|
||||
@@ -729,19 +743,9 @@ $routes->get('payments/getByParent/(:num)', 'View\PaymentController::getByParent
|
||||
$routes->get('payments/create', 'View\PaymentController::create');
|
||||
$routes->post('payments/updateBalance/(:num)', 'View\PaymentController::updateBalance/$1');
|
||||
|
||||
// Web View Routes for Payment Transactions
|
||||
$routes->get('payment_transactions/getByPayment/(:num)', 'View\PaymentTransactionController::getByPayment/$1');
|
||||
$routes->get('payment_transactions/create', 'View\PaymentTransactionController::create');
|
||||
$routes->post('payment_transactions/updateStatus/(:num)', 'View\PaymentTransactionController::updateStatus/$1');
|
||||
|
||||
// Routes for PayPal integration
|
||||
$routes->get('payments/createPaypalPayment/(:num)', 'View\PaymentController::createPaypalPayment/$1');
|
||||
$routes->get('payments/executePaypalPayment', 'View\PaymentController::executePaypalPayment');
|
||||
$routes->get('payments/cancelPaypalPayment', 'View\PaymentController::cancelPaypalPayment');
|
||||
|
||||
// Routes for payment pages
|
||||
$routes->get('payments/view/(:num)', 'View\PaymentController::viewPayment/$1');
|
||||
$routes->post('payments/createPaypalPayment/(:num)', 'View\PaymentController::createPaypalPayment/$1');
|
||||
$routes->get('payment/get_enrolled_students/(:num)', 'View\PaymentController::getEnrolledStudents/$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']);
|
||||
|
||||
// Payment Notification Management
|
||||
$routes->get('payment/notification_management', 'View\PaymentNotificationController::index', ['filter' => 'auth:view_invoice']);
|
||||
@@ -961,15 +965,6 @@ $routes->group('inventory', ['filter' => 'csrf'], static function ($routes) {
|
||||
$routes->get('admin/enrollment/new-students', 'View\AdministratorController::showNewStudents', ['filter' => 'auth:view_new_students']);
|
||||
|
||||
|
||||
//Paypal transactions
|
||||
$routes->post('api/paypal-webhook', 'Api\PaypalWebhook::handle');
|
||||
$routes->get('administrator/paypal_transactions', 'View\PaypalTransactionsController::index');
|
||||
$routes->get('administrator/paypal_transactions/export', 'View\PaypalTransactionsController::exportCsv');
|
||||
$routes->get('admin/paypal-transactions', 'View\PaypalTransactionsController::index');
|
||||
$routes->get('admin/paypal-transactions/export', 'View\PaypalTransactionsController::exportCsv');
|
||||
|
||||
|
||||
|
||||
//Emergency Contact
|
||||
$routes->get('administrator/emergency_contact', 'View\EmergencyContactController::index');
|
||||
$routes->get('administrator/emergency_contact/edit/(:num)', 'View\EmergencyContactController::edit/$1');
|
||||
@@ -1048,16 +1043,16 @@ $routes->get('family', 'View\FamilyAdminController::index');
|
||||
//////////////////////////////////////////////////////////
|
||||
|
||||
//upload files
|
||||
$routes->get('receipts/(:any)', 'View\FilesController::receipt/$1');
|
||||
$routes->get('reimbreceipts/(:any)', 'View\FilesController::reimb/$1'); // serves from writable/uploads/reimbursements
|
||||
$routes->get('receipts/(:any)', 'View\FilesController::receipt/$1', ['filter' => 'auth']);
|
||||
$routes->get('reimbreceipts/(:any)', 'View\FilesController::reimb/$1', ['filter' => 'auth']); // serves from writable/uploads/reimbursements
|
||||
$routes->get('early-dismissal-signatures/(:any)', 'View\FilesController::earlyDismissalSignature/$1');
|
||||
// Expenses
|
||||
$routes->get('expenses/edit/(:num)', 'View\ExpenseController::edit/$1');
|
||||
$routes->post('expenses/update/(:num)', 'View\ExpenseController::update/$1');
|
||||
$routes->get('expenses/edit/(:num)', 'View\ExpenseController::edit/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('expenses/update/(:num)', 'View\ExpenseController::update/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
|
||||
// Reimbursements
|
||||
$routes->get('reimbursements/edit/(:num)', 'View\ReimbursementController::edit/$1');
|
||||
$routes->post('reimbursements/update/(:num)', 'View\ReimbursementController::update/$1');
|
||||
$routes->get('reimbursements/edit/(:num)', 'View\ReimbursementController::edit/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('reimbursements/update/(:num)', 'View\ReimbursementController::update/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
|
||||
|
||||
|
||||
@@ -1137,6 +1132,22 @@ $routes->post('/configuration/addConfig', 'View\ConfigurationController::addConf
|
||||
$routes->match(['get', 'post'], '/configuration/editConfig/(:num)', 'View\ConfigurationController::editConfig/$1');
|
||||
$routes->post('/configuration/deleteConfig/(:num)', 'View\ConfigurationController::deleteConfig/$1');
|
||||
|
||||
// School-year management
|
||||
$routes->group('administrator/school-years', ['filter' => 'auth:admin'], static function ($routes) {
|
||||
$routes->get('', 'Administrator\SchoolYearController::index');
|
||||
$routes->post('store', 'Administrator\SchoolYearController::store');
|
||||
$routes->post('(:num)/update', 'Administrator\SchoolYearController::update/$1');
|
||||
$routes->post('(:num)/activate', 'Administrator\SchoolYearController::activate/$1');
|
||||
$routes->post('(:num)/delete-draft', 'Administrator\SchoolYearController::deleteDraft/$1');
|
||||
$routes->post('(:num)/archive', 'Administrator\SchoolYearController::archive/$1');
|
||||
$routes->post('(:num)/reopen', 'Administrator\SchoolYearController::reopen/$1');
|
||||
$routes->get('(:num)/closing/preview', 'Administrator\SchoolYearClosingController::preview/$1');
|
||||
$routes->post('(:num)/closing/start', 'Administrator\SchoolYearClosingController::start/$1');
|
||||
$routes->post('(:num)/closing/execute', 'Administrator\SchoolYearClosingController::execute/$1');
|
||||
$routes->post('(:num)/closing/complete', 'Administrator\SchoolYearClosingController::complete/$1');
|
||||
$routes->post('(:num)/closing/cancel', 'Administrator\SchoolYearClosingController::cancel/$1');
|
||||
});
|
||||
|
||||
// Route for Attendance Comment Templates
|
||||
$routes->get('/administrator/attendance-templates', 'View\AttendanceCommentTemplateController::index');
|
||||
$routes->get('/api/attendance-templates', 'View\AttendanceCommentTemplateController::listData');
|
||||
@@ -1202,16 +1213,15 @@ $routes->get('/terms_of_service', 'View\PageController::termsOfService');
|
||||
$routes->get('/help_center', 'View\PageController::helpCenter');
|
||||
|
||||
//payment
|
||||
$routes->get('/payment', 'View\PaymentController::redirectPage');
|
||||
$routes->get('/payment/paypal', 'View\PaymentController::paypal');
|
||||
$routes->get('/payment', 'View\PaymentController::redirectPage', ['filter' => 'auth:parent']);
|
||||
$routes->get('/payment/manual', 'View\PaymentController::manual');
|
||||
$routes->post('/payment/manual', 'View\PaymentController::manual');
|
||||
|
||||
// Voucher management
|
||||
$routes->get('discounts/list', 'View\DiscountController::listVouchers');
|
||||
$routes->match(['get', 'post'], 'discount/create', 'View\DiscountController::createVoucher');
|
||||
$routes->match(['get', 'post'], 'discount/editVoucher/(:num)', 'View\DiscountController::editVoucher/$1');
|
||||
$routes->match(['get', 'post'], 'discount/apply', 'View\DiscountController::applyVoucher');
|
||||
$routes->get('discounts/list', 'View\DiscountController::listVouchers', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->match(['get', 'post'], 'discount/create', 'View\DiscountController::createVoucher', ['filter' => 'auth:create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->match(['get', 'post'], 'discount/editVoucher/(:num)', 'View\DiscountController::editVoucher/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->match(['get', 'post'], 'discount/apply', 'View\DiscountController::applyVoucher', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
|
||||
|
||||
|
||||
@@ -1555,11 +1565,6 @@ $routes->group('api/v1', ['filter' => 'apiAuth', 'namespace' => 'App\Controllers
|
||||
$routes->get('class-preparation/(:num)', 'View\SupportController::show/$1');
|
||||
$routes->post('class-preparation/(:num)/mark-printed', 'View\SupportController::markPrinted/$1');
|
||||
|
||||
// PayPal Transactions
|
||||
$routes->get('paypal-transactions', 'View\UserController::index');
|
||||
$routes->get('paypal-transactions/(:num)', 'View\SupportController::show/$1');
|
||||
$routes->get('paypal-transactions/transaction/(:segment)', 'View\SupportController::getByTransactionId/$1');
|
||||
|
||||
// Stats
|
||||
$routes->get('stats', 'View\UserController::index');
|
||||
|
||||
|
||||
@@ -180,4 +180,66 @@ class Services extends BaseService
|
||||
$http = static::curlrequest($options);
|
||||
return new \App\Services\ApiClient($http, $apiConfig);
|
||||
}
|
||||
|
||||
public static function schoolYearContext(bool $getShared = true): \App\Services\SchoolYearContextService
|
||||
{
|
||||
if ($getShared) {
|
||||
return static::getSharedInstance('schoolYearContext');
|
||||
}
|
||||
|
||||
return new \App\Services\SchoolYearContextService(
|
||||
model(\App\Models\SchoolYearModel::class)
|
||||
);
|
||||
}
|
||||
|
||||
public static function schoolYearWriteGuard(bool $getShared = true): \App\Services\SchoolYearWriteGuard
|
||||
{
|
||||
if ($getShared) {
|
||||
return static::getSharedInstance('schoolYearWriteGuard');
|
||||
}
|
||||
|
||||
return new \App\Services\SchoolYearWriteGuard();
|
||||
}
|
||||
|
||||
public static function schoolYearValidation(bool $getShared = true): \App\Services\SchoolYearValidationService
|
||||
{
|
||||
if ($getShared) {
|
||||
return static::getSharedInstance('schoolYearValidation');
|
||||
}
|
||||
|
||||
return new \App\Services\SchoolYearValidationService(
|
||||
model(\App\Models\SchoolYearModel::class)
|
||||
);
|
||||
}
|
||||
|
||||
public static function schoolYearManagement(bool $getShared = true): \App\Services\SchoolYearManagementService
|
||||
{
|
||||
if ($getShared) {
|
||||
return static::getSharedInstance('schoolYearManagement');
|
||||
}
|
||||
|
||||
return new \App\Services\SchoolYearManagementService(
|
||||
model(\App\Models\SchoolYearModel::class),
|
||||
model(\App\Models\ConfigurationModel::class),
|
||||
model(\App\Models\SchoolYearTransitionLogModel::class),
|
||||
model(\App\Models\SchoolYearClosingBatchModel::class),
|
||||
static::schoolYearValidation(),
|
||||
\Config\Database::connect()
|
||||
);
|
||||
}
|
||||
|
||||
public static function schoolYearClosing(bool $getShared = true): \App\Services\SchoolYearClosingService
|
||||
{
|
||||
if ($getShared) {
|
||||
return static::getSharedInstance('schoolYearClosing');
|
||||
}
|
||||
|
||||
return new \App\Services\SchoolYearClosingService(
|
||||
model(\App\Models\SchoolYearModel::class),
|
||||
model(\App\Models\SchoolYearClosingBatchModel::class),
|
||||
model(\App\Models\SchoolYearClosingItemModel::class),
|
||||
static::schoolYearManagement(),
|
||||
\Config\Database::connect()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Administrator;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Models\SchoolYearModel;
|
||||
use Throwable;
|
||||
|
||||
class SchoolYearClosingController extends BaseController
|
||||
{
|
||||
public function preview(int $id)
|
||||
{
|
||||
try {
|
||||
$targetId = $this->normalizeInt($this->request->getGet('target_school_year_id'));
|
||||
|
||||
return view('school_years/closing_preview', [
|
||||
'preview' => service('schoolYearClosing')->preview($id, $targetId),
|
||||
'latestBatch' => service('schoolYearClosing')->latestBatch($id),
|
||||
'schoolYears' => (new SchoolYearModel())->orderBy('name', 'DESC')->findAll(),
|
||||
]);
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function start(int $id)
|
||||
{
|
||||
try {
|
||||
$targetId = $this->normalizeInt($this->request->getPost('target_school_year_id'));
|
||||
if ($targetId === null) {
|
||||
return redirect()->back()->with('error', 'Select a target school year.');
|
||||
}
|
||||
|
||||
service('schoolYearClosing')->start($id, $targetId, $this->userId());
|
||||
return redirect()->to('/administrator/school-years/' . $id . '/closing/preview')->with('success', 'Closing started.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function execute(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearClosing')->execute($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years/' . $id . '/closing/preview')->with('success', 'Carry-forward batch executed.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function complete(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearClosing')->complete($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'School year closed.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function cancel(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearClosing')->cancel($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'Closing cancelled.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function normalizeInt(mixed $value): ?int
|
||||
{
|
||||
return is_numeric($value) && (int) $value > 0 ? (int) $value : null;
|
||||
}
|
||||
|
||||
private function userId(): ?int
|
||||
{
|
||||
$id = session('user_id') ?? session('id');
|
||||
|
||||
return is_numeric($id) ? (int) $id : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Administrator;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Support\SchoolYear\SchoolYearStatus;
|
||||
use Throwable;
|
||||
|
||||
class SchoolYearController extends BaseController
|
||||
{
|
||||
private SchoolYearModel $schoolYearModel;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->schoolYearModel = new SchoolYearModel();
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
$schoolYears = $this->schoolYearModel
|
||||
->orderBy('name', 'DESC')
|
||||
->findAll();
|
||||
|
||||
$activeYear = null;
|
||||
$nextDraftYear = null;
|
||||
$closingYear = null;
|
||||
$archivedCount = 0;
|
||||
|
||||
foreach ($schoolYears as $year) {
|
||||
$status = (string) ($year['status'] ?? '');
|
||||
if ($status === SchoolYearStatus::ACTIVE && $activeYear === null) {
|
||||
$activeYear = $year;
|
||||
}
|
||||
if ($status === SchoolYearStatus::DRAFT && $nextDraftYear === null) {
|
||||
$nextDraftYear = $year;
|
||||
}
|
||||
if ($status === SchoolYearStatus::CLOSING && $closingYear === null) {
|
||||
$closingYear = $year;
|
||||
}
|
||||
if ($status === SchoolYearStatus::ARCHIVED) {
|
||||
$archivedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return view('school_years/index', [
|
||||
'schoolYears' => $schoolYears,
|
||||
'statuses' => SchoolYearStatus::ALL,
|
||||
'activeYear' => $activeYear,
|
||||
'nextDraftYear' => $nextDraftYear,
|
||||
'closingYear' => $closingYear,
|
||||
'archivedCount' => $archivedCount,
|
||||
'latestTransitions' => service('schoolYearManagement')->latestTransitionByYear(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store()
|
||||
{
|
||||
try {
|
||||
service('schoolYearManagement')->createDraft($this->request->getPost(), $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'Draft school year created.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->withInput()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function update(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearManagement')->updateMetadata($id, $this->request->getPost(), $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'School year metadata updated.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->back()->withInput()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function activate(int $id)
|
||||
{
|
||||
try {
|
||||
if ($this->request->getPost('confirm_activation') !== '1') {
|
||||
return redirect()->to('/administrator/school-years')->with('error', 'Activation confirmation is required.');
|
||||
}
|
||||
|
||||
service('schoolYearManagement')->activate($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'School year activated. Any previous active year is now in closing.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteDraft(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearManagement')->deleteDraft($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'Draft school year deleted.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function archive(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearManagement')->archive($id, $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'School year archived.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function reopen(int $id)
|
||||
{
|
||||
try {
|
||||
service('schoolYearManagement')->reopen($id, (string) $this->request->getPost('reason'), $this->userId());
|
||||
return redirect()->to('/administrator/school-years')->with('success', 'School year reopened.');
|
||||
} catch (Throwable $e) {
|
||||
return redirect()->to('/administrator/school-years')->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function userId(): ?int
|
||||
{
|
||||
$id = session('user_id') ?? session('id');
|
||||
|
||||
return is_numeric($id) ? (int) $id : null;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ use CodeIgniter\HTTP\RequestInterface;
|
||||
use CodeIgniter\HTTP\ResponseInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use App\Services\ApiClient;
|
||||
use App\Support\SchoolYear\SchoolYearContext;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Class BaseController
|
||||
@@ -88,6 +90,27 @@ abstract class BaseController extends Controller
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
protected function resolveSchoolYearContext(?int $routeSchoolYearId = null): SchoolYearContext
|
||||
{
|
||||
try {
|
||||
return service('schoolYearContext')->resolve($this->request, $routeSchoolYearId);
|
||||
} catch (Throwable $e) {
|
||||
log_message('warning', 'School-year resolution failed: {message}', [
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
protected function assertSchoolYearWritable(
|
||||
SchoolYearContext $context,
|
||||
bool $allowDraftForAdmin = false,
|
||||
bool $isAdmin = false
|
||||
): void {
|
||||
service('schoolYearWriteGuard')->assertWritable($context, $allowDraftForAdmin, $isAdmin);
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
|
||||
@@ -730,18 +730,15 @@ class AdministratorController extends BaseController
|
||||
->join('users u', 'u.id = tc.teacher_id', 'left')
|
||||
->orderBy('cs.class_section_name', 'ASC');
|
||||
|
||||
$filteredQuery = clone $assignmentQuery;
|
||||
// teacher_class assignments are scoped by school year only.
|
||||
// The table has no semester column; semester filtering belongs on
|
||||
// semester-specific records such as scores, comments, attendance,
|
||||
// homework, and exam drafts.
|
||||
if ($schoolYear !== '') {
|
||||
$filteredQuery = $filteredQuery->where('tc.school_year', $schoolYear);
|
||||
}
|
||||
if (!empty($semesterCandidates)) {
|
||||
$filteredQuery = $filteredQuery->whereIn('tc.semester', $semesterCandidates);
|
||||
$assignmentQuery->where('tc.school_year', $schoolYear);
|
||||
}
|
||||
|
||||
$assignmentRows = $filteredQuery->get()->getResultArray();
|
||||
if (empty($assignmentRows) && ($schoolYear !== '' || $semester !== '')) {
|
||||
$assignmentRows = $assignmentQuery->get()->getResultArray();
|
||||
}
|
||||
|
||||
$studentCounts = $this->studentClassModel->getStudentCountsBySection($schoolYear !== '' ? $schoolYear : null);
|
||||
$sectionRows = $this->classSectionModel
|
||||
@@ -873,14 +870,12 @@ class AdministratorController extends BaseController
|
||||
continue;
|
||||
}
|
||||
|
||||
$studentQuery = $this->studentClassModel
|
||||
$studentEntries = $this->db->table('student_class')
|
||||
->select('student_id')
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear);
|
||||
if (!empty($semesterCandidates)) {
|
||||
$studentQuery->whereIn('semester', $semesterCandidates);
|
||||
}
|
||||
$studentEntries = $studentQuery->findAll();
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getResultArray();
|
||||
if (empty($studentEntries)) {
|
||||
$studentEntries = $this->studentClassModel
|
||||
->select('student_id')
|
||||
|
||||
@@ -6,7 +6,6 @@ use App\Controllers\BaseController;
|
||||
use App\Models\ClassSectionModel;
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\CertificateRecordModel;
|
||||
use App\Models\StudentDecisionModel;
|
||||
|
||||
class CertificateController extends BaseController
|
||||
{
|
||||
@@ -40,96 +39,126 @@ class CertificateController extends BaseController
|
||||
->where('sc.school_year', $schoolYear)
|
||||
->orderBy('s.firstname', 'ASC')
|
||||
->orderBy('s.lastname', 'ASC')
|
||||
->get()->getResultArray();
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$allIds = array_unique(array_column($allEnrolled, 'student_id'));
|
||||
$allIds = array_values(array_unique(array_map('intval', array_column($allEnrolled, 'student_id'))));
|
||||
|
||||
// ── Saved generated YEAR decisions from student_decisions ──────────────
|
||||
//
|
||||
// Source of truth:
|
||||
// student_decisions.year_score
|
||||
// student_decisions.decision
|
||||
//
|
||||
// Do NOT recalculate certificate decisions here from semester_scores.
|
||||
$decisionsByStudent = [];
|
||||
|
||||
// ── Semester scores ────────────────────────────────────────────────────
|
||||
$allScoreMap = [];
|
||||
if (!empty($allIds)) {
|
||||
foreach ($db->table('semester_scores')
|
||||
->select('student_id, semester, semester_score')
|
||||
$decisionRows = $db->table('student_decisions')
|
||||
->whereIn('student_id', $allIds)
|
||||
->where('school_year', $schoolYear)
|
||||
->where('semester_score IS NOT NULL', null, false)
|
||||
->get()->getResultArray() as $sr) {
|
||||
$allScoreMap[(int)$sr['student_id']][ucfirst(strtolower($sr['semester']))] =
|
||||
is_numeric($sr['semester_score']) ? (float)$sr['semester_score'] : null;
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
foreach ($decisionRows as $d) {
|
||||
$sid = (int)($d['student_id'] ?? 0);
|
||||
|
||||
if ($sid <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$decision = trim((string)($d['decision'] ?? ''));
|
||||
$source = trim((string)($d['source'] ?? ''));
|
||||
|
||||
if ($source === '') {
|
||||
$source = $decision === '' ? 'pending' : 'manual';
|
||||
}
|
||||
|
||||
$decisionsByStudent[$sid]['Year'] = [
|
||||
'decision' => $decision,
|
||||
'source' => $source,
|
||||
'notes' => (string)($d['notes'] ?? ''),
|
||||
'year_score' => $d['year_score'] ?? null,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// ── Below-60 manual decisions ──────────────────────────────────────────
|
||||
$allBelowMap = [];
|
||||
if (!empty($allIds)) {
|
||||
foreach ($db->table('below_sixty_decisions')
|
||||
->whereIn('student_id', $allIds)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()->getResultArray() as $b) {
|
||||
$allBelowMap[(int)$b['student_id']][ucfirst(strtolower($b['semester']))] = (string)$b['decision'];
|
||||
}
|
||||
}
|
||||
|
||||
// ── Certificate records (most recent per student) ──────────────────────
|
||||
// ── Certificate records: most recent per student ───────────────────────
|
||||
$certsByStudent = [];
|
||||
|
||||
if (!empty($allIds)) {
|
||||
foreach ($db->table('certificate_records')
|
||||
->select('student_id, certificate_number, issued_at')
|
||||
->whereIn('student_id', $allIds)
|
||||
->where('school_year', $schoolYear)
|
||||
->orderBy('issued_at', 'DESC')
|
||||
->get()->getResultArray() as $c) {
|
||||
->get()
|
||||
->getResultArray() as $c) {
|
||||
$sid = (int)$c['student_id'];
|
||||
|
||||
if (!isset($certsByStudent[$sid])) {
|
||||
$certsByStudent[$sid] = $c['certificate_number'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Build per-student decisions + per-class buckets ────────────────────
|
||||
$decisionsByStudent = [];
|
||||
$studentsByClass = []; // [csid => [student rows...]]
|
||||
$statsPerClass = []; // [csid => {name, total, pass, cert}]
|
||||
// ── Build per-class buckets and stats ──────────────────────────────────
|
||||
$studentsByClass = [];
|
||||
$statsPerClass = [];
|
||||
|
||||
foreach ($allEnrolled as $row) {
|
||||
$sid = (int)$row['student_id'];
|
||||
$csid = (int)$row['class_section_id'];
|
||||
|
||||
// Decisions per semester
|
||||
foreach ($allScoreMap[$sid] ?? [] as $sem => $score) {
|
||||
if ($score === null) continue;
|
||||
if ($score >= 60) {
|
||||
$dec = 'Pass'; $src = 'auto';
|
||||
} elseif (!empty($allBelowMap[$sid][$sem])) {
|
||||
$dec = $allBelowMap[$sid][$sem]; $src = 'manual';
|
||||
} else {
|
||||
$dec = ''; $src = 'pending';
|
||||
}
|
||||
$decisionsByStudent[$sid][$sem] = ['decision' => $dec, 'source' => $src];
|
||||
if (!isset($statsPerClass[$csid])) {
|
||||
$statsPerClass[$csid] = [
|
||||
'name' => $row['class_section_name'],
|
||||
'total' => 0,
|
||||
'pass' => 0,
|
||||
'cert' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
// Per-class stats
|
||||
if (!isset($statsPerClass[$csid])) {
|
||||
$statsPerClass[$csid] = ['name' => $row['class_section_name'], 'total' => 0, 'pass' => 0, 'cert' => 0];
|
||||
}
|
||||
$statsPerClass[$csid]['total']++;
|
||||
|
||||
$sems = $allScoreMap[$sid] ?? [];
|
||||
$isPass = !empty($sems);
|
||||
foreach ($sems as $sem => $score) {
|
||||
if ($score === null) { $isPass = false; break; }
|
||||
if ($score >= 60) continue;
|
||||
$md = $allBelowMap[$sid][$sem] ?? '';
|
||||
if ($md === '' || $md !== 'Pass') { $isPass = false; break; }
|
||||
// If no generated decision exists yet, explicitly mark pending.
|
||||
if (!isset($decisionsByStudent[$sid])) {
|
||||
$decisionsByStudent[$sid]['Decision'] = [
|
||||
'decision' => '',
|
||||
'source' => 'pending',
|
||||
'notes' => '',
|
||||
'year_score' => null,
|
||||
];
|
||||
}
|
||||
|
||||
// Certificate eligibility:
|
||||
// A student is eligible only if the saved final generated decision is Pass.
|
||||
$studentDecisions = $decisionsByStudent[$sid] ?? [];
|
||||
$isPass = !empty($studentDecisions);
|
||||
|
||||
foreach ($studentDecisions as $decisionRow) {
|
||||
$decision = trim((string)($decisionRow['decision'] ?? ''));
|
||||
|
||||
if (strcasecmp($decision, 'Pass') !== 0) {
|
||||
$isPass = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($isPass) {
|
||||
$statsPerClass[$csid]['pass']++;
|
||||
}
|
||||
|
||||
if (isset($certsByStudent[$sid])) {
|
||||
$statsPerClass[$csid]['cert']++;
|
||||
}
|
||||
if ($isPass) $statsPerClass[$csid]['pass']++;
|
||||
if (isset($certsByStudent[$sid])) $statsPerClass[$csid]['cert']++;
|
||||
|
||||
// Group students by class
|
||||
$studentsByClass[$csid][] = $row;
|
||||
}
|
||||
|
||||
// ── Determine default active tab ───────────────────────────────────────
|
||||
$firstCsid = !empty($allEnrolled) ? (int)$allEnrolled[0]['class_section_id'] : null;
|
||||
|
||||
if ($selectedCsid === null && $firstCsid !== null) {
|
||||
$selectedCsid = (string)$firstCsid;
|
||||
}
|
||||
@@ -181,9 +210,12 @@ class CertificateController extends BaseController
|
||||
->where('cr.verification_token', $certNumber)
|
||||
->orWhere('cr.certificate_number', strtoupper($certNumber))
|
||||
->groupEnd()
|
||||
->get()->getRowArray();
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
return view('certificates/verify', ['record' => $record ?: null]);
|
||||
return view('certificates/verify', [
|
||||
'record' => $record ?: null,
|
||||
]);
|
||||
}
|
||||
|
||||
// ─── Reprint an existing certificate ──────────────────────────────────────
|
||||
@@ -193,7 +225,8 @@ class CertificateController extends BaseController
|
||||
$record = \Config\Database::connect()
|
||||
->table('certificate_records')
|
||||
->where('certificate_number', strtoupper($certNumber))
|
||||
->get()->getRowArray();
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if (!$record) {
|
||||
return redirect()->to('administrator/certificates/log')
|
||||
@@ -201,8 +234,10 @@ class CertificateController extends BaseController
|
||||
}
|
||||
|
||||
$certDateFormatted = '';
|
||||
|
||||
if (!empty($record['cert_date'])) {
|
||||
$ts = strtotime((string)$record['cert_date']);
|
||||
|
||||
if ($ts) {
|
||||
$certDateFormatted = date('m/d/Y', $ts);
|
||||
}
|
||||
@@ -216,8 +251,9 @@ class CertificateController extends BaseController
|
||||
'verify_token' => $this->ensureVerificationTokenForRecord($record),
|
||||
];
|
||||
|
||||
// student_name is stored as "Firstname Lastname" — split for the PDF builder
|
||||
// student_name is stored as "Firstname Lastname" — split for the PDF builder.
|
||||
$parts = explode(' ', trim($student['firstname']), 2);
|
||||
|
||||
if (count($parts) === 2) {
|
||||
$student['firstname'] = $parts[0];
|
||||
$student['lastname'] = $parts[1];
|
||||
@@ -252,7 +288,9 @@ class CertificateController extends BaseController
|
||||
'csrf_hash' => csrf_hash(),
|
||||
]);
|
||||
}
|
||||
return redirect()->to('administrator/certificates')->with('error', 'Please select at least one student.');
|
||||
|
||||
return redirect()->to('administrator/certificates')
|
||||
->with('error', 'Please select at least one student.');
|
||||
}
|
||||
|
||||
$studentIds = array_filter(array_map('intval', $studentIds));
|
||||
@@ -269,7 +307,9 @@ class CertificateController extends BaseController
|
||||
'csrf_hash' => csrf_hash(),
|
||||
]);
|
||||
}
|
||||
return redirect()->to('administrator/certificates')->with('error', 'Invalid student selection.');
|
||||
|
||||
return redirect()->to('administrator/certificates')
|
||||
->with('error', 'Invalid student selection.');
|
||||
}
|
||||
|
||||
$db = \Config\Database::connect();
|
||||
@@ -277,21 +317,26 @@ class CertificateController extends BaseController
|
||||
|
||||
foreach ($studentIds as $id) {
|
||||
$row = null;
|
||||
|
||||
if ($classSectionId) {
|
||||
$row = $db->table('student_class sc')
|
||||
->select('s.id, s.firstname, s.lastname, cs.class_section_name AS grade')
|
||||
->join('students s', 's.id = sc.student_id')
|
||||
->join('classSection cs', 'cs.class_section_id = sc.class_section_id')
|
||||
->where('sc.class_section_id', (int) $classSectionId)
|
||||
->where('sc.class_section_id', (int)$classSectionId)
|
||||
->where('sc.school_year', $schoolYear)
|
||||
->where('s.id', $id)
|
||||
->get()->getRowArray();
|
||||
->get()
|
||||
->getRowArray();
|
||||
}
|
||||
|
||||
if (!$row) {
|
||||
$s = $db->table('students')
|
||||
->select('id, firstname, lastname, registration_grade AS grade')
|
||||
->where('id', $id)
|
||||
->get()->getRowArray();
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
$row = $s ?: null;
|
||||
}
|
||||
|
||||
@@ -311,51 +356,56 @@ class CertificateController extends BaseController
|
||||
'csrf_hash' => csrf_hash(),
|
||||
]);
|
||||
}
|
||||
return redirect()->to('administrator/certificates')->with('error', 'No valid students found.');
|
||||
|
||||
return redirect()->to('administrator/certificates')
|
||||
->with('error', 'No valid students found.');
|
||||
}
|
||||
|
||||
$issuedBy = session()->get('user_id');
|
||||
$issuedAt = date('Y-m-d H:i:s');
|
||||
$certDateDb = $this->parseCertDate($certDate);
|
||||
|
||||
// Load any existing certificates for these students this school year
|
||||
$db = \Config\Database::connect();
|
||||
// Load existing certificates for these students this school year.
|
||||
$existingCerts = $db->table('certificate_records')
|
||||
->select('id, student_id, certificate_number, verification_token')
|
||||
->whereIn('student_id', array_column($students, 'id'))
|
||||
->where('school_year', $schoolYear)
|
||||
->get()->getResultArray();
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$existingCertMap = [];
|
||||
|
||||
foreach ($existingCerts as $ec) {
|
||||
$existingCertMap[(int)$ec['student_id']] = $ec;
|
||||
}
|
||||
|
||||
foreach ($students as &$student) {
|
||||
$sid = (int)$student['id'];
|
||||
|
||||
if (isset($existingCertMap[$sid])) {
|
||||
// Reuse existing certificate number — do not create a new record
|
||||
// Reuse existing certificate number — do not create a new record.
|
||||
$existing = $existingCertMap[$sid];
|
||||
|
||||
$student['cert_number'] = (string)($existing['certificate_number'] ?? '');
|
||||
$student['verify_token'] = $this->ensureVerificationTokenForRecord($existing);
|
||||
} else {
|
||||
$certNumber = $this->certRecordModel->nextNumber($schoolYear);
|
||||
$verifyToken = $this->certRecordModel->generateVerificationToken();
|
||||
|
||||
$this->certRecordModel->insert([
|
||||
'certificate_number' => $certNumber,
|
||||
'verification_token' => $verifyToken,
|
||||
'student_id' => $sid,
|
||||
'student_name' => $student['firstname'] . ' ' . $student['lastname'],
|
||||
'grade' => $this->formatGrade($student['grade'] ?? ''),
|
||||
//'cert_date' => $certDateDb,
|
||||
'school_year' => $schoolYear,
|
||||
'class_section_id' => $classSectionId ?: null,
|
||||
//'issued_by' => $issuedBy,
|
||||
'issued_at' => $issuedAt,
|
||||
]);
|
||||
|
||||
$student['cert_number'] = $certNumber;
|
||||
$student['verify_token'] = $verifyToken;
|
||||
}
|
||||
}
|
||||
|
||||
unset($student);
|
||||
|
||||
$pdfData = $this->buildPdf($students, $certDate);
|
||||
@@ -376,9 +426,11 @@ class CertificateController extends BaseController
|
||||
if (preg_match('#^(\d{2})/(\d{2})/(\d{4})$#', $certDate, $m)) {
|
||||
return $m[3] . '-' . $m[1] . '-' . $m[2];
|
||||
}
|
||||
|
||||
if (preg_match('#^\d{4}-\d{2}-\d{2}$#', $certDate)) {
|
||||
return $certDate;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -387,17 +439,20 @@ class CertificateController extends BaseController
|
||||
$clean = trim($raw);
|
||||
$lower = strtolower($clean);
|
||||
|
||||
// Strip section suffix: "Grade 1-A" → "Grade 1", "Grade 2-B" → "Grade 2"
|
||||
// Strip section suffix: "Grade 1-A" → "Grade 1", "Grade 2-B" → "Grade 2".
|
||||
if (preg_match('/^grade\s*(\d+)/i', $clean, $m)) {
|
||||
return 'Grade ' . (int)$m[1];
|
||||
}
|
||||
|
||||
if ($lower === 'youth') {
|
||||
return 'Youth';
|
||||
}
|
||||
|
||||
if ($lower === 'kg' || $lower === 'kindergarten') {
|
||||
return 'Kindergarten';
|
||||
}
|
||||
// Raw number or number-section (e.g. "1", "1-A", "2-B") → keep number only
|
||||
|
||||
// Raw number or number-section: "1", "1-A", "2-B" → keep number only.
|
||||
if (preg_match('/^(\d+)([- ][A-Za-z0-9]+)?$/', $clean, $m)) {
|
||||
return 'Grade ' . (int)$m[1];
|
||||
}
|
||||
@@ -408,17 +463,22 @@ class CertificateController extends BaseController
|
||||
private function ensureVerificationTokenForRecord(array $record): string
|
||||
{
|
||||
$token = trim((string)($record['verification_token'] ?? ''));
|
||||
|
||||
if ($token !== '') {
|
||||
return $token;
|
||||
}
|
||||
|
||||
$recordId = (int)($record['id'] ?? 0);
|
||||
|
||||
if ($recordId <= 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$token = $this->certRecordModel->generateVerificationToken();
|
||||
$this->certRecordModel->update($recordId, ['verification_token' => $token]);
|
||||
|
||||
$this->certRecordModel->update($recordId, [
|
||||
'verification_token' => $token,
|
||||
]);
|
||||
|
||||
return $token;
|
||||
}
|
||||
@@ -435,6 +495,7 @@ class CertificateController extends BaseController
|
||||
$ebGaramond = \TCPDF_FONTS::addTTFfont($fontDir . 'EBGaramond-Regular.ttf', 'TrueTypeUnicode', '', 32);
|
||||
|
||||
$pdf = new \TCPDF('L', 'pt', 'A4', true, 'UTF-8', false);
|
||||
|
||||
$pdf->SetCreator('Al Rahma Sunday School');
|
||||
$pdf->SetTitle('Student Certificates');
|
||||
$pdf->SetMargins(0, 0, 0, true);
|
||||
@@ -450,7 +511,7 @@ class CertificateController extends BaseController
|
||||
foreach ($students as $student) {
|
||||
$pdf->AddPage();
|
||||
|
||||
$name = $student['firstname'] . ' ' . $student['lastname'];
|
||||
$name = trim((string)($student['firstname'] ?? '') . ' ' . (string)($student['lastname'] ?? ''));
|
||||
$grade = $this->formatGrade($student['grade'] ?? '');
|
||||
$certNumber = $student['cert_number'] ?? '';
|
||||
$verifyToken = $student['verify_token'] ?? '';
|
||||
@@ -460,10 +521,18 @@ class CertificateController extends BaseController
|
||||
: null;
|
||||
|
||||
$this->drawCertificate(
|
||||
$pdf, $W, $H,
|
||||
$name, $grade, $certDate, $certNumber,
|
||||
$pdf,
|
||||
$W,
|
||||
$H,
|
||||
$name,
|
||||
$grade,
|
||||
$certDate,
|
||||
$certNumber,
|
||||
$verifyUrl,
|
||||
$imgDir, $edwardianFont, $garamondBold, $ebGaramond
|
||||
$imgDir,
|
||||
$edwardianFont,
|
||||
$garamondBold,
|
||||
$ebGaramond
|
||||
);
|
||||
}
|
||||
|
||||
@@ -499,21 +568,24 @@ class CertificateController extends BaseController
|
||||
$pdf->SetXY(0, 151);
|
||||
$pdf->Cell($W, 24, 'Presented to:', 0, 0, 'C');
|
||||
|
||||
// ── QR code — left-aligned with "Presented to:", vertically centred on that line
|
||||
$qrSize = 42; // pt
|
||||
// ── QR code — left-aligned with "Presented to:", vertically centred on that line.
|
||||
$qrSize = 42;
|
||||
|
||||
if (!empty($verifyUrl)) {
|
||||
$qrX = 120; // ~1 cm from left edge
|
||||
$qrY = 171 + (24 - $qrSize) / 2; // vertically centred on "Presented to:" row
|
||||
$qrX = 120;
|
||||
$qrY = 171 + (24 - $qrSize) / 2;
|
||||
|
||||
$style = [
|
||||
'border' => false,
|
||||
'padding' => 0,
|
||||
'fgcolor' => [0, 0, 0],
|
||||
'bgcolor' => false,
|
||||
];
|
||||
|
||||
$pdf->write2DBarcode($verifyUrl, 'QRCODE,L', $qrX, $qrY, $qrSize, $qrSize, $style, 'N');
|
||||
}
|
||||
|
||||
// ── Student name — center based on actual string width
|
||||
// ── Student name — center based on actual string width.
|
||||
$pdf->SetFont($edwardianFont, '', 38);
|
||||
$nameX = ($W - $pdf->GetStringWidth($name)) / 2;
|
||||
$this->drawGradientText($pdf, $edwardianFont, 38, $name, $nameX, 221.5);
|
||||
@@ -543,7 +615,7 @@ class CertificateController extends BaseController
|
||||
$pdf->SetXY(0, 375);
|
||||
$pdf->Cell($W, 20, 'Al Rahma Sunday School', 0, 0, 'C');
|
||||
|
||||
// ── Date (gradient script)
|
||||
// ── Date
|
||||
$this->drawGradientText($pdf, $edwardianFont, 26, $certDate, 586, 456);
|
||||
|
||||
// ── Date underline + label
|
||||
@@ -559,7 +631,7 @@ class CertificateController extends BaseController
|
||||
$pdf->SetXY(106, 492);
|
||||
$pdf->Cell(168, 20, 'Signature', 0, 0, 'C');
|
||||
|
||||
// ── Certificate number — 1.4 cm from bottom, 2.5 cm from left
|
||||
// ── Certificate number — 1.4 cm from bottom, 2.5 cm from left.
|
||||
if ($certNumber !== '') {
|
||||
$pdf->SetFont('helvetica', '', 8);
|
||||
$pdf->SetTextColor(150, 150, 150);
|
||||
@@ -569,8 +641,14 @@ class CertificateController extends BaseController
|
||||
}
|
||||
}
|
||||
|
||||
private function drawGradientText(\TCPDF $pdf, string $fontName, float $fontSize, string $text, float $x, float $y): void
|
||||
{
|
||||
private function drawGradientText(
|
||||
\TCPDF $pdf,
|
||||
string $fontName,
|
||||
float $fontSize,
|
||||
string $text,
|
||||
float $x,
|
||||
float $y
|
||||
): void {
|
||||
$pdf->SetFont($fontName, '', $fontSize);
|
||||
|
||||
for ($i = 0; $i < 6; $i++) {
|
||||
|
||||
@@ -21,8 +21,10 @@ class ClassPreparationController extends BaseController
|
||||
protected $schoolYear;
|
||||
protected $semester;
|
||||
protected $adjustmentModel;
|
||||
/** cache for roster presence per term */
|
||||
/** Cache for roster presence per school year. */
|
||||
private array $rosterPresenceCache = [];
|
||||
/** Cache table-column checks to avoid repeated schema queries. */
|
||||
private array $columnExistsCache = [];
|
||||
// Inside ClassPreparationController (class scope, not inside a method)
|
||||
private array $allowedPrepCategories = [
|
||||
'Grade Box',
|
||||
@@ -57,7 +59,7 @@ class ClassPreparationController extends BaseController
|
||||
$semParam = $this->request->getGet('semester');
|
||||
$semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester;
|
||||
$allowed = $this->allowedPrepCategories;
|
||||
$limitToSemester = $this->hasRosterForSemester($schoolYear, $semester);
|
||||
$hasRoster = $this->hasRosterForSchoolYear($schoolYear);
|
||||
|
||||
// 1) Get student count per class-section (distinct students, correct semester)
|
||||
$scQ = $this->db->table('student_class sc')
|
||||
@@ -65,13 +67,12 @@ class ClassPreparationController extends BaseController
|
||||
->join('students s', 's.id = sc.student_id', 'inner')
|
||||
->where('s.is_active', 1)
|
||||
->where('sc.school_year', $schoolYear);
|
||||
if ($limitToSemester && $semester !== '') {
|
||||
$scQ->where('sc.semester', $semester);
|
||||
}
|
||||
$classSections = $scQ->groupBy('sc.class_section_id')->get()->getResultArray();
|
||||
$classSections = $hasRoster
|
||||
? $scQ->groupBy('sc.class_section_id')->get()->getResultArray()
|
||||
: [];
|
||||
|
||||
// 2) Inventory availability — prefer good_qty when present, else condition='good' quantity.
|
||||
$inventoryMap = $this->buildInventoryAvailability($schoolYear, $semester, $limitToSemester, $allowed);
|
||||
$inventoryMap = $this->buildInventoryAvailability($schoolYear, $semester, $allowed);
|
||||
|
||||
// Seed totals with allowed categories for stable ordering
|
||||
$requiredTotals = array_fill_keys($allowed, 0);
|
||||
@@ -85,14 +86,10 @@ class ClassPreparationController extends BaseController
|
||||
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId);
|
||||
|
||||
// Calculate required items (whitelist inside)
|
||||
$baseItems = $this->calculatePrepItems($studentCount, $classLevel, $classSectionId);
|
||||
$baseItems = $this->calculatePrepItems($studentCount, $classLevel, $classSectionId, $schoolYear);
|
||||
|
||||
// --- Apply adjustments (only Small/Large Table), clamp >= 0 ---
|
||||
$rawAdjustments = $this->adjustmentModel
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear)
|
||||
->where('adjustable', 1)
|
||||
->findAll();
|
||||
$rawAdjustments = $this->getAdjustments((string) $classSectionId, (string) $schoolYear);
|
||||
|
||||
$adjMap = ['Large Table' => 0, 'Small Table' => 0];
|
||||
|
||||
@@ -117,11 +114,7 @@ class ClassPreparationController extends BaseController
|
||||
}
|
||||
|
||||
// 5) Compare with last snapshot; do not save here — only on print or explicit API
|
||||
$oldSnap = $this->prepLogModel
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear)
|
||||
->orderBy('created_at', 'DESC')
|
||||
->first();
|
||||
$oldSnap = $this->getLatestPrepSnapshot((string) $classSectionId, (string) $schoolYear);
|
||||
|
||||
$oldPrep = $oldSnap ? json_decode($oldSnap['prep_data'], true) : [];
|
||||
$hasChanged = $this->hasPrepChanged($baseItems, $oldPrep);
|
||||
@@ -175,7 +168,7 @@ class ClassPreparationController extends BaseController
|
||||
return (int)($row['cnt'] ?? 0);
|
||||
}
|
||||
|
||||
private function calculatePrepItems(int $students, int $classLevel, string $classSectionId): array
|
||||
private function calculatePrepItems(int $students, int $classLevel, string $classSectionId, ?string $schoolYear = null): array
|
||||
{
|
||||
// 1) Stable keys: your whitelist, all zero to start
|
||||
$allowed = $this->allowedPrepCategories;
|
||||
@@ -192,7 +185,7 @@ class ClassPreparationController extends BaseController
|
||||
|
||||
// 3) Rules
|
||||
$isLowerGrades = in_array($classLevel, [1, 2], true);
|
||||
$teacherCount = $this->getTeacherCountForSection($classSectionId, $this->schoolYear);
|
||||
$teacherCount = $this->getTeacherCountForSection($classSectionId, $schoolYear ?? $this->schoolYear);
|
||||
|
||||
foreach ($categories as $cat) {
|
||||
$name = $cat['name']; // e.g., 'Small Table'
|
||||
@@ -253,24 +246,35 @@ class ClassPreparationController extends BaseController
|
||||
$adjustments = $data['adjustments'] ?? [];
|
||||
|
||||
foreach ($adjustments as $itemName => $adjustment) {
|
||||
$row = $this->adjustmentModel
|
||||
$adjustmentQuery = $this->adjustmentModel
|
||||
->where('class_section_id', $sectionId)
|
||||
->where('school_year', $schoolYear)
|
||||
->where('item_name', $itemName)
|
||||
->first();
|
||||
->where('item_name', $itemName);
|
||||
|
||||
$adjustmentTable = $this->adjustmentModel->getTable();
|
||||
|
||||
if ($schoolYear !== '' && $this->tableHasColumn($adjustmentTable, 'school_year')) {
|
||||
$adjustmentQuery->where('school_year', $schoolYear);
|
||||
}
|
||||
|
||||
$row = $adjustmentQuery->first();
|
||||
|
||||
if ($row) {
|
||||
// Update
|
||||
$this->adjustmentModel->update($row['id'], ['adjustment' => (int)$adjustment, 'adjustable' => 1]);
|
||||
} else {
|
||||
// Insert
|
||||
$this->adjustmentModel->insert([
|
||||
$insertData = [
|
||||
'class_section_id' => $sectionId,
|
||||
'item_name' => $itemName,
|
||||
'adjustment' => (int)$adjustment,
|
||||
'school_year' => $schoolYear,
|
||||
'adjustment' => (int) $adjustment,
|
||||
'adjustable' => 1,
|
||||
]);
|
||||
];
|
||||
|
||||
if ($schoolYear !== '' && $this->tableHasColumn($adjustmentTable, 'school_year')) {
|
||||
$insertData['school_year'] = $schoolYear;
|
||||
}
|
||||
|
||||
$this->adjustmentModel->insert($insertData);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -292,10 +296,6 @@ class ClassPreparationController extends BaseController
|
||||
|
||||
public function print($classSectionId, $schoolYear)
|
||||
{
|
||||
$semParam = $this->request->getGet('semester');
|
||||
$semester = (is_string($semParam) && $semParam !== '') ? (string) $semParam : (string) $this->semester;
|
||||
$limitToSemester = $this->hasRosterForSemester((string) $schoolYear, $semester);
|
||||
|
||||
// Friendly label (if you have this helper)
|
||||
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId) ?? $classSectionId;
|
||||
|
||||
@@ -306,15 +306,12 @@ class ClassPreparationController extends BaseController
|
||||
->where('s.is_active', 1)
|
||||
->where('sc.class_section_id', $classSectionId)
|
||||
->where('sc.school_year', $schoolYear);
|
||||
if ($limitToSemester && $semester !== '') {
|
||||
$studentQ->where('sc.semester', $semester);
|
||||
}
|
||||
$studentRow = $studentQ->get()->getRowArray();
|
||||
$studentCount = (int)($studentRow['cnt'] ?? 0);
|
||||
|
||||
// Live calc + adjustments
|
||||
$classLevel = $this->getClassLevelBySection((string)$classSectionId);
|
||||
$items = $this->calculatePrepItems($studentCount, $classLevel, (string)$classSectionId);
|
||||
$items = $this->calculatePrepItems($studentCount, $classLevel, (string)$classSectionId, (string)$schoolYear);
|
||||
|
||||
$rawAdjustments = $this->adjustmentModel
|
||||
->where('class_section_id', $classSectionId)
|
||||
@@ -328,13 +325,15 @@ class ClassPreparationController extends BaseController
|
||||
}
|
||||
|
||||
// Record a snapshot at print time as the new baseline
|
||||
$this->prepLogModel->insert([
|
||||
'class_section_id' => (string)$classSectionId,
|
||||
'class_section' => $className,
|
||||
'school_year' => $schoolYear,
|
||||
'prep_data' => json_encode($items),
|
||||
'created_at' => utc_now(),
|
||||
]);
|
||||
$this->prepLogModel->insert(
|
||||
$this->buildPrepLogData(
|
||||
(string) $classSectionId,
|
||||
(string) $className,
|
||||
(string) $schoolYear,
|
||||
$items,
|
||||
utc_now()
|
||||
)
|
||||
);
|
||||
|
||||
// Return PRINT view (HTML) that auto-opens the print dialog
|
||||
return view('class_prep/print', [
|
||||
@@ -356,7 +355,7 @@ class ClassPreparationController extends BaseController
|
||||
$semParam = $this->request->getGet('semester');
|
||||
$semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester;
|
||||
$allowed = $this->allowedPrepCategories;
|
||||
$limitToSemester = $this->hasRosterForSemester($schoolYear, $semester);
|
||||
$hasRoster = $this->hasRosterForSchoolYear($schoolYear);
|
||||
|
||||
// Student counts
|
||||
$scQ = $this->db->table('student_class sc')
|
||||
@@ -364,13 +363,12 @@ class ClassPreparationController extends BaseController
|
||||
->join('students s', 's.id = sc.student_id', 'inner')
|
||||
->where('s.is_active', 1)
|
||||
->where('sc.school_year', $schoolYear);
|
||||
if ($limitToSemester && $semester !== '') {
|
||||
$scQ->where('sc.semester', $semester);
|
||||
}
|
||||
$classSections = $scQ->groupBy('sc.class_section_id')->get()->getResultArray();
|
||||
$classSections = $hasRoster
|
||||
? $scQ->groupBy('sc.class_section_id')->get()->getResultArray()
|
||||
: [];
|
||||
|
||||
// Build inventory availability maps
|
||||
$inventoryMap = $this->buildInventoryAvailability($schoolYear, $semester, $limitToSemester, $allowed);
|
||||
$inventoryMap = $this->buildInventoryAvailability($schoolYear, $semester, $allowed);
|
||||
|
||||
$requiredTotals = array_fill_keys($allowed, 0);
|
||||
$results = [];
|
||||
@@ -381,12 +379,8 @@ class ClassPreparationController extends BaseController
|
||||
$classLevel = $this->getClassLevelBySection($classSectionId);
|
||||
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId);
|
||||
|
||||
$baseItems = $this->calculatePrepItems($studentCount, $classLevel, $classSectionId);
|
||||
$rawAdjustments = $this->adjustmentModel
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear)
|
||||
->where('adjustable', 1)
|
||||
->findAll();
|
||||
$baseItems = $this->calculatePrepItems($studentCount, $classLevel, $classSectionId, $schoolYear);
|
||||
$rawAdjustments = $this->getAdjustments((string) $classSectionId, (string) $schoolYear);
|
||||
$adjMap = ['Large Table' => 0, 'Small Table' => 0];
|
||||
foreach ($rawAdjustments as $a) {
|
||||
$item = $a['item_name'];
|
||||
@@ -399,11 +393,7 @@ class ClassPreparationController extends BaseController
|
||||
$requiredTotals[$cat] += (int)($baseItems[$cat] ?? 0);
|
||||
}
|
||||
|
||||
$oldSnap = $this->prepLogModel
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear)
|
||||
->orderBy('created_at', 'DESC')
|
||||
->first();
|
||||
$oldSnap = $this->getLatestPrepSnapshot((string) $classSectionId, (string) $schoolYear);
|
||||
$oldPrep = $oldSnap ? json_decode($oldSnap['prep_data'], true) : [];
|
||||
$hasChanged = $this->hasPrepChanged($baseItems, $oldPrep);
|
||||
|
||||
@@ -446,7 +436,6 @@ class ClassPreparationController extends BaseController
|
||||
$schoolYear = (string)($this->request->getPost('school_year') ?? $this->schoolYear);
|
||||
$semParam = $this->request->getPost('semester');
|
||||
$semester = (is_string($semParam) && $semParam !== '') ? (string)$semParam : (string)$this->semester;
|
||||
$limitToSemester = $this->hasRosterForSemester($schoolYear, $semester);
|
||||
$ids = $this->request->getPost('class_section_ids') ?? [];
|
||||
if (!is_array($ids)) $ids = $ids ? [$ids] : [];
|
||||
$ids = array_values(array_unique(array_filter(array_map('strval', $ids))));
|
||||
@@ -460,21 +449,14 @@ class ClassPreparationController extends BaseController
|
||||
->where('s.is_active', 1)
|
||||
->where('sc.class_section_id', $classSectionId)
|
||||
->where('sc.school_year', $schoolYear);
|
||||
if ($limitToSemester && $semester !== '') {
|
||||
$studentQ->where('sc.semester', $semester);
|
||||
}
|
||||
$studentRow = $studentQ->get()->getRowArray();
|
||||
$studentCount = (int)($studentRow['cnt'] ?? 0);
|
||||
$classLevel = $this->getClassLevelBySection((string)$classSectionId);
|
||||
$className = $this->classSectionModel->getClassSectionNameBySectionId($classSectionId) ?? $classSectionId;
|
||||
|
||||
$items = $this->calculatePrepItems($studentCount, $classLevel, (string)$classSectionId);
|
||||
$items = $this->calculatePrepItems($studentCount, $classLevel, (string)$classSectionId, (string)$schoolYear);
|
||||
|
||||
$rawAdjustments = $this->adjustmentModel
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear)
|
||||
->where('adjustable', 1)
|
||||
->findAll();
|
||||
$rawAdjustments = $this->getAdjustments((string) $classSectionId, (string) $schoolYear);
|
||||
foreach ($rawAdjustments as $a) {
|
||||
$item = $a['item_name'];
|
||||
$delta = (int)$a['adjustment'];
|
||||
@@ -482,13 +464,15 @@ class ClassPreparationController extends BaseController
|
||||
}
|
||||
|
||||
try {
|
||||
$this->prepLogModel->insert([
|
||||
'class_section_id' => (string)$classSectionId,
|
||||
'class_section' => $className,
|
||||
'school_year' => $schoolYear,
|
||||
'prep_data' => json_encode($items),
|
||||
'created_at' => $now,
|
||||
]);
|
||||
$this->prepLogModel->insert(
|
||||
$this->buildPrepLogData(
|
||||
(string) $classSectionId,
|
||||
(string) $className,
|
||||
(string) $schoolYear,
|
||||
$items,
|
||||
$now
|
||||
)
|
||||
);
|
||||
$count++;
|
||||
} catch (\Throwable $e) {
|
||||
// ignore and continue
|
||||
@@ -528,12 +512,12 @@ class ClassPreparationController extends BaseController
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if student_class has any rows for the given school year.
|
||||
* The semester argument is ignored because assignments are tracked per year.
|
||||
* Returns true when student_class contains at least one assignment
|
||||
* for the selected school year.
|
||||
*/
|
||||
private function hasRosterForTerm(string $schoolYear, string $semester): bool
|
||||
private function hasRosterForSchoolYear(string $schoolYear): bool
|
||||
{
|
||||
$year = trim((string)$schoolYear);
|
||||
$year = trim($schoolYear);
|
||||
if ($year === '') {
|
||||
return false;
|
||||
}
|
||||
@@ -542,72 +526,151 @@ class ClassPreparationController extends BaseController
|
||||
return $this->rosterPresenceCache[$year];
|
||||
}
|
||||
|
||||
$cnt = $this->db->table('student_class')
|
||||
$exists = $this->db->table('student_class')
|
||||
->where('school_year', $year)
|
||||
->countAllResults();
|
||||
->limit(1)
|
||||
->countAllResults() > 0;
|
||||
|
||||
$this->rosterPresenceCache[$year] = $cnt > 0;
|
||||
return $this->rosterPresenceCache[$year];
|
||||
$this->rosterPresenceCache[$year] = $exists;
|
||||
|
||||
return $exists;
|
||||
}
|
||||
|
||||
private function hasRosterForSemester(string $schoolYear, string $semester): bool
|
||||
private function tableHasColumn(string $table, string $column): bool
|
||||
{
|
||||
$year = trim((string)$schoolYear);
|
||||
$sem = trim((string)$semester);
|
||||
if ($year === '' || $sem === '') {
|
||||
return false;
|
||||
$key = $table . '.' . $column;
|
||||
|
||||
if (!array_key_exists($key, $this->columnExistsCache)) {
|
||||
$this->columnExistsCache[$key] = $this->db->fieldExists($column, $table);
|
||||
}
|
||||
|
||||
$key = sprintf('sem:%s:%s', $year, $sem);
|
||||
if (array_key_exists($key, $this->rosterPresenceCache)) {
|
||||
return $this->rosterPresenceCache[$key];
|
||||
return $this->columnExistsCache[$key];
|
||||
}
|
||||
|
||||
$cnt = $this->db->table('student_class')
|
||||
->where('school_year', $year)
|
||||
->where('semester', $sem)
|
||||
->countAllResults();
|
||||
private function getAdjustments(string $classSectionId, string $schoolYear): array
|
||||
{
|
||||
$query = $this->adjustmentModel
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('adjustable', 1);
|
||||
|
||||
$this->rosterPresenceCache[$key] = $cnt > 0;
|
||||
return $this->rosterPresenceCache[$key];
|
||||
$table = $this->adjustmentModel->getTable();
|
||||
|
||||
if ($schoolYear !== '' && $this->tableHasColumn($table, 'school_year')) {
|
||||
$query->where('school_year', $schoolYear);
|
||||
}
|
||||
|
||||
private function buildInventoryAvailability(string $schoolYear, string $semester, bool $limitToSemester, array $allowed): array
|
||||
return $query->findAll();
|
||||
}
|
||||
|
||||
private function getLatestPrepSnapshot(string $classSectionId, string $schoolYear): ?array
|
||||
{
|
||||
$query = $this->prepLogModel
|
||||
->where('class_section_id', $classSectionId);
|
||||
|
||||
$table = $this->prepLogModel->getTable();
|
||||
|
||||
if ($schoolYear !== '' && $this->tableHasColumn($table, 'school_year')) {
|
||||
$query->where('school_year', $schoolYear);
|
||||
}
|
||||
|
||||
return $query
|
||||
->orderBy('created_at', 'DESC')
|
||||
->first();
|
||||
}
|
||||
|
||||
private function buildPrepLogData(
|
||||
string $classSectionId,
|
||||
string $className,
|
||||
string $schoolYear,
|
||||
array $items,
|
||||
string $createdAt
|
||||
): array {
|
||||
$data = [
|
||||
'class_section_id' => $classSectionId,
|
||||
'class_section' => $className,
|
||||
'prep_data' => json_encode($items),
|
||||
'created_at' => $createdAt,
|
||||
];
|
||||
|
||||
$table = $this->prepLogModel->getTable();
|
||||
|
||||
if ($schoolYear !== '' && $this->tableHasColumn($table, 'school_year')) {
|
||||
$data['school_year'] = $schoolYear;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function buildInventoryAvailability(string $schoolYear, string $semester, array $allowed): array
|
||||
{
|
||||
$inventoryMap = array_fill_keys($allowed, 0);
|
||||
|
||||
$hasSchoolYear = $this->tableHasColumn('inventory_items', 'school_year');
|
||||
$hasSemester = $this->tableHasColumn('inventory_items', 'semester');
|
||||
$hasName = $this->tableHasColumn('inventory_items', 'name');
|
||||
|
||||
$joinRows = $this->db->table('inventory_items ii')
|
||||
->select('ic.name AS item_name, COALESCE(SUM(CASE WHEN ii.good_qty IS NOT NULL THEN ii.good_qty WHEN ii.`condition`="good" THEN ii.quantity ELSE 0 END),0) AS available')
|
||||
->select('ic.name AS item_name, COALESCE(SUM(CASE WHEN ii.good_qty IS NOT NULL THEN ii.good_qty WHEN ii.`condition` = "good" THEN ii.quantity ELSE 0 END), 0) AS available', false)
|
||||
->join('inventory_categories ic', 'ic.id = ii.category_id', 'left')
|
||||
->where('ii.type', 'classroom')
|
||||
->where('ii.school_year', $schoolYear)
|
||||
->whereIn('ic.name', $allowed);
|
||||
if ($limitToSemester && $semester !== '') {
|
||||
|
||||
if ($hasSchoolYear && $schoolYear !== '') {
|
||||
$joinRows->where('ii.school_year', $schoolYear);
|
||||
}
|
||||
|
||||
if ($hasSemester && $semester !== '') {
|
||||
$joinRows->where('ii.semester', $semester);
|
||||
}
|
||||
$joinRows = $joinRows->groupBy('ic.name')->get()->getResultArray();
|
||||
|
||||
foreach ($joinRows as $r) {
|
||||
$name = (string)($r['item_name'] ?? '');
|
||||
if ($name !== '' && isset($inventoryMap[$name])) {
|
||||
$inventoryMap[$name] = max($inventoryMap[$name], (int)($r['available'] ?? 0));
|
||||
$joinRows = $joinRows
|
||||
->groupBy('ic.name')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
foreach ($joinRows as $row) {
|
||||
$name = (string) ($row['item_name'] ?? '');
|
||||
|
||||
if ($name !== '' && array_key_exists($name, $inventoryMap)) {
|
||||
$inventoryMap[$name] = max(
|
||||
$inventoryMap[$name],
|
||||
(int) ($row['available'] ?? 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Some older schemas store the item name directly on inventory_items.
|
||||
* Only run this fallback when that column actually exists.
|
||||
*/
|
||||
if ($hasName) {
|
||||
$nameRows = $this->db->table('inventory_items')
|
||||
->select('name AS item_name, COALESCE(SUM(CASE WHEN good_qty IS NOT NULL THEN good_qty WHEN `condition`="good" THEN quantity ELSE 0 END),0) AS available')
|
||||
->select('name AS item_name, COALESCE(SUM(CASE WHEN good_qty IS NOT NULL THEN good_qty WHEN `condition` = "good" THEN quantity ELSE 0 END), 0) AS available', false)
|
||||
->where('type', 'classroom')
|
||||
->where('school_year', $schoolYear)
|
||||
->whereIn('name', $allowed);
|
||||
if ($limitToSemester && $semester !== '') {
|
||||
|
||||
if ($hasSchoolYear && $schoolYear !== '') {
|
||||
$nameRows->where('school_year', $schoolYear);
|
||||
}
|
||||
|
||||
if ($hasSemester && $semester !== '') {
|
||||
$nameRows->where('semester', $semester);
|
||||
}
|
||||
$nameRows = $nameRows->groupBy('name')->get()->getResultArray();
|
||||
|
||||
foreach ($nameRows as $r) {
|
||||
$name = (string)($r['item_name'] ?? '');
|
||||
if ($name !== '' && isset($inventoryMap[$name])) {
|
||||
$inventoryMap[$name] = max($inventoryMap[$name], (int)($r['available'] ?? 0));
|
||||
$nameRows = $nameRows
|
||||
->groupBy('name')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
foreach ($nameRows as $row) {
|
||||
$name = (string) ($row['item_name'] ?? '');
|
||||
|
||||
if ($name !== '' && array_key_exists($name, $inventoryMap)) {
|
||||
$inventoryMap[$name] = max(
|
||||
$inventoryMap[$name],
|
||||
(int) ($row['available'] ?? 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Controllers\View;
|
||||
use App\Controllers\BaseController;
|
||||
use App\Libraries\InvoiceLedgerService;
|
||||
use App\Models\DiscountVoucherModel;
|
||||
use App\Models\DiscountUsageModel;
|
||||
use App\Models\InvoiceModel;
|
||||
@@ -28,6 +29,7 @@ class DiscountController extends BaseController
|
||||
protected $eventChargesModel;
|
||||
protected $additionalChargeModel;
|
||||
protected $classSectionModel;
|
||||
protected $invoiceLedgerService;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
@@ -41,6 +43,7 @@ class DiscountController extends BaseController
|
||||
$this->eventChargesModel = new EventChargesModel();
|
||||
$this->additionalChargeModel = new AdditionalChargeModel();
|
||||
$this->classSectionModel = new ClassSectionModel();
|
||||
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||
|
||||
$this->schoolYear = $this->configModel->getConfig('school_year');
|
||||
$this->semester = $this->configModel->getConfig('semester');
|
||||
@@ -121,6 +124,8 @@ class DiscountController extends BaseController
|
||||
foreach ($invoices as $invoice) {
|
||||
if ($remainingUses <= 0) break 2; // out of parentIds loop too
|
||||
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $invoice['id']]);
|
||||
|
||||
// Snapshot current balance BEFORE applying
|
||||
$initialPreBalance = (float) $this->getCurrentInvoiceBalance($invoice['id'], $this->schoolYear);
|
||||
if ($initialPreBalance <= 0) {
|
||||
@@ -201,22 +206,9 @@ class DiscountController extends BaseController
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
// Update invoice balance based on pre-discount snapshot (supports multiple discounts)
|
||||
$newBalance = max(0.0, round($initialPreBalance - $discount, 2));
|
||||
$this->db->table('invoices')
|
||||
->where('id', $invoice['id'])
|
||||
->update([
|
||||
'balance' => $newBalance,
|
||||
'has_discount' => 1,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
// Compute post-balance based on pre-snapshot (more stable than $invoice['balance'])
|
||||
$postBalance = round($initialPreBalance - $discount, 2);
|
||||
if ($postBalance < 0) $postBalance = 0.0;
|
||||
|
||||
// (Optional) current balance re-check (in case of concurrent writes)
|
||||
$currentBalance = (float) $this->getCurrentInvoiceBalance($invoice['id'], $this->schoolYear);
|
||||
$ledger = $this->invoiceLedgerService->recalculateInvoice((int) $invoice['id']);
|
||||
$postBalance = (float) ($ledger['balance'] ?? 0.0);
|
||||
$currentBalance = $postBalance;
|
||||
|
||||
// Increment voucher usage
|
||||
$this->db->table('discount_vouchers')
|
||||
@@ -596,53 +588,11 @@ class DiscountController extends BaseController
|
||||
*/
|
||||
private function getCurrentInvoiceBalance($invoiceId, $schoolYear)
|
||||
{
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) return 0.0;
|
||||
|
||||
// Payments (exclude void/refund/failed, honor year)
|
||||
$qb = $this->paymentModel
|
||||
->select('COALESCE(SUM(paid_amount),0) AS total_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('school_year', $schoolYear);
|
||||
|
||||
$table = $this->paymentModel->table;
|
||||
$hasStatus = $this->db->fieldExists('status', $table);
|
||||
$hasVoid = $this->db->fieldExists('is_void', $table);
|
||||
if ($hasStatus) {
|
||||
$qb->groupStart()
|
||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
try {
|
||||
return (float) ($this->invoiceLedgerService->calculateInvoice((int) $invoiceId)['balance'] ?? 0.0);
|
||||
} catch (\Throwable $e) {
|
||||
return 0.0;
|
||||
}
|
||||
if ($hasVoid) {
|
||||
$qb->groupStart()
|
||||
->where('is_void', 0)
|
||||
->orWhere('is_void IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
$rowPaid = $qb->first();
|
||||
$totalPaid = (float)($rowPaid['total_paid'] ?? 0);
|
||||
|
||||
// Discounts for this invoice in this year
|
||||
$rowDisc = $this->db->table('discount_usages du')
|
||||
->select('COALESCE(SUM(du.discount_amount),0) AS total_disc')
|
||||
->join('invoices i', 'i.id = du.invoice_id')
|
||||
->where('du.invoice_id', $invoiceId)
|
||||
->where('i.school_year', $schoolYear)
|
||||
->get()->getRowArray();
|
||||
$totalDisc = (float)($rowDisc['total_disc'] ?? 0);
|
||||
|
||||
// Refunds PAID for this invoice in this year
|
||||
$rowRefund = $this->db->table('refunds')
|
||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('school_year', $schoolYear)
|
||||
->whereIn('status', ['Partial', 'Paid'])
|
||||
->get()->getRowArray();
|
||||
$totalRefundPaid = (float)($rowRefund['total_refund_paid'] ?? 0);
|
||||
|
||||
$total = (float)($invoice['total_amount'] ?? 0);
|
||||
return max(0.0, round($total - $totalPaid - $totalDisc - $totalRefundPaid, 2));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -650,169 +600,7 @@ class DiscountController extends BaseController
|
||||
*/
|
||||
private function recalculateInvoice($invoiceId, $schoolYear): void
|
||||
{
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) return;
|
||||
|
||||
$parentId = (int)($invoice['parent_id'] ?? 0);
|
||||
if ($parentId <= 0) return;
|
||||
|
||||
// ---- Tuition (recompute from enrollments) ----
|
||||
$enrollments = $this->enrollmentModel
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
|
||||
$registered = [];
|
||||
$withdrawn = [];
|
||||
foreach ($enrollments as $e) {
|
||||
$row = [
|
||||
'student_id' => (int)($e['student_id'] ?? 0),
|
||||
'class_section_id' => $e['class_section_id'] ?? null,
|
||||
'enrollment_status'=> (string)($e['enrollment_status'] ?? ''),
|
||||
];
|
||||
if (in_array($row['enrollment_status'], ['enrolled','payment pending'], true)) {
|
||||
$registered[] = $row;
|
||||
} elseif (in_array($row['enrollment_status'], ['withdrawn','refund pending','withdraw under review'], true)) {
|
||||
$withdrawn[] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
// Refund window check – if after deadline, withdrawn still billed
|
||||
$refundDeadline = (string)($this->configModel->getConfig('refund_deadline') ?? '');
|
||||
$refundAllowed = true;
|
||||
try {
|
||||
$tzName = (string) (config('School')->attendance['timezone'] ?? user_timezone());
|
||||
$tz = new \DateTimeZone($tzName);
|
||||
$today = new \DateTimeImmutable('today', $tz);
|
||||
$deadline = new \DateTimeImmutable($refundDeadline, $tz);
|
||||
$refundAllowed = $today <= $deadline;
|
||||
} catch (\Throwable $e) {
|
||||
$refundAllowed = true;
|
||||
}
|
||||
|
||||
$tuitionStudents = $registered;
|
||||
if (!$refundAllowed) {
|
||||
$tuitionStudents = array_merge($tuitionStudents, $withdrawn);
|
||||
}
|
||||
|
||||
// Grade threshold and fees
|
||||
$gradeFee = (int)($this->configModel->getConfig('grade_fee') ?? 9);
|
||||
$firstStudentFee = (float)($this->configModel->getConfig('first_student_fee') ?? 350);
|
||||
$secondStudentFee = (float)($this->configModel->getConfig('second_student_fee') ?? 200);
|
||||
$youthFee = (float)($this->configModel->getConfig('youth_fee') ?? 180);
|
||||
|
||||
// Normalize grades for tuition students
|
||||
foreach ($tuitionStudents as &$s) {
|
||||
$name = null;
|
||||
if (!empty($s['class_section_id'])) {
|
||||
$name = $this->classSectionModel->getClassSectionNameBySectionId($s['class_section_id']);
|
||||
}
|
||||
$s['grade_name'] = is_string($name) ? strtoupper(trim($name)) : 'N/A';
|
||||
}
|
||||
unset($s);
|
||||
|
||||
// Count regular vs youth and compute tuition
|
||||
$regularCount = 0;
|
||||
$youthCount = 0;
|
||||
foreach ($tuitionStudents as $s) {
|
||||
$lvl = $this->parseGradeLevel($s['grade_name']);
|
||||
if ($lvl > $gradeFee) $youthCount++; else $regularCount++;
|
||||
}
|
||||
|
||||
$tuitionSubtotal = 0.0;
|
||||
$tuitionSubtotal += $youthCount * $youthFee;
|
||||
if ($regularCount >= 2) {
|
||||
$tuitionSubtotal += $firstStudentFee + ($regularCount - 1) * $secondStudentFee;
|
||||
} elseif ($regularCount === 1) {
|
||||
$tuitionSubtotal += $firstStudentFee;
|
||||
}
|
||||
|
||||
// ---- Event charges (parent-year) ----
|
||||
$eventSubtotal = 0.0;
|
||||
try {
|
||||
$events = $this->eventChargesModel->getChargesWithEventInfo($parentId, $schoolYear) ?? [];
|
||||
foreach ($events as $ev) { $eventSubtotal += (float)($ev['charged'] ?? 0.0); }
|
||||
} catch (\Throwable $e) {}
|
||||
|
||||
// ---- Additional charges (per-invoice) ----
|
||||
$additionalSubtotal = 0.0;
|
||||
try {
|
||||
$rows = $this->additionalChargeModel
|
||||
->select('charge_type, amount')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('status', 'applied')
|
||||
->findAll();
|
||||
foreach ($rows as $r) {
|
||||
$amt = (float)($r['amount'] ?? 0);
|
||||
$typ = strtolower((string)($r['charge_type'] ?? 'add'));
|
||||
if ($typ === 'deduct') $amt = -abs($amt); else $amt = abs($amt);
|
||||
$additionalSubtotal += $amt;
|
||||
}
|
||||
} catch (\Throwable $e) {}
|
||||
|
||||
$discountableTotal = $tuitionSubtotal + $additionalSubtotal;
|
||||
$nonDiscountableTotal = $eventSubtotal;
|
||||
$newTotal = round($discountableTotal + $nonDiscountableTotal, 2);
|
||||
|
||||
// ---- Payments / Discounts / Refunds ----
|
||||
$db = $this->db;
|
||||
$table = $this->paymentModel->table;
|
||||
$hasStatus = $db->fieldExists('status', $table);
|
||||
$hasVoid = $db->fieldExists('is_void', $table);
|
||||
$exclude = ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'];
|
||||
|
||||
$qb = $this->paymentModel
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('school_year', $schoolYear);
|
||||
|
||||
if ($hasStatus) {
|
||||
$qb->groupStart()
|
||||
->whereNotIn('status', $exclude)
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
if ($hasVoid) {
|
||||
$qb->groupStart()
|
||||
->where('is_void', 0)
|
||||
->orWhere('is_void IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
$payments = $qb->findAll();
|
||||
$totalPaid = 0.0;
|
||||
foreach ($payments as $p) { $totalPaid += (float)($p['paid_amount'] ?? 0); }
|
||||
|
||||
$discRow = $this->db->table('discount_usages')
|
||||
->select('COALESCE(SUM(discount_amount),0) AS total_disc')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->get()->getRowArray();
|
||||
$totalDisc = (float)($discRow['total_disc'] ?? 0);
|
||||
|
||||
$refundRow = $this->db->table('refunds')
|
||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->whereIn('status', ['Partial','Paid'])
|
||||
->get()->getRowArray();
|
||||
$totalRefundPaid = (float)($refundRow['total_refund_paid'] ?? 0);
|
||||
|
||||
$appliedDiscount = min($totalDisc, $discountableTotal);
|
||||
$newBalance = max(0.0, $newTotal - $appliedDiscount - $totalPaid - $totalRefundPaid);
|
||||
$newStatus = ($newBalance <= 0.00001) ? 'Paid' : (($totalPaid > 0) ? 'Partially Paid' : 'Unpaid');
|
||||
|
||||
$updateData = [
|
||||
'total_amount' => $newTotal,
|
||||
'paid_amount' => $totalPaid,
|
||||
'balance' => $newBalance,
|
||||
'status' => $newStatus,
|
||||
'has_discount' => ($totalDisc > 0.0) ? 1 : 0,
|
||||
];
|
||||
|
||||
if ($this->db->fieldExists('discount', $this->invoiceModel->table)) {
|
||||
$updateData['discount'] = $totalDisc;
|
||||
}
|
||||
|
||||
$this->invoiceModel->update($invoiceId, $updateData);
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $invoiceId);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace App\Controllers\View;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Libraries\FinancialStatus;
|
||||
use App\Libraries\InvoiceLedgerService;
|
||||
use App\Models\AdditionalChargeModel;
|
||||
use CodeIgniter\Controller;
|
||||
use App\Models\UserModel;
|
||||
@@ -28,6 +30,7 @@ class ExtraChargesController extends BaseController
|
||||
protected $studentClassModel;
|
||||
protected $enableAttendance;
|
||||
protected $attendanceDayModel;
|
||||
protected $invoiceLedgerService;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
@@ -39,6 +42,7 @@ class ExtraChargesController extends BaseController
|
||||
$this->invoiceModel = new InvoiceModel();
|
||||
$this->semester = $this->configModel->getConfig('semester');
|
||||
$this->schoolYear = $this->configModel->getConfig('school_year');
|
||||
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||
}
|
||||
|
||||
public function index()
|
||||
@@ -247,13 +251,9 @@ class ExtraChargesController extends BaseController
|
||||
// keep status as-is
|
||||
]);
|
||||
|
||||
// If it’s already applied on an invoice and the amount changed, reflect the delta
|
||||
if ($row['status'] === 'applied' && !empty($row['invoice_id']) && abs($delta) > 0.00001) {
|
||||
if ($delta > 0) {
|
||||
$this->invoiceModel->applyAdditionalCharge((int)$row['invoice_id'], $delta);
|
||||
} else {
|
||||
$this->invoiceModel->reverseAdditionalCharge((int)$row['invoice_id'], -$delta);
|
||||
}
|
||||
if (($row['status'] ?? '') === FinancialStatus::ADDITIONAL_CHARGE_APPLIED && !empty($row['invoice_id'])) {
|
||||
$db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $row['invoice_id']]);
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $row['invoice_id']);
|
||||
}
|
||||
|
||||
$db->transComplete();
|
||||
@@ -343,7 +343,7 @@ class ExtraChargesController extends BaseController
|
||||
'description' => trim($data['description'] ?? ''),
|
||||
'amount' => $signedAmount,
|
||||
'due_date' => !empty($data['due_date']) ? $data['due_date'] : null,
|
||||
'status' => $invoiceId ? 'applied' : 'pending',
|
||||
'status' => $invoiceId ? FinancialStatus::ADDITIONAL_CHARGE_APPLIED : FinancialStatus::ADDITIONAL_CHARGE_PENDING,
|
||||
'created_by' => (int)(session()->get('user_id') ?? 0),
|
||||
'created_at' => \CodeIgniter\I18n\Time::now('UTC')->toDateTimeString(), // store UTC
|
||||
];
|
||||
@@ -357,17 +357,9 @@ class ExtraChargesController extends BaseController
|
||||
$this->additionalChargeModel->insert($payload);
|
||||
$chargeId = (int)$this->additionalChargeModel->getInsertID();
|
||||
|
||||
// Apply to invoice if present
|
||||
if ($invoiceId) {
|
||||
try {
|
||||
if ($chargeType === 'add') {
|
||||
$this->invoiceModel->applyAdditionalCharge($invoiceId, $amountAbs);
|
||||
} else {
|
||||
$this->invoiceModel->deductAdditionalCharge($invoiceId, $amountAbs);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'apply/deductAdditionalCharge failed: ' . $e->getMessage());
|
||||
}
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$invoiceId]);
|
||||
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||
}
|
||||
|
||||
// AFTER
|
||||
@@ -470,23 +462,15 @@ class ExtraChargesController extends BaseController
|
||||
|
||||
$this->db->transStart();
|
||||
|
||||
if ($status === 'applied' && $invoiceId > 0 && $amountAbs > 0) {
|
||||
try {
|
||||
if ($chargeType === 'add') {
|
||||
$this->invoiceModel->reverseAdditionalCharge($invoiceId, $amountAbs);
|
||||
} else {
|
||||
// voiding a deduction -> add back
|
||||
$this->invoiceModel->applyAdditionalCharge($invoiceId, $amountAbs);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'void(): invoice adjust failed: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
$this->additionalChargeModel->update((int)$id, [
|
||||
'status' => 'void',
|
||||
'status' => FinancialStatus::ADDITIONAL_CHARGE_VOIDED,
|
||||
]);
|
||||
|
||||
if ($status === FinancialStatus::ADDITIONAL_CHARGE_APPLIED && $invoiceId > 0) {
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$invoiceId]);
|
||||
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||
}
|
||||
|
||||
$this->db->transComplete();
|
||||
|
||||
if (!$this->db->transStatus()) {
|
||||
@@ -514,26 +498,19 @@ class ExtraChargesController extends BaseController
|
||||
$chargeType = (string)($row['charge_type'] ?? 'add');
|
||||
$status = (string)($row['status'] ?? 'pending');
|
||||
|
||||
if ($status !== 'applied' || $invoiceId <= 0 || $amountAbs <= 0) {
|
||||
if ($status !== FinancialStatus::ADDITIONAL_CHARGE_APPLIED || $invoiceId <= 0 || $amountAbs <= 0) {
|
||||
if ($this->wantsJson()) return $this->response->setJSON(['ok' => false, 'error' => 'Nothing to reverse']);
|
||||
return redirect()->back()->with('error', 'Nothing to reverse.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
try {
|
||||
if ($chargeType === 'add') {
|
||||
$this->invoiceModel->reverseAdditionalCharge($invoiceId, $amountAbs);
|
||||
} else {
|
||||
$this->invoiceModel->applyAdditionalCharge($invoiceId, $amountAbs);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'reverse(): invoice adjust failed: ' . $e->getMessage());
|
||||
}
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$invoiceId]);
|
||||
|
||||
$this->additionalChargeModel->update((int)$id, [
|
||||
'status' => 'pending',
|
||||
'status' => FinancialStatus::ADDITIONAL_CHARGE_PENDING,
|
||||
'invoice_id' => null,
|
||||
]);
|
||||
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||
|
||||
$this->db->transComplete();
|
||||
|
||||
|
||||
@@ -150,10 +150,12 @@ class FamilyAdminController extends BaseController
|
||||
}
|
||||
|
||||
// Recent payments (limit 10)
|
||||
$payRows = $db->table('payments')
|
||||
->select('id, parent_id, invoice_id, paid_amount, balance, payment_method, payment_date, status')
|
||||
->whereIn('parent_id', $parentIds)
|
||||
->orderBy('payment_date', 'DESC')
|
||||
$payRows = $db->table('payments p')
|
||||
->select('p.id, p.parent_id, p.invoice_id, p.paid_amount, p.payment_method, p.payment_date, p.status AS payment_status, p.installment_seq, p.number_of_installments, i.invoice_number, i.balance AS invoice_current_balance, i.status AS invoice_status, i.school_year')
|
||||
->join('invoices i', 'i.id = p.invoice_id', 'inner')
|
||||
->whereIn('p.parent_id', $parentIds)
|
||||
->orderBy('p.payment_date', 'DESC')
|
||||
->orderBy('p.id', 'DESC')
|
||||
->limit(10)
|
||||
->get()->getResultArray();
|
||||
$fam['payments'] = $payRows;
|
||||
@@ -395,10 +397,12 @@ class FamilyAdminController extends BaseController
|
||||
}
|
||||
|
||||
// Payments
|
||||
$payRows = $db->table('payments')
|
||||
->select('id, parent_id, invoice_id, paid_amount, balance, payment_method, payment_date, status')
|
||||
->whereIn('parent_id', $parentIds)
|
||||
->orderBy('payment_date', 'DESC')
|
||||
$payRows = $db->table('payments p')
|
||||
->select('p.id, p.parent_id, p.invoice_id, p.paid_amount, p.payment_method, p.payment_date, p.status AS payment_status, p.installment_seq, p.number_of_installments, i.invoice_number, i.balance AS invoice_current_balance, i.status AS invoice_status, i.school_year')
|
||||
->join('invoices i', 'i.id = p.invoice_id', 'inner')
|
||||
->whereIn('p.parent_id', $parentIds)
|
||||
->orderBy('p.payment_date', 'DESC')
|
||||
->orderBy('p.id', 'DESC')
|
||||
->limit(10)
|
||||
->get()->getResultArray();
|
||||
$family['payments'] = $payRows;
|
||||
|
||||
@@ -4,7 +4,6 @@ namespace App\Controllers\View;
|
||||
|
||||
use CodeIgniter\Controller;
|
||||
use CodeIgniter\Exceptions\PageNotFoundException;
|
||||
use Config\Database;
|
||||
|
||||
class FilesController extends Controller
|
||||
{
|
||||
@@ -22,7 +21,11 @@ class FilesController extends Controller
|
||||
throw PageNotFoundException::forPageNotFound();
|
||||
}
|
||||
|
||||
// 3) Build path under writable
|
||||
$expense = $this->expenseRecordForFile($name);
|
||||
if ($expense === null || !$this->canViewExpenseFile($expense)) {
|
||||
return $this->response->setStatusCode(403, 'You are not allowed to access this file.');
|
||||
}
|
||||
|
||||
$path = WRITEPATH . 'uploads/receipts/' . $name;
|
||||
if (!is_file($path)) {
|
||||
throw PageNotFoundException::forPageNotFound();
|
||||
@@ -79,7 +82,11 @@ class FilesController extends Controller
|
||||
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
|
||||
}
|
||||
|
||||
// 3) Build path under writable (REIMBURSEMENTS)
|
||||
$reimbursement = $this->reimbursementRecordForFile($name);
|
||||
if ($reimbursement === null || !$this->canViewReimbursementFile($reimbursement)) {
|
||||
return $this->response->setStatusCode(403, 'You are not allowed to access this file.');
|
||||
}
|
||||
|
||||
$path = WRITEPATH . 'uploads/reimbursements/' . $name;
|
||||
if (!is_file($path)) {
|
||||
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
|
||||
@@ -425,4 +432,69 @@ class FilesController extends Controller
|
||||
|
||||
return $draftSemester === '' || $currentSemester === '' || $draftSemester === $currentSemester;
|
||||
}
|
||||
|
||||
private function expenseRecordForFile(string $name): ?array
|
||||
{
|
||||
return \Config\Database::connect()
|
||||
->table('expenses')
|
||||
->where('receipt_path', $name)
|
||||
->get()
|
||||
->getRowArray();
|
||||
}
|
||||
|
||||
private function reimbursementRecordForFile(string $name): ?array
|
||||
{
|
||||
return \Config\Database::connect()
|
||||
->table('reimbursements')
|
||||
->where('receipt_path', $name)
|
||||
->get()
|
||||
->getRowArray();
|
||||
}
|
||||
|
||||
private function canViewExpenseFile(array $expense): bool
|
||||
{
|
||||
if ($this->hasFinancialStaffAccess()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$userId = (int) (session()->get('user_id') ?? 0);
|
||||
|
||||
return $userId > 0 && in_array($userId, [
|
||||
(int) ($expense['purchased_by'] ?? 0),
|
||||
(int) ($expense['added_by'] ?? 0),
|
||||
(int) ($expense['approved_by'] ?? 0),
|
||||
], true);
|
||||
}
|
||||
|
||||
private function canViewReimbursementFile(array $reimbursement): bool
|
||||
{
|
||||
if ($this->hasFinancialStaffAccess()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$userId = (int) (session()->get('user_id') ?? 0);
|
||||
|
||||
return $userId > 0 && in_array($userId, [
|
||||
(int) ($reimbursement['reimbursed_to'] ?? 0),
|
||||
(int) ($reimbursement['approved_by'] ?? 0),
|
||||
(int) ($reimbursement['added_by'] ?? 0),
|
||||
], true);
|
||||
}
|
||||
|
||||
private function hasFinancialStaffAccess(): bool
|
||||
{
|
||||
$roles = array_map('strtolower', (array) (session()->get('roles') ?? []));
|
||||
$activeRole = strtolower((string) (session()->get('role') ?? ''));
|
||||
if ($activeRole !== '' && !in_array($activeRole, $roles, true)) {
|
||||
$roles[] = $activeRole;
|
||||
}
|
||||
|
||||
foreach (['administrator', 'administrative staff', 'principal', 'teacher', 'teacher_assistant'] as $role) {
|
||||
if (in_array($role, $roles, true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -74,7 +74,7 @@ class InvoiceController extends ResourceController
|
||||
$this->dueDate = $this->configModel->getConfig('due_date');
|
||||
$this->firstStudentFee = (float) ($this->configModel->getConfig('first_student_fee') ?? 350);
|
||||
$this->secondStudentFee = (float) ($this->configModel->getConfig('second_student_fee') ?? 200);
|
||||
$this->youthFee = (float) ($this->configModel->getConfig('youth_fee') ?? 180);
|
||||
$this->youthFee = (float) ($this->configModel->getConfig('youth_fee') ?? 200);
|
||||
$this->refundDeadline = date('Y-m-d', strtotime($this->configModel->getConfig('refund_deadline')));
|
||||
$this->db = \Config\Database::connect();
|
||||
$this->request = \Config\Services::request();
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace App\Controllers\View;
|
||||
|
||||
use App\Libraries\FinancialAttachmentService;
|
||||
use App\Libraries\FinancialStatus;
|
||||
use App\Libraries\InvoiceLedgerService;
|
||||
use App\Models\PaymentModel;
|
||||
use App\Models\AdditionalChargeModel;
|
||||
use App\Models\ClassSectionModel;
|
||||
@@ -16,23 +19,14 @@ use App\Models\PaymentErrorModel;
|
||||
use App\Models\InvoiceModel;
|
||||
use App\Models\TeacherClassModel;
|
||||
use App\Models\DiscountUsageModel;
|
||||
use Config\PaypalConfig;
|
||||
use PayPal\Api\Amount;
|
||||
use PayPal\Api\Payment;
|
||||
use PayPal\Api\PaymentExecution;
|
||||
use PayPal\Api\Payer;
|
||||
use PayPal\Api\Transaction;
|
||||
use PayPal\Rest\ApiContext;
|
||||
use PayPal\Auth\OAuthTokenCredential;
|
||||
|
||||
use CodeIgniter\RESTful\ResourceController;
|
||||
use CodeIgniter\Events\Events;
|
||||
use CodeIgniter\Exceptions\PageNotFoundException;
|
||||
|
||||
class PaymentController extends ResourceController
|
||||
{
|
||||
protected $paymentModel;
|
||||
protected $paypalConfig;
|
||||
protected $apiContext;
|
||||
protected $request;
|
||||
protected $db;
|
||||
protected $invoiceModel;
|
||||
@@ -51,6 +45,8 @@ class PaymentController extends ResourceController
|
||||
protected $discountUsageModel;
|
||||
protected $additionalChargeModel;
|
||||
protected $classSectionModel;
|
||||
protected $invoiceLedgerService;
|
||||
protected $financialAttachmentService;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
@@ -60,7 +56,6 @@ class PaymentController extends ResourceController
|
||||
$this->eventChargesModel = new EventChargesModel();
|
||||
$this->manualPaymentModel = new ManualPaymentModel();
|
||||
$this->paymentModel = new PaymentModel();
|
||||
$this->paypalConfig = new PaypalConfig();
|
||||
$this->request = \Config\Services::request();
|
||||
$this->db = \Config\Database::connect();
|
||||
$this->invoiceModel = new InvoiceModel();
|
||||
@@ -74,19 +69,8 @@ class PaymentController extends ResourceController
|
||||
$this->discountUsageModel = new DiscountUsageModel();
|
||||
$this->additionalChargeModel = new AdditionalChargeModel();
|
||||
$this->classSectionModel = new ClassSectionModel();
|
||||
|
||||
// Set up PayPal API context
|
||||
$this->apiContext = new ApiContext(
|
||||
new OAuthTokenCredential(
|
||||
$this->paypalConfig->paypalClientId,
|
||||
$this->paypalConfig->paypalSecret
|
||||
)
|
||||
);
|
||||
|
||||
$this->apiContext->setConfig([
|
||||
'mode' => $this->paypalConfig->paypalMode, // 'sandbox' or 'live'
|
||||
'http.headers' => ['Connection' => 'Close']
|
||||
]);
|
||||
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||
$this->financialAttachmentService = new FinancialAttachmentService();
|
||||
}
|
||||
|
||||
// API: Create a new payment plan
|
||||
@@ -101,7 +85,6 @@ class PaymentController extends ResourceController
|
||||
'payment_date' => $this->request->getPost('payment_date'),
|
||||
'payment_type' => $this->request->getPost('payment_type'),
|
||||
'status' => 'Pending',
|
||||
'semester' => $this->request->getPost('semester'),
|
||||
'school_year' => $this->request->getPost('school_year'),
|
||||
];
|
||||
|
||||
@@ -115,7 +98,8 @@ class PaymentController extends ResourceController
|
||||
// API: Get payments by parent ID
|
||||
public function getByParentAPI($parentId)
|
||||
{
|
||||
$payments = $this->paymentModel->getPaymentsByParentId($parentId);
|
||||
$selectedYear = $this->getSelectedPaymentHistoryYear();
|
||||
$payments = $this->paymentModel->getPaymentsByParentId((int) $parentId, $selectedYear);
|
||||
if ($payments) {
|
||||
return $this->respond($payments);
|
||||
} else {
|
||||
@@ -126,13 +110,8 @@ class PaymentController extends ResourceController
|
||||
// View: Get payments by parent ID (for web views)
|
||||
public function getByParent($parentId)
|
||||
{
|
||||
// Fetch payments with invoice number (if available)
|
||||
$payments = $this->paymentModel
|
||||
->select('payments.*, invoices.invoice_number')
|
||||
->join('invoices', 'invoices.id = payments.invoice_id', 'left')
|
||||
->where('payments.parent_id', (int)$parentId)
|
||||
->orderBy('payments.payment_date', 'DESC')
|
||||
->findAll();
|
||||
$selectedYear = $this->getSelectedPaymentHistoryYear();
|
||||
$payments = $this->paymentModel->getPaymentsByParentId((int) $parentId, $selectedYear);
|
||||
|
||||
// Parent display name
|
||||
$parent = $this->userModel->select('firstname, lastname')->find((int)$parentId) ?: [];
|
||||
@@ -156,6 +135,13 @@ class PaymentController extends ResourceController
|
||||
]);
|
||||
}
|
||||
|
||||
private function getSelectedPaymentHistoryYear(): ?string
|
||||
{
|
||||
$selectedYear = $this->request->getGet('school_year') ?? $this->schoolYear;
|
||||
|
||||
return $selectedYear !== '' ? $selectedYear : null;
|
||||
}
|
||||
|
||||
// View: Create a new payment plan
|
||||
public function create()
|
||||
{
|
||||
@@ -185,135 +171,11 @@ class PaymentController extends ResourceController
|
||||
}
|
||||
|
||||
|
||||
// Create a PayPal payment
|
||||
public function createPaypalPayment($paymentId)
|
||||
{
|
||||
// Fetch the payment details from the database
|
||||
$payment = $this->paymentModel->find($paymentId);
|
||||
|
||||
// Create the payer object (who is making the payment)
|
||||
$payer = new Payer();
|
||||
$payer->setPaymentMethod('paypal');
|
||||
|
||||
// Set up the payment amount
|
||||
$amount = new Amount();
|
||||
$amount->setCurrency('USD')
|
||||
->setTotal($payment['balance_amount']); // The balance amount to be paid
|
||||
|
||||
// Set up the transaction details
|
||||
$transaction = new Transaction();
|
||||
$transaction->setAmount($amount)
|
||||
->setDescription('Payment for school fees')
|
||||
->setInvoiceNumber(uniqid());
|
||||
|
||||
// Create the payment and set the redirect URLs
|
||||
$payment = new Payment();
|
||||
$payment->setIntent('sale')
|
||||
->setPayer($payer)
|
||||
->setTransactions([$transaction]);
|
||||
|
||||
// Set the approval URL for the payment
|
||||
$redirectUrls = new \PayPal\Api\RedirectUrls();
|
||||
$redirectUrls->setReturnUrl(base_url('payments/executePaypalPayment')) // Set this to where the user will be redirected after approval
|
||||
->setCancelUrl(base_url('payments/cancelPaypalPayment'));
|
||||
|
||||
$payment->setRedirectUrls($redirectUrls);
|
||||
|
||||
// Create the payment and get the approval URL
|
||||
try {
|
||||
$payment->create($this->apiContext);
|
||||
// Store the payment ID in the session to retrieve it later
|
||||
session()->set('paypalPaymentId', $payment->getId());
|
||||
session()->set('paymentId', $paymentId);
|
||||
$approvalUrl = $payment->getApprovalLink();
|
||||
|
||||
return redirect()->to($approvalUrl); // Redirect the user to PayPal's approval page
|
||||
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
|
||||
// Handle errors
|
||||
echo $ex->getData();
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the PayPal payment after user approval
|
||||
public function executePaypalPayment()
|
||||
{
|
||||
// Get the payment ID and Payer ID from the request
|
||||
$paymentId = session()->get('paypalPaymentId');
|
||||
$payerId = $this->request->getGet('PayerID');
|
||||
|
||||
// Get the payment object using the payment ID
|
||||
$payment = Payment::get($paymentId, $this->apiContext);
|
||||
|
||||
// Create an execution object to execute the payment
|
||||
$execution = new PaymentExecution();
|
||||
$execution->setPayerId($payerId);
|
||||
|
||||
// Execute the payment
|
||||
try {
|
||||
$result = $payment->execute($execution, $this->apiContext);
|
||||
|
||||
// Payment successful, update the payment status in the database
|
||||
$paymentId = session()->get('paymentId');
|
||||
$this->paymentModel->update($paymentId, ['status' => 'Completed']);
|
||||
|
||||
return redirect()->to('/payments'); // Redirect to the payments page after success
|
||||
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
|
||||
// Handle payment execution failure
|
||||
echo $ex->getData();
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
// Cancel the PayPal payment
|
||||
public function cancelPaypalPayment()
|
||||
{
|
||||
// Payment was canceled by the user
|
||||
return redirect()->to('/payments')->with('error', 'Payment was canceled.');
|
||||
}
|
||||
|
||||
|
||||
public function redirectPage()
|
||||
{
|
||||
$modeCheck = $this->configModel->getConfig('paypal_mode');
|
||||
|
||||
$parentId = session()->get('user_id'); // assuming this is the logged-in parent
|
||||
|
||||
// Get parent name and school ID
|
||||
$parent = $this->db->table('users')
|
||||
->select('firstname, lastname, school_id')
|
||||
->where('id', $parentId)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
$parentName = isset($parent['firstname'], $parent['lastname'])
|
||||
? $parent['firstname'] . ' ' . $parent['lastname']
|
||||
: 'Parent';
|
||||
|
||||
$schoolId = $parent['school_id'] ?? null;
|
||||
|
||||
// Get latest invoice total_amount
|
||||
$latestInvoice = $this->invoiceModel->where('parent_id', $parentId)
|
||||
->orderBy('created_at', 'DESC')
|
||||
->select('total_amount')
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
$totalAmount = $latestInvoice['total_amount'] ?? 0;
|
||||
|
||||
return view('payment/payment_redirect', [
|
||||
'parentName' => $parentName,
|
||||
'totalAmount' => $totalAmount,
|
||||
'schoolId' => $schoolId,
|
||||
'modeCheck' => $modeCheck,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
public function paypal()
|
||||
{
|
||||
// Redirect to PayPal API or show instructions
|
||||
return redirect()->to('https://www.paypal.com/ncp/payment/87FJL3EV8C7NE');
|
||||
return redirect()
|
||||
->to(site_url('parent/invoice_payment'))
|
||||
->with('info', 'Online payment is currently unavailable. Please contact the school office to complete payment.');
|
||||
}
|
||||
|
||||
public function manual()
|
||||
@@ -329,11 +191,7 @@ class PaymentController extends ResourceController
|
||||
|
||||
// Handle file upload if present
|
||||
$proof = $this->request->getFile('proof');
|
||||
if ($proof && $proof->isValid() && !$proof->hasMoved()) {
|
||||
$filename = $proof->getRandomName();
|
||||
$proof->move(WRITEPATH . 'uploads/payments/', $filename);
|
||||
$data['proof_path'] = $filename;
|
||||
}
|
||||
$data['proof_path'] = $this->financialAttachmentService->saveUploadedFile($proof, 'payments');
|
||||
|
||||
$this->manualPaymentModel->insert($data);
|
||||
|
||||
@@ -490,12 +348,12 @@ class PaymentController extends ResourceController
|
||||
->where('parent_id', $parentId)
|
||||
->findAll();
|
||||
|
||||
// Payments (paginated)
|
||||
$payments = $this->paymentModel
|
||||
->where('parent_id', $parentId)
|
||||
->orderBy('payment_date', 'DESC')
|
||||
->paginate(10);
|
||||
$pager = $this->paymentModel->pager;
|
||||
// Payments (paginated). Join invoices so history is filtered by invoice term
|
||||
// and displays current invoice state instead of stale payment snapshots.
|
||||
$selectedYear = $this->getSelectedPaymentHistoryYear();
|
||||
$paymentHistory = $this->paymentModel->parentPaymentHistoryQuery($parentId, $selectedYear);
|
||||
$payments = $paymentHistory->paginate(10);
|
||||
$pager = $paymentHistory->pager;
|
||||
|
||||
// Invoices
|
||||
$rawInvoices = $this->invoiceModel
|
||||
@@ -1057,26 +915,13 @@ class PaymentController extends ResourceController
|
||||
// Optional receipt upload
|
||||
$checkFile = null;
|
||||
$paymentFile = $this->request->getFile('payment_file');
|
||||
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) {
|
||||
$okTypes = ['image/jpeg', 'image/png', 'application/pdf'];
|
||||
$okExts = ['jpg', 'jpeg', 'png', 'pdf'];
|
||||
|
||||
$mime = $paymentFile->getMimeType();
|
||||
$ext = strtolower($paymentFile->getClientExtension());
|
||||
|
||||
if (!in_array($mime, $okTypes, true) || !in_array($ext, $okExts, true)) {
|
||||
return redirect()->back()->withInput()->with('error', 'Unsupported file type. Use JPG, PNG, or PDF.');
|
||||
}
|
||||
if ($paymentFile->getSize() > 5 * 1024 * 1024) {
|
||||
return redirect()->back()->withInput()->with('error', 'File too large. Max 5MB.');
|
||||
}
|
||||
|
||||
$fileName = $paymentFile->getRandomName();
|
||||
$subdir = ($paymentMethod === 'check') ? 'checks' : (($paymentMethod === 'card') ? 'cards' : 'misc');
|
||||
$targetDir = WRITEPATH . 'uploads/' . $subdir . '/';
|
||||
if (!is_dir($targetDir)) @mkdir($targetDir, 0775, true);
|
||||
$paymentFile->move($targetDir, $fileName);
|
||||
$checkFile = $fileName;
|
||||
try {
|
||||
$checkFile = $this->financialAttachmentService->saveUploadedFile(
|
||||
$paymentFile,
|
||||
$paymentMethod === 'check' ? 'checks' : ($paymentMethod === 'card' ? 'cards' : 'misc')
|
||||
);
|
||||
} catch (\RuntimeException $e) {
|
||||
return redirect()->back()->withInput()->with('error', $e->getMessage());
|
||||
}
|
||||
$this->db->transBegin();
|
||||
|
||||
@@ -1096,10 +941,7 @@ class PaymentController extends ResourceController
|
||||
$invYear = (string)($row['school_year'] ?? $this->schoolYear);
|
||||
|
||||
// Recompute invoice totals from tuition + events + additional charges
|
||||
$this->recalculateInvoice($invoiceId, $invYear);
|
||||
|
||||
// Authoritative balance
|
||||
$currentBalance = $this->getCurrentInvoiceBalance($invoiceId);
|
||||
$currentBalance = (float) $this->invoiceLedgerService->recalculateInvoice($invoiceId)['balance'];
|
||||
|
||||
if ($amount > $currentBalance + 0.00001) {
|
||||
$this->db->transRollback();
|
||||
@@ -1132,10 +974,11 @@ class PaymentController extends ResourceController
|
||||
$checkFile,
|
||||
$transactionId,
|
||||
$paymentDate,
|
||||
$this->schoolYear,
|
||||
$this->semester,
|
||||
$invYear,
|
||||
$checkNumber,
|
||||
$installmentSeq
|
||||
$installmentSeq,
|
||||
(array) $this->invoiceModel->find($invoiceId),
|
||||
$currentBalance
|
||||
);
|
||||
|
||||
if (!$ok) {
|
||||
@@ -1144,11 +987,10 @@ class PaymentController extends ResourceController
|
||||
}
|
||||
|
||||
// Ensure invoice totals/balance reflect discounts and this payment
|
||||
$this->recalculateInvoice($invoiceId, $this->schoolYear);
|
||||
$ledger = $this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||
|
||||
// Post-payment balance from snapshot
|
||||
$postBalance = (float)round($initialPreBalance - $amount, 2);
|
||||
if ($postBalance < 0) $postBalance = 0.0;
|
||||
$postBalance = (float) ($ledger['balance'] ?? max(0.0, round($initialPreBalance - $amount, 2)));
|
||||
|
||||
// Optional enrollment update
|
||||
$enrollmentupdated = $this->updateEnrollmentStatusIfPaid($invoiceId);
|
||||
@@ -1174,7 +1016,7 @@ class PaymentController extends ResourceController
|
||||
$rowParentDisc = $this->db->table('discount_usages')
|
||||
->selectSum('discount_amount', 'sum_disc')
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $this->schoolYear)
|
||||
->where('school_year', $invYear)
|
||||
->get()->getRowArray();
|
||||
if ($rowParentDisc && isset($rowParentDisc['sum_disc'])) {
|
||||
$parentYearDiscountTotal = (float)$rowParentDisc['sum_disc'];
|
||||
@@ -1235,21 +1077,22 @@ class PaymentController extends ResourceController
|
||||
$checkFile = $payment['check_file']; // default keep old file
|
||||
|
||||
// Handle optional check or card payment receipt upload
|
||||
try {
|
||||
$paymentFile = $this->request->getFile('payment_file');
|
||||
if (strtolower($paymentMethod) === 'check') {
|
||||
$paymentFile = $this->request->getFile('payment_file'); // ✅ Updated to payment_file
|
||||
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) {
|
||||
$fileName = $paymentFile->getRandomName();
|
||||
$paymentFile->move(WRITEPATH . 'uploads/checks/', $fileName);
|
||||
$checkFile = $fileName;
|
||||
$uploaded = $this->financialAttachmentService->saveUploadedFile($paymentFile, 'checks');
|
||||
if ($uploaded !== null) {
|
||||
$checkFile = $uploaded;
|
||||
}
|
||||
} elseif (strtolower($paymentMethod) === 'card') {
|
||||
$paymentFile = $this->request->getFile('payment_file'); // ✅ Updated to payment_file
|
||||
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) {
|
||||
$fileName = $paymentFile->getRandomName();
|
||||
$paymentFile->move(WRITEPATH . 'uploads/cards/', $fileName);
|
||||
$checkFile = $fileName; // reuse for compatibility
|
||||
$uploaded = $this->financialAttachmentService->saveUploadedFile($paymentFile, 'cards');
|
||||
if ($uploaded !== null) {
|
||||
$checkFile = $uploaded;
|
||||
}
|
||||
}
|
||||
} catch (\RuntimeException $e) {
|
||||
return redirect()->back()->withInput()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
// ❌ Validate amount - negative or zero
|
||||
if ($paidAmount <= 0) {
|
||||
@@ -1259,41 +1102,51 @@ class PaymentController extends ResourceController
|
||||
);
|
||||
}
|
||||
|
||||
// 🔄 Recalculate invoice first to ensure totals reflect tuition + events + additional
|
||||
$this->recalculateInvoice($payment['invoice_id'], $this->schoolYear);
|
||||
$this->db->transBegin();
|
||||
|
||||
// 🔄 Get current balance based on actual payments (with school_year filter)
|
||||
// We need to calculate what the balance would be WITHOUT the current payment being edited
|
||||
$currentBalance = $this->getCurrentInvoiceBalanceExcludingPayment($payment['invoice_id'], $paymentId);
|
||||
try {
|
||||
$invoiceId = (int) ($payment['invoice_id'] ?? 0);
|
||||
$lockedInvoice = $this->db->query(
|
||||
'SELECT id FROM invoices WHERE id = ? FOR UPDATE',
|
||||
[$invoiceId]
|
||||
)->getRowArray();
|
||||
|
||||
if ($paidAmount > $currentBalance) {
|
||||
if (!$lockedInvoice) {
|
||||
$this->db->transRollback();
|
||||
return redirect()->back()->with('error', 'Linked invoice not found.');
|
||||
}
|
||||
|
||||
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||
$currentBalance = $this->getCurrentInvoiceBalanceExcludingPayment($invoiceId, $paymentId);
|
||||
|
||||
if ($paidAmount > $currentBalance + 0.00001) {
|
||||
$this->db->transRollback();
|
||||
return redirect()->back()->with(
|
||||
'error',
|
||||
'Entered amount (' . number_format($paidAmount, 2) . ') exceeds remaining balance (' . number_format($currentBalance, 2) . ').'
|
||||
);
|
||||
}
|
||||
|
||||
// ✅ Update edited payment with check_number
|
||||
$updateData = [
|
||||
'paid_amount' => $paidAmount,
|
||||
'payment_method' => strtolower($paymentMethod),
|
||||
'check_file' => $checkFile,
|
||||
'updated_by' => session()->get('user_id')
|
||||
'check_number' => strtolower($paymentMethod) === 'check' ? $checkNumber : null,
|
||||
'balance' => max(0.0, round($currentBalance - $paidAmount, 2)),
|
||||
'status' => FinancialStatus::PAYMENT_RECORDED,
|
||||
'updated_by' => session()->get('user_id'),
|
||||
];
|
||||
|
||||
// ✅ Only add check_number if payment method is check
|
||||
if (strtolower($paymentMethod) === 'check') {
|
||||
$updateData['check_number'] = $checkNumber;
|
||||
} else {
|
||||
$updateData['check_number'] = null; // Clear check number for non-check payments
|
||||
}
|
||||
|
||||
$this->paymentModel->update($paymentId, $updateData);
|
||||
|
||||
// 🔄 Always recalc invoice after change
|
||||
$this->recalculateInvoice($payment['invoice_id'], $this->schoolYear);
|
||||
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||
$this->db->transCommit();
|
||||
|
||||
return redirect()->back()->with('success', 'Payment updated successfully.');
|
||||
} catch (\Throwable $e) {
|
||||
$this->db->transRollback();
|
||||
log_message('error', '[manualPayEdit] ' . $e->getMessage());
|
||||
return redirect()->back()->withInput()->with('error', 'Unexpected error while updating payment.');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1302,164 +1155,7 @@ class PaymentController extends ResourceController
|
||||
*/
|
||||
private function recalculateInvoice($invoiceId, $schoolYear)
|
||||
{
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) return;
|
||||
|
||||
$parentId = (int)($invoice['parent_id'] ?? 0);
|
||||
if ($parentId <= 0) return;
|
||||
|
||||
// ---- Tuition (recompute from enrollments) ----
|
||||
$enrollments = $this->enrollmentModel
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
|
||||
$registered = [];
|
||||
$withdrawn = [];
|
||||
foreach ($enrollments as $e) {
|
||||
$row = [
|
||||
'student_id' => (int)($e['student_id'] ?? 0),
|
||||
'class_section_id' => $e['class_section_id'] ?? null,
|
||||
'enrollment_status'=> (string)($e['enrollment_status'] ?? ''),
|
||||
];
|
||||
if (in_array($row['enrollment_status'], ['enrolled','payment pending'], true)) {
|
||||
$registered[] = $row;
|
||||
} elseif (in_array($row['enrollment_status'], ['withdrawn','refund pending','withdraw under review'], true)) {
|
||||
$withdrawn[] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
// Refund window check – if after deadline, withdrawn still billed
|
||||
$refundDeadline = (string)($this->configModel->getConfig('refund_deadline') ?? '');
|
||||
$refundAllowed = true;
|
||||
try {
|
||||
$tzName = (string) (config('School')->attendance['timezone'] ?? user_timezone());
|
||||
$tz = new \DateTimeZone($tzName);
|
||||
$today = new \DateTimeImmutable('today', $tz);
|
||||
$deadline = new \DateTimeImmutable($refundDeadline, $tz);
|
||||
$refundAllowed = $today <= $deadline;
|
||||
} catch (\Throwable $e) {
|
||||
$refundAllowed = true;
|
||||
}
|
||||
|
||||
$tuitionStudents = $registered;
|
||||
if (!$refundAllowed) {
|
||||
$tuitionStudents = array_merge($tuitionStudents, $withdrawn);
|
||||
}
|
||||
|
||||
$tuitionStudents = array_values(array_filter($tuitionStudents, function ($student) use ($schoolYear) {
|
||||
$sid = (int)($student['student_id'] ?? 0);
|
||||
return $sid > 0 && $this->studentClassModel->hasNonEventAssignment($sid, $schoolYear);
|
||||
}));
|
||||
|
||||
// Grade threshold and fees
|
||||
$gradeFee = (int)($this->configModel->getConfig('grade_fee') ?? 9);
|
||||
$firstStudentFee = (float)($this->configModel->getConfig('first_student_fee') ?? 350);
|
||||
$secondStudentFee = (float)($this->configModel->getConfig('second_student_fee') ?? 200);
|
||||
$youthFee = (float)($this->configModel->getConfig('youth_fee') ?? 180);
|
||||
|
||||
// Normalize grades for tuition students
|
||||
foreach ($tuitionStudents as &$s) {
|
||||
$name = null;
|
||||
if (!empty($s['class_section_id'])) {
|
||||
$name = $this->classSectionModel->getClassSectionNameBySectionId($s['class_section_id']);
|
||||
}
|
||||
$s['grade_name'] = is_string($name) ? strtoupper(trim($name)) : 'N/A';
|
||||
}
|
||||
unset($s);
|
||||
|
||||
// Count regular vs youth and compute tuition
|
||||
$regularCount = 0;
|
||||
$youthCount = 0;
|
||||
foreach ($tuitionStudents as $s) {
|
||||
$lvl = $this->parseGradeLevel($s['grade_name']);
|
||||
if ($lvl > $gradeFee) $youthCount++; else $regularCount++;
|
||||
}
|
||||
|
||||
$tuitionSubtotal = 0.0;
|
||||
$tuitionSubtotal += $youthCount * $youthFee;
|
||||
if ($regularCount >= 2) {
|
||||
$tuitionSubtotal += $firstStudentFee + ($regularCount - 1) * $secondStudentFee;
|
||||
} elseif ($regularCount === 1) {
|
||||
$tuitionSubtotal += $firstStudentFee;
|
||||
}
|
||||
|
||||
// ---- Event charges (parent-year) ----
|
||||
$eventSubtotal = 0.0;
|
||||
try {
|
||||
$events = $this->eventChargesModel->getChargesWithEventInfo($parentId, $schoolYear) ?? [];
|
||||
foreach ($events as $ev) { $eventSubtotal += (float)($ev['charged'] ?? 0.0); }
|
||||
} catch (\Throwable $e) {}
|
||||
|
||||
// ---- Additional charges (per-invoice) ----
|
||||
$additionalSubtotal = 0.0;
|
||||
try {
|
||||
$rows = $this->additionalChargeModel
|
||||
->select('charge_type, amount')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('status', 'applied')
|
||||
->findAll();
|
||||
foreach ($rows as $r) {
|
||||
$amt = (float)($r['amount'] ?? 0);
|
||||
$typ = strtolower((string)($r['charge_type'] ?? 'add'));
|
||||
if ($typ === 'deduct') $amt = -abs($amt); else $amt = abs($amt);
|
||||
$additionalSubtotal += $amt;
|
||||
}
|
||||
} catch (\Throwable $e) {}
|
||||
|
||||
$newTotal = round($tuitionSubtotal + $eventSubtotal + $additionalSubtotal, 2);
|
||||
|
||||
// ---- Payments / Discounts / Refunds ----
|
||||
$db = $this->db;
|
||||
$table = $this->paymentModel->table;
|
||||
$hasStatus = $db->fieldExists('status', $table);
|
||||
$hasVoid = $db->fieldExists('is_void', $table);
|
||||
$exclude = ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'];
|
||||
|
||||
$qb = $this->paymentModel
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('school_year', $schoolYear);
|
||||
|
||||
if ($hasStatus) {
|
||||
$qb->groupStart()
|
||||
->whereNotIn('status', $exclude)
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
if ($hasVoid) {
|
||||
$qb->groupStart()
|
||||
->where('is_void', 0)
|
||||
->orWhere('is_void IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
$payments = $qb->findAll();
|
||||
$totalPaid = 0.0;
|
||||
foreach ($payments as $p) { $totalPaid += (float)($p['paid_amount'] ?? 0); }
|
||||
|
||||
$discRow = $this->db->table('discount_usages')
|
||||
->select('COALESCE(SUM(discount_amount),0) AS total_disc')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->get()->getRowArray();
|
||||
$totalDisc = (float)($discRow['total_disc'] ?? 0);
|
||||
|
||||
$refundRow = $this->db->table('refunds')
|
||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->whereIn('status', ['Partial','Paid'])
|
||||
->get()->getRowArray();
|
||||
$totalRefundPaid = (float)($refundRow['total_refund_paid'] ?? 0);
|
||||
|
||||
$newBalance = max(0.0, $newTotal - $totalDisc - $totalPaid - $totalRefundPaid);
|
||||
$newStatus = ($newBalance <= 0.00001) ? 'Paid' : (($totalPaid > 0) ? 'Partially Paid' : 'Unpaid');
|
||||
|
||||
$this->invoiceModel->update($invoiceId, [
|
||||
'total_amount' => $newTotal,
|
||||
'paid_amount' => $totalPaid,
|
||||
'balance' => $newBalance,
|
||||
'status' => $newStatus,
|
||||
]);
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $invoiceId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1521,106 +1217,28 @@ class PaymentController extends ResourceController
|
||||
/** Get current invoice balance = total - payments - discounts - refundsPaid (no school_year filter). */
|
||||
private function getCurrentInvoiceBalance(int $invoiceId): float
|
||||
{
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) return 0.0;
|
||||
|
||||
$db = $this->db;
|
||||
$table = $this->paymentModel->table; // usually 'payments'
|
||||
$hasStatus = $db->fieldExists('status', $table);
|
||||
$hasVoid = $db->fieldExists('is_void', $table);
|
||||
|
||||
$qb = $this->paymentModel
|
||||
->select('COALESCE(SUM(paid_amount),0) AS total_paid')
|
||||
->where('invoice_id', $invoiceId);
|
||||
|
||||
if ($hasStatus) {
|
||||
$qb->groupStart()
|
||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
try {
|
||||
return (float) ($this->invoiceLedgerService->calculateInvoice($invoiceId)['balance'] ?? 0.0);
|
||||
} catch (\Throwable $e) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
if ($hasVoid) {
|
||||
$qb->groupStart()
|
||||
->where('is_void', 0)
|
||||
->orWhere('is_void IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
$row = $qb->first();
|
||||
$totalPaid = (float)($row['total_paid'] ?? 0);
|
||||
|
||||
// Discount sum on this invoice
|
||||
$discRow = $this->db->table('discount_usages')
|
||||
->select('COALESCE(SUM(discount_amount),0) AS total_disc')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->get()->getRowArray();
|
||||
$totalDisc = (float)($discRow['total_disc'] ?? 0);
|
||||
|
||||
// Refunds paid
|
||||
$refundRow = $this->db->table('refunds')
|
||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->whereIn('status', ['Partial','Paid'])
|
||||
->get()->getRowArray();
|
||||
$totalRefundPaid = (float)($refundRow['total_refund_paid'] ?? 0);
|
||||
|
||||
$total = (float)($invoice['total_amount'] ?? 0);
|
||||
|
||||
return max(0.0, round($total - $totalPaid - $totalDisc - $totalRefundPaid, 2));
|
||||
}
|
||||
|
||||
/** Balance excluding a specific payment (for edit scenarios) and subtracting discounts/refunds. */
|
||||
private function getCurrentInvoiceBalanceExcludingPayment(int $invoiceId, int $excludePaymentId): float
|
||||
{
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) return 0.0;
|
||||
|
||||
$db = $this->db;
|
||||
$table = $this->paymentModel->table;
|
||||
$hasStatus = $db->fieldExists('status', $table);
|
||||
$hasVoid = $db->fieldExists('is_void', $table);
|
||||
|
||||
$qb = $this->paymentModel
|
||||
->select('COALESCE(SUM(paid_amount),0) AS total_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('id !=', $excludePaymentId);
|
||||
|
||||
if ($hasStatus) {
|
||||
$qb->groupStart()
|
||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
$payment = $this->paymentModel->find($excludePaymentId);
|
||||
if (!$payment) {
|
||||
return $this->getCurrentInvoiceBalance($invoiceId);
|
||||
}
|
||||
|
||||
if ($hasVoid) {
|
||||
$qb->groupStart()
|
||||
->where('is_void', 0)
|
||||
->orWhere('is_void IS NULL', null, false)
|
||||
->groupEnd();
|
||||
$currentBalance = $this->getCurrentInvoiceBalance($invoiceId);
|
||||
$status = FinancialStatus::normalizePaymentStatus($payment['status'] ?? null);
|
||||
if (in_array($status, FinancialStatus::EXCLUDED_PAYMENT_STATUSES, true)) {
|
||||
return $currentBalance;
|
||||
}
|
||||
|
||||
$row = $qb->first();
|
||||
$totalPaid = (float)($row['total_paid'] ?? 0);
|
||||
|
||||
// Discount sum on this invoice
|
||||
$discRow = $this->db->table('discount_usages')
|
||||
->select('COALESCE(SUM(discount_amount),0) AS total_disc')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->get()->getRowArray();
|
||||
$totalDisc = (float)($discRow['total_disc'] ?? 0);
|
||||
|
||||
// Refunds paid
|
||||
$refundRow = $this->db->table('refunds')
|
||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->whereIn('status', ['Partial','Paid'])
|
||||
->get()->getRowArray();
|
||||
$totalRefundPaid = (float)($refundRow['total_refund_paid'] ?? 0);
|
||||
|
||||
$total = (float)($invoice['total_amount'] ?? 0);
|
||||
|
||||
return max(0.0, round($total - $totalPaid - $totalDisc - $totalRefundPaid, 2));
|
||||
return max(0.0, round($currentBalance + (float) ($payment['paid_amount'] ?? 0), 2));
|
||||
}
|
||||
|
||||
|
||||
@@ -1653,11 +1271,12 @@ class PaymentController extends ResourceController
|
||||
$transactionId = null,
|
||||
$paymentDate = null,
|
||||
$schoolYear = null,
|
||||
$semester = null,
|
||||
$checkNumber = null,
|
||||
?int $installmentSeq = null // <-- NOW: the installment sequence (1,2,3,...) for this invoice
|
||||
?int $installmentSeq = null,
|
||||
?array $invoice = null,
|
||||
?float $currentBalance = null
|
||||
) {
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
$invoice = $invoice ?? $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) {
|
||||
return false;
|
||||
}
|
||||
@@ -1678,32 +1297,9 @@ class PaymentController extends ResourceController
|
||||
}
|
||||
|
||||
|
||||
// Compute new totals
|
||||
$newPaid = (float) $invoice['paid_amount'] + (float) $amount;
|
||||
$newBalance = (float) $invoice['balance'] - (float) $amount;
|
||||
if ($newBalance == $invoice['total_amount']) {
|
||||
$paymentStatus = 'Unpaid';
|
||||
} elseif ($newBalance > 0 && $newBalance < $invoice['total_amount']) {
|
||||
$paymentStatus = 'Partially Paid';
|
||||
} elseif ($newBalance <= 0.00001) {
|
||||
$paymentStatus = 'Paid';
|
||||
} else {
|
||||
$paymentStatus = $invoice['status']; // fallback
|
||||
}
|
||||
$preBalance = $currentBalance ?? $this->getCurrentInvoiceBalance((int) $invoiceId);
|
||||
$newBalance = max(0.0, round($preBalance - (float) $amount, 2));
|
||||
|
||||
// Update invoice
|
||||
$invoiceUpdateData = [
|
||||
'paid_amount' => $newPaid,
|
||||
'balance' => $newBalance,
|
||||
'status' => $paymentStatus,
|
||||
'updated_by' => session()->get('user_id'),
|
||||
];
|
||||
if (!$this->invoiceModel->update($invoiceId, $invoiceUpdateData)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Store the *sequence* in number_of_installments (kept for schema compatibility)
|
||||
// Consider renaming the column to `installment_seq` in a future migration.
|
||||
$paymentData = [
|
||||
'parent_id' => $invoice['parent_id'],
|
||||
'invoice_id' => $invoiceId,
|
||||
@@ -1711,16 +1307,15 @@ class PaymentController extends ResourceController
|
||||
'paid_amount' => $amount,
|
||||
'balance' => $newBalance,
|
||||
'number_of_installments' => $installmentSeq, // <-- installment sequence (1,2,3,...)
|
||||
'installment_seq' => $installmentSeq,
|
||||
'transaction_id' => $transactionId,
|
||||
'payment_method' => strtolower($paymentMethod),
|
||||
'payment_date' => $paymentDate,
|
||||
'status' => $paymentStatus,
|
||||
'status' => FinancialStatus::PAYMENT_RECORDED,
|
||||
'check_file' => $checkFile,
|
||||
'check_number' => (strtolower($paymentMethod) === 'check') ? $checkNumber : null,
|
||||
'updated_by' => session()->get('user_id'),
|
||||
'school_year' => $schoolYear ?? $this->schoolYear,
|
||||
'semester' => $semester ?? $this->semester,
|
||||
// 'installment_index' => $installmentSeq, // use if you add a dedicated column later
|
||||
'school_year' => $schoolYear ?? ($invoice['school_year'] ?? $this->schoolYear),
|
||||
];
|
||||
|
||||
if (!$this->paymentModel->insert($paymentData)) {
|
||||
@@ -1741,35 +1336,53 @@ class PaymentController extends ResourceController
|
||||
->countAllResults();
|
||||
}
|
||||
|
||||
public function serveCheckFile($filename, $mode = 'download')
|
||||
public function servePaymentFile(int $paymentId, string $mode = 'download')
|
||||
{
|
||||
$filename = basename($filename);
|
||||
$roots = [
|
||||
WRITEPATH . 'uploads/checks/' . $filename,
|
||||
WRITEPATH . 'uploads/cards/' . $filename,
|
||||
WRITEPATH . 'uploads/misc/' . $filename,
|
||||
WRITEPATH . 'uploads/' . $filename, // final fallback
|
||||
];
|
||||
|
||||
$path = null;
|
||||
foreach ($roots as $candidate) {
|
||||
if (is_file($candidate)) {
|
||||
$path = $candidate;
|
||||
break;
|
||||
}
|
||||
$payment = $this->paymentModel->find($paymentId);
|
||||
if (!$payment || empty($payment['check_file'])) {
|
||||
throw PageNotFoundException::forPageNotFound('Payment file not found.');
|
||||
}
|
||||
|
||||
if (!$path) {
|
||||
throw new \CodeIgniter\Exceptions\PageNotFoundException('Payment file not found: ' . esc($filename));
|
||||
if (!$this->canViewPayment($payment)) {
|
||||
return $this->response->setStatusCode(403);
|
||||
}
|
||||
|
||||
$subdir = match (strtolower((string) ($payment['payment_method'] ?? ''))) {
|
||||
'check' => 'checks',
|
||||
'card', 'debit/credit card' => 'cards',
|
||||
default => 'misc',
|
||||
};
|
||||
|
||||
$path = $this->financialAttachmentService->resolvePath($subdir, (string) $payment['check_file']);
|
||||
if ($path === null) {
|
||||
throw PageNotFoundException::forPageNotFound('Payment file not found.');
|
||||
}
|
||||
|
||||
if ($mode === 'inline') {
|
||||
return $this->response
|
||||
->setHeader('Content-Type', mime_content_type($path))
|
||||
->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"')
|
||||
->setHeader('Content-Type', $this->financialAttachmentService->detectMime($path))
|
||||
->setHeader('Content-Disposition', 'inline; filename="' . basename($path) . '"')
|
||||
->setBody(file_get_contents($path));
|
||||
}
|
||||
|
||||
return $this->response->download($path, null);
|
||||
}
|
||||
|
||||
private function canViewPayment(array $payment): bool
|
||||
{
|
||||
$roles = array_map('strtolower', (array) (session()->get('roles') ?? []));
|
||||
$activeRole = strtolower((string) (session()->get('role') ?? ''));
|
||||
if ($activeRole !== '' && !in_array($activeRole, $roles, true)) {
|
||||
$roles[] = $activeRole;
|
||||
}
|
||||
|
||||
$staffRoles = ['administrator', 'administrative staff', 'principal', 'teacher', 'teacher_assistant'];
|
||||
foreach ($staffRoles as $role) {
|
||||
if (in_array($role, $roles, true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return in_array('parent', $roles, true) && (int) ($payment['parent_id'] ?? 0) === (int) session()->get('user_id');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\View;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Models\PayPalPaymentModel;
|
||||
use App\Models\PaymentModel;
|
||||
use App\Models\UserModel;
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\InvoiceModel;
|
||||
|
||||
class PaypalTransactionsController extends BaseController
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$model = new PayPalPaymentModel();
|
||||
|
||||
$keyword = $this->request->getGet('q');
|
||||
$perPage = 10;
|
||||
|
||||
if ($keyword) {
|
||||
$transactions = $model
|
||||
->groupStart()
|
||||
->like('transaction_id', $keyword)
|
||||
->orLike('payer_email', $keyword)
|
||||
->orLike('event_type', $keyword)
|
||||
->orLike('order_id', $keyword)
|
||||
->orLike('parent_school_id', $keyword)
|
||||
->groupEnd()
|
||||
->orderBy('created_at', 'DESC')
|
||||
->paginate($perPage);
|
||||
} else {
|
||||
$transactions = $model
|
||||
->orderBy('created_at', 'DESC')
|
||||
->paginate($perPage);
|
||||
}
|
||||
|
||||
return view('administrator/paypal_transactions', [
|
||||
'transactions' => $transactions,
|
||||
'pager' => $model->pager,
|
||||
'keyword' => $keyword
|
||||
]);
|
||||
}
|
||||
|
||||
public function exportCsv()
|
||||
{
|
||||
$model = new PayPalPaymentModel();
|
||||
$keyword = $this->request->getGet('q');
|
||||
|
||||
if ($keyword) {
|
||||
$transactions = $model
|
||||
->groupStart()
|
||||
->like('transaction_id', $keyword)
|
||||
->orLike('payer_email', $keyword)
|
||||
->orLike('event_type', $keyword)
|
||||
->orLike('order_id', $keyword)
|
||||
->orLike('parent_school_id', $keyword)
|
||||
->groupEnd()
|
||||
->orderBy('created_at', 'DESC')
|
||||
->findAll();
|
||||
} else {
|
||||
$transactions = $model->orderBy('created_at', 'DESC')->findAll();
|
||||
}
|
||||
|
||||
$filename = 'paypal_transactions_' . date('Ymd_His') . '.csv';
|
||||
|
||||
header('Content-Type: text/csv');
|
||||
header("Content-Disposition: attachment; filename=\"$filename\"");
|
||||
|
||||
$output = fopen('php://output', 'w');
|
||||
|
||||
// CSV headers
|
||||
fputcsv($output, [
|
||||
'ID', 'Transaction ID', 'Order ID', 'Parent School ID',
|
||||
'Email', 'Amount', 'Net Amount', 'Currency',
|
||||
'Status', 'Event Type', 'Created At'
|
||||
]);
|
||||
|
||||
foreach ($transactions as $t) {
|
||||
fputcsv($output, [
|
||||
$t['id'],
|
||||
$t['transaction_id'],
|
||||
$t['order_id'],
|
||||
$t['parent_school_id'],
|
||||
$t['payer_email'],
|
||||
$t['amount'],
|
||||
$t['net_amount'],
|
||||
$t['currency'],
|
||||
$t['status'],
|
||||
$t['event_type'],
|
||||
$t['created_at'],
|
||||
]);
|
||||
}
|
||||
|
||||
fclose($output);
|
||||
exit;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,12 +3,15 @@
|
||||
namespace App\Controllers\View;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Libraries\FinancialAttachmentService;
|
||||
use App\Libraries\InvoiceLedgerService;
|
||||
use App\Models\RefundModel;
|
||||
use App\Models\UserModel;
|
||||
use App\Models\PaymentModel;
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\InvoiceModel;
|
||||
use App\Models\EnrollmentModel;
|
||||
use CodeIgniter\Exceptions\PageNotFoundException;
|
||||
|
||||
class RefundController extends BaseController
|
||||
{
|
||||
@@ -18,6 +21,8 @@ class RefundController extends BaseController
|
||||
protected ConfigurationModel $configModel;
|
||||
protected InvoiceModel $invoiceModel;
|
||||
protected EnrollmentModel $enrollmentModel;
|
||||
protected InvoiceLedgerService $invoiceLedgerService;
|
||||
protected FinancialAttachmentService $financialAttachmentService;
|
||||
protected $db;
|
||||
|
||||
// Allowed request types (mapped to your `refunds.request` column)
|
||||
@@ -33,6 +38,8 @@ class RefundController extends BaseController
|
||||
$this->configModel = new ConfigurationModel();
|
||||
$this->invoiceModel = new InvoiceModel();
|
||||
$this->enrollmentModel = new EnrollmentModel();
|
||||
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||
$this->financialAttachmentService = new FinancialAttachmentService();
|
||||
$this->db = \Config\Database::connect();
|
||||
}
|
||||
|
||||
@@ -445,6 +452,14 @@ class RefundController extends BaseController
|
||||
return $this->response->setJSON(['error' => 'Failed to create refund request.']);
|
||||
}
|
||||
|
||||
if (!empty($invoiceId)) {
|
||||
try {
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $invoiceId);
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'requestRefund recalc failed: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Fire refundPending notification/event for newly created refunds
|
||||
try {
|
||||
$user = $this->userModel->select('id, email, firstname, lastname')->find($parentId) ?: [];
|
||||
@@ -467,6 +482,18 @@ class RefundController extends BaseController
|
||||
// Approve refund (no money movement)
|
||||
public function approveRefund(int $refundId)
|
||||
{
|
||||
$refund = $this->refundModel->find($refundId);
|
||||
if (!$refund) {
|
||||
return $this->response->setJSON(['error' => 'Refund not found']);
|
||||
}
|
||||
|
||||
$this->db->transBegin();
|
||||
|
||||
try {
|
||||
if (!empty($refund['invoice_id'])) {
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $refund['invoice_id']]);
|
||||
}
|
||||
|
||||
$ok = $this->refundModel->update($refundId, [
|
||||
'status' => 'Approved',
|
||||
'approved_at' => utc_now(),
|
||||
@@ -475,12 +502,35 @@ class RefundController extends BaseController
|
||||
'updated_by' => session()->get('user_id'),
|
||||
]);
|
||||
|
||||
if (!empty($refund['invoice_id'])) {
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $refund['invoice_id']);
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
} catch (\Throwable $e) {
|
||||
$this->db->transRollback();
|
||||
log_message('error', 'approveRefund failed: ' . $e->getMessage());
|
||||
$ok = false;
|
||||
}
|
||||
|
||||
return $this->response->setJSON($ok ? ['success' => 'Refund approved'] : ['error' => 'Approve failed']);
|
||||
}
|
||||
|
||||
// Reject refund
|
||||
public function rejectRefund(int $refundId)
|
||||
{
|
||||
$refund = $this->refundModel->find($refundId);
|
||||
if (!$refund) {
|
||||
return $this->response->setJSON(['error' => 'Refund not found']);
|
||||
}
|
||||
|
||||
$this->db->transBegin();
|
||||
|
||||
try {
|
||||
if (!empty($refund['invoice_id'])) {
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $refund['invoice_id']]);
|
||||
}
|
||||
|
||||
$ok = $this->refundModel->update($refundId, [
|
||||
'status' => 'Rejected',
|
||||
'approved_at' => utc_now(),
|
||||
@@ -489,6 +539,17 @@ class RefundController extends BaseController
|
||||
'updated_by' => session()->get('user_id'),
|
||||
]);
|
||||
|
||||
if (!empty($refund['invoice_id'])) {
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $refund['invoice_id']);
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
} catch (\Throwable $e) {
|
||||
$this->db->transRollback();
|
||||
log_message('error', 'rejectRefund failed: ' . $e->getMessage());
|
||||
$ok = false;
|
||||
}
|
||||
|
||||
return $this->response->setJSON($ok ? ['success' => 'Refund rejected'] : ['error' => 'Reject failed']);
|
||||
}
|
||||
|
||||
@@ -526,17 +587,21 @@ class RefundController extends BaseController
|
||||
// Optional file upload for Check
|
||||
$checkFileName = $refund['check_file'] ?? null;
|
||||
if ($refundMethod === 'Check') {
|
||||
try {
|
||||
$checkFile = $this->request->getFile('check_file');
|
||||
if ($checkFile && $checkFile->isValid() && !$checkFile->hasMoved()) {
|
||||
$checkFileName = $checkFile->getRandomName();
|
||||
$checkFile->move(WRITEPATH . 'uploads/checks/', $checkFileName);
|
||||
$uploaded = $this->financialAttachmentService->saveUploadedFile($checkFile, 'checks');
|
||||
if ($uploaded !== null) {
|
||||
$checkFileName = $uploaded;
|
||||
}
|
||||
} catch (\RuntimeException $e) {
|
||||
return $this->response->setJSON(['error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
$newStatus = ($total < $target) ? 'Partial' : 'Paid';
|
||||
|
||||
$db = db_connect();
|
||||
$db->transStart();
|
||||
$db->transBegin();
|
||||
|
||||
// 0) If this refund is not tied to an invoice yet, assign it to the most overpaid invoice
|
||||
$assignInvoiceId = null;
|
||||
@@ -595,7 +660,12 @@ class RefundController extends BaseController
|
||||
}
|
||||
}
|
||||
|
||||
// 1) Update refund row
|
||||
try {
|
||||
$affectedInvoiceId = (int) ($assignInvoiceId ?? $refund['invoice_id'] ?? 0);
|
||||
if ($affectedInvoiceId > 0) {
|
||||
$db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$affectedInvoiceId]);
|
||||
}
|
||||
|
||||
$this->refundModel->update($refundId, [
|
||||
'refund_paid_amount' => $total,
|
||||
'status' => $newStatus,
|
||||
@@ -605,16 +675,17 @@ class RefundController extends BaseController
|
||||
'refund_method' => $refundMethod,
|
||||
'check_nbr' => $checkNbr,
|
||||
'check_file' => $checkFileName,
|
||||
// tie to invoice if determined
|
||||
'invoice_id' => $assignInvoiceId ?? $refund['invoice_id'],
|
||||
'invoice_id' => $affectedInvoiceId ?: null,
|
||||
]);
|
||||
|
||||
// 2) Optional: If you want an accounting journal entry for payouts, write to a dedicated table.
|
||||
// We no longer insert a negative row into payments to avoid schema/validation conflicts.
|
||||
if ($affectedInvoiceId > 0) {
|
||||
$this->invoiceLedgerService->recalculateInvoice($affectedInvoiceId);
|
||||
}
|
||||
|
||||
$db->transComplete();
|
||||
|
||||
if ($db->transStatus() === false) {
|
||||
$db->transCommit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->transRollback();
|
||||
log_message('error', 'updatePayment failed: ' . $e->getMessage());
|
||||
return $this->response->setJSON(['error' => 'Failed to update payment.']);
|
||||
}
|
||||
|
||||
@@ -770,6 +841,13 @@ class RefundController extends BaseController
|
||||
return $this->response->setJSON(['error' => 'Refund not found.']);
|
||||
}
|
||||
|
||||
$this->db->transBegin();
|
||||
|
||||
try {
|
||||
if (!empty($refund['invoice_id'])) {
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $refund['invoice_id']]);
|
||||
}
|
||||
|
||||
$ok = $this->refundModel->update($refundId, [
|
||||
'status' => $status,
|
||||
'reason' => $reason,
|
||||
@@ -779,7 +857,61 @@ class RefundController extends BaseController
|
||||
'updated_by' => session()->get('user_id'),
|
||||
]);
|
||||
|
||||
if (!empty($refund['invoice_id'])) {
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $refund['invoice_id']);
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
} catch (\Throwable $e) {
|
||||
$this->db->transRollback();
|
||||
log_message('error', 'updateStatus failed: ' . $e->getMessage());
|
||||
$ok = false;
|
||||
}
|
||||
|
||||
return $this->response->setJSON($ok ? ['success' => 'Refund status updated successfully.']
|
||||
: ['error' => 'Failed to update refund status.']);
|
||||
}
|
||||
|
||||
public function serveRefundFile(int $refundId, string $mode = 'download')
|
||||
{
|
||||
$refund = $this->refundModel->find($refundId);
|
||||
if (!$refund || empty($refund['check_file'])) {
|
||||
throw PageNotFoundException::forPageNotFound('Refund file not found.');
|
||||
}
|
||||
|
||||
if (!$this->canViewRefund($refund)) {
|
||||
return $this->response->setStatusCode(403);
|
||||
}
|
||||
|
||||
$path = $this->financialAttachmentService->resolvePath('checks', (string) $refund['check_file']);
|
||||
if ($path === null) {
|
||||
throw PageNotFoundException::forPageNotFound('Refund file not found.');
|
||||
}
|
||||
|
||||
if ($mode === 'inline') {
|
||||
return $this->response
|
||||
->setHeader('Content-Type', $this->financialAttachmentService->detectMime($path))
|
||||
->setHeader('Content-Disposition', 'inline; filename="' . basename($path) . '"')
|
||||
->setBody(file_get_contents($path));
|
||||
}
|
||||
|
||||
return $this->response->download($path, null);
|
||||
}
|
||||
|
||||
private function canViewRefund(array $refund): bool
|
||||
{
|
||||
$roles = array_map('strtolower', (array) (session()->get('roles') ?? []));
|
||||
$activeRole = strtolower((string) (session()->get('role') ?? ''));
|
||||
if ($activeRole !== '' && !in_array($activeRole, $roles, true)) {
|
||||
$roles[] = $activeRole;
|
||||
}
|
||||
|
||||
foreach (['administrator', 'administrative staff', 'principal', 'teacher', 'teacher_assistant'] as $role) {
|
||||
if (in_array($role, $roles, true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return in_array('parent', $roles, true) && (int) ($refund['parent_id'] ?? 0) === (int) session()->get('user_id');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -601,8 +601,8 @@ class ReimbursementController extends BaseController
|
||||
]);
|
||||
}
|
||||
|
||||
public function updateBatchAssignment()
|
||||
{
|
||||
public function updateBatchAssignment()
|
||||
{
|
||||
if (strtolower($this->request->getMethod()) !== 'post') {
|
||||
return $this->response->setStatusCode(405)->setJSON([
|
||||
'success' => false,
|
||||
@@ -611,14 +611,18 @@ class ReimbursementController extends BaseController
|
||||
}
|
||||
|
||||
$expenseId = (int) $this->request->getPost('expense_id');
|
||||
|
||||
$batchIdRaw = $this->request->getPost('batch_id');
|
||||
$batchId = (int) $batchIdRaw;
|
||||
|
||||
$fallbackBatchNumber = $this->request->getPost('batch_number');
|
||||
if ($batchId <= 0 && $fallbackBatchNumber !== null && trim((string) $fallbackBatchNumber) !== '') {
|
||||
$batchId = (int) $fallbackBatchNumber;
|
||||
}
|
||||
|
||||
$adminIdRaw = $this->request->getPost('admin_id');
|
||||
$adminId = ($adminIdRaw === '' || $adminIdRaw === null) ? null : (int) $adminIdRaw;
|
||||
|
||||
$reimbursementId = (int) $this->request->getPost('reimbursement_id') ?: null;
|
||||
|
||||
if ($expenseId <= 0) {
|
||||
@@ -630,124 +634,186 @@ class ReimbursementController extends BaseController
|
||||
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
$newHashResponse = function (array $payload = []) {
|
||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||
|
||||
return $this->response
|
||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||
->setJSON(array_merge($payload, [
|
||||
'csrf_hash' => $newHash,
|
||||
]));
|
||||
};
|
||||
|
||||
$this->db->transBegin();
|
||||
|
||||
try {
|
||||
$activeItem = $this->batchItemModel
|
||||
->where('expense_id', $expenseId)
|
||||
->where('unassigned_at IS NULL', null, false)
|
||||
->first();
|
||||
|
||||
/**
|
||||
* If no batch is provided, remove the item from active batch processing.
|
||||
* This means "unassigned from batch", not "unassigned admin".
|
||||
*/
|
||||
if ($batchId <= 0) {
|
||||
if ($activeItem) {
|
||||
$this->batchItemModel->update((int) $activeItem['id'], ['unassigned_at' => $now]);
|
||||
$this->batchItemModel->update((int) $activeItem['id'], [
|
||||
'unassigned_at' => $now,
|
||||
]);
|
||||
|
||||
if (!$reimbursementId && !empty($activeItem['reimbursement_id'])) {
|
||||
$reimbursementId = (int) $activeItem['reimbursement_id'];
|
||||
}
|
||||
}
|
||||
|
||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||
return $this->response
|
||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||
->setJSON([
|
||||
if (!$this->db->transStatus()) {
|
||||
throw new \RuntimeException('Transaction failed while unassigning batch item.');
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
|
||||
return $newHashResponse([
|
||||
'success' => true,
|
||||
'batch_id' => 0,
|
||||
'admin_id' => null,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
'csrf_hash' => $newHash,
|
||||
]);
|
||||
}
|
||||
|
||||
$batch = $this->batchModel->find($batchId);
|
||||
if (!$batch || strtolower((string) ($batch['status'] ?? 'open')) !== 'open') {
|
||||
$this->db->transRollback();
|
||||
|
||||
return $this->response->setStatusCode(404)->setJSON([
|
||||
'success' => false,
|
||||
'error' => 'Batch not found or already closed.',
|
||||
]);
|
||||
}
|
||||
|
||||
$currentAdmin = $activeItem ? (int) ($activeItem['admin_id'] ?? 0) : null;
|
||||
if (!$reimbursementId) {
|
||||
if ($activeItem && !empty($activeItem['reimbursement_id'])) {
|
||||
$reimbursementId = (int) $activeItem['reimbursement_id'];
|
||||
} else {
|
||||
$reimbursementId = $this->lookupReimbursementId($expenseId);
|
||||
}
|
||||
}
|
||||
|
||||
$activeSameBatch = $activeItem && (int) ($activeItem['batch_id'] ?? 0) === $batchId;
|
||||
if ($activeSameBatch && ($currentAdmin === ($adminId ?? 0))) {
|
||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||
return $this->response
|
||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||
->setJSON([
|
||||
$currentAdmin = $activeItem ? (int) ($activeItem['admin_id'] ?? 0) : null;
|
||||
$requestedAdmin = $adminId ?? 0;
|
||||
|
||||
/**
|
||||
* If the item is already active in the same batch/admin slot, just return success.
|
||||
*/
|
||||
if ($activeSameBatch && $currentAdmin === $requestedAdmin) {
|
||||
if (!$this->db->transStatus()) {
|
||||
throw new \RuntimeException('Transaction failed while checking existing assignment.');
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
|
||||
return $newHashResponse([
|
||||
'success' => true,
|
||||
'batch_id' => $batchId,
|
||||
'admin_id' => $adminId,
|
||||
'reimbursement_id' => $activeItem['reimbursement_id'] ?? null,
|
||||
'csrf_hash' => $newHash,
|
||||
'reimbursement_id' => $activeItem['reimbursement_id'] ?? $reimbursementId,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* If same batch but different admin, update the existing active row.
|
||||
*
|
||||
* Important:
|
||||
* admin_id = null means active in the batch but not assigned to an admin.
|
||||
* unassigned_at != null means removed from active batch processing.
|
||||
*/
|
||||
if ($activeSameBatch) {
|
||||
if (!$reimbursementId) {
|
||||
$reimbursementId = $activeItem['reimbursement_id'] ? (int) $activeItem['reimbursement_id'] : $this->lookupReimbursementId($expenseId);
|
||||
}
|
||||
$updatePayload = [
|
||||
$this->batchItemModel->update((int) $activeItem['id'], [
|
||||
'admin_id' => $adminId,
|
||||
'assigned_at' => $now,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
'unassigned_at' => $adminId === null ? $now : null,
|
||||
];
|
||||
$this->batchItemModel->update((int) $activeItem['id'], $updatePayload);
|
||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||
return $this->response
|
||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||
->setJSON([
|
||||
'unassigned_at' => null,
|
||||
]);
|
||||
|
||||
if (!$this->db->transStatus()) {
|
||||
throw new \RuntimeException('Transaction failed while updating existing assignment.');
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
|
||||
return $newHashResponse([
|
||||
'success' => true,
|
||||
'batch_id' => $batchId,
|
||||
'admin_id' => $adminId,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
'csrf_hash' => $newHash,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* If the item is active in another batch, soft-unassign that row first.
|
||||
*/
|
||||
if ($activeItem) {
|
||||
$this->batchItemModel->update((int) $activeItem['id'], ['unassigned_at' => $now]);
|
||||
if (!$reimbursementId && !empty($activeItem['reimbursement_id'])) {
|
||||
$reimbursementId = (int) $activeItem['reimbursement_id'];
|
||||
}
|
||||
$this->batchItemModel->update((int) $activeItem['id'], [
|
||||
'unassigned_at' => $now,
|
||||
]);
|
||||
}
|
||||
|
||||
if (!$reimbursementId) {
|
||||
$reimbursementId = $this->lookupReimbursementId($expenseId);
|
||||
}
|
||||
/**
|
||||
* Critical fix:
|
||||
* Check whether this expense was previously assigned to this batch.
|
||||
* Because uq_batch_expense(batch_id, expense_id) blocks duplicate rows,
|
||||
* we must reactivate/update the old row instead of inserting again.
|
||||
*/
|
||||
$existingBatchItem = $this->batchItemModel
|
||||
->where('batch_id', $batchId)
|
||||
->where('expense_id', $expenseId)
|
||||
->first();
|
||||
|
||||
$insertData = [
|
||||
$assignmentData = [
|
||||
'batch_id' => $batchId,
|
||||
'expense_id' => $expenseId,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
'admin_id' => $adminId,
|
||||
'assigned_at' => $now,
|
||||
'unassigned_at' => null,
|
||||
'school_year' => $this->schoolYear,
|
||||
'semester' => $this->semester,
|
||||
];
|
||||
|
||||
try {
|
||||
$this->batchItemModel->insert($insertData);
|
||||
if ($existingBatchItem) {
|
||||
$this->batchItemModel->update((int) $existingBatchItem['id'], $assignmentData);
|
||||
} else {
|
||||
$this->batchItemModel->insert($assignmentData);
|
||||
}
|
||||
|
||||
if (!$this->db->transStatus()) {
|
||||
throw new \RuntimeException('Transaction failed while saving assignment.');
|
||||
}
|
||||
|
||||
$this->db->transCommit();
|
||||
|
||||
return $newHashResponse([
|
||||
'success' => true,
|
||||
'batch_id' => $batchId,
|
||||
'admin_id' => $adminId,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'Failed to assign expense #{expense} to batch #{batch}: {msg}', [
|
||||
$this->db->transRollback();
|
||||
|
||||
log_message('error', 'Failed to update batch assignment for expense #{expense}, batch #{batch}: {msg}', [
|
||||
'expense' => $expenseId,
|
||||
'batch' => $batchId,
|
||||
'msg' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return $this->response->setStatusCode(500)->setJSON([
|
||||
'success' => false,
|
||||
'error' => 'Unable to update batch assignment right now.',
|
||||
]);
|
||||
}
|
||||
|
||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||
|
||||
return $this->response
|
||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||
->setJSON([
|
||||
'success' => true,
|
||||
'batch_id' => $batchId,
|
||||
'admin_id' => $adminId,
|
||||
'reimbursement_id' => $reimbursementId,
|
||||
'csrf_hash' => $newHash,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function lockBatch()
|
||||
{
|
||||
|
||||
@@ -317,18 +317,27 @@ class ReportCardsController extends PrintablesBaseController
|
||||
$examCommentTypes = $isSecond
|
||||
? ['final']
|
||||
: ($isFirst ? ['midterm'] : ['midterm', 'final']);
|
||||
$commentTypes = array_merge($examCommentTypes, ['ptap', 'attendance', 'attendance_comment']);
|
||||
$wantedCommentTypes = array_merge($examCommentTypes, ['ptap', 'attendance']);
|
||||
$hasCommentReview = $this->db->fieldExists('comment_review', 'score_comments');
|
||||
$commentSelect = $hasCommentReview
|
||||
? 'student_id, score_type, comment, comment_review'
|
||||
: 'student_id, score_type, comment';
|
||||
$hasCommentSemester = $this->db->fieldExists('semester', 'score_comments');
|
||||
$hasCommentUpdatedAt = $this->db->fieldExists('updated_at', 'score_comments');
|
||||
$commentSelectParts = ['student_id', 'score_type', 'comment'];
|
||||
if ($hasCommentReview) {
|
||||
$commentSelectParts[] = 'comment_review';
|
||||
}
|
||||
if ($hasCommentSemester) {
|
||||
$commentSelectParts[] = 'semester';
|
||||
}
|
||||
|
||||
// Do NOT filter comments by score_type or semester here.
|
||||
// A single bad row like "Attendance Comment", "attendance-comment", or a blank semester
|
||||
// should not make one student look incomplete while the PDF can still print the comment.
|
||||
$commentBuilder = $this->scoreCommentModel
|
||||
->select($commentSelect)
|
||||
->select(implode(', ', $commentSelectParts))
|
||||
->whereIn('student_id', $studentIds)
|
||||
->where('school_year', $year)
|
||||
->whereIn('score_type', $commentTypes);
|
||||
if ($sem !== '') {
|
||||
$this->applySemesterFilter($commentBuilder, $sem, 'semester');
|
||||
->where('school_year', $year);
|
||||
if ($hasCommentUpdatedAt) {
|
||||
$commentBuilder->orderBy('updated_at', 'DESC');
|
||||
}
|
||||
$commentRows = [];
|
||||
try {
|
||||
@@ -336,25 +345,92 @@ class ReportCardsController extends PrintablesBaseController
|
||||
} catch (\Throwable $e) {
|
||||
}
|
||||
|
||||
$cleanComment = static function ($value): string {
|
||||
$text = (string)($value ?? '');
|
||||
$text = str_replace("\xc2\xa0", ' ', $text); // normalize non-breaking spaces
|
||||
return trim($text);
|
||||
};
|
||||
|
||||
$normalizeCommentType = static function ($value) use ($cleanComment): string {
|
||||
$type = strtolower($cleanComment($value));
|
||||
$type = preg_replace('/[^a-z0-9]+/', '_', $type);
|
||||
$type = trim((string)$type, '_');
|
||||
|
||||
$map = [
|
||||
'attendance_comment' => 'attendance',
|
||||
'attendance_comments' => 'attendance',
|
||||
'attendance' => 'attendance',
|
||||
'attendence' => 'attendance',
|
||||
'attendence_comment' => 'attendance',
|
||||
'attendence_comments' => 'attendance',
|
||||
'ptap_comment' => 'ptap',
|
||||
'ptap_comments' => 'ptap',
|
||||
'ptap' => 'ptap',
|
||||
'midterm_comment' => 'midterm',
|
||||
'midterm_comments' => 'midterm',
|
||||
'midterm' => 'midterm',
|
||||
'final_comment' => 'final',
|
||||
'final_comments' => 'final',
|
||||
'final' => 'final',
|
||||
];
|
||||
|
||||
return $map[$type] ?? $type;
|
||||
};
|
||||
|
||||
$normalizeSemester = static function ($value) use ($cleanComment): string {
|
||||
$v = strtolower($cleanComment($value));
|
||||
$v = preg_replace('/[^a-z0-9]+/', ' ', $v);
|
||||
$v = trim((string)$v);
|
||||
if (in_array($v, ['fall', 'first', 'first semester', 'semester 1', '1'], true)) {
|
||||
return 'fall';
|
||||
}
|
||||
if (in_array($v, ['spring', 'second', 'second semester', 'semester 2', '2'], true)) {
|
||||
return 'spring';
|
||||
}
|
||||
return $v;
|
||||
};
|
||||
$wantedSemester = $normalizeSemester($sem);
|
||||
|
||||
$commentsByStudent = [];
|
||||
$commentPriorityByStudent = [];
|
||||
foreach ($commentRows as $row) {
|
||||
$sid = (int)($row['student_id'] ?? 0);
|
||||
if ($sid <= 0) {
|
||||
continue;
|
||||
}
|
||||
$typeRaw = strtolower(trim((string)($row['score_type'] ?? '')));
|
||||
if ($typeRaw === '') {
|
||||
|
||||
$typeRaw = $normalizeCommentType($row['score_type'] ?? '');
|
||||
if ($typeRaw === '' || !in_array($typeRaw, $wantedCommentTypes, true)) {
|
||||
continue;
|
||||
}
|
||||
if ($typeRaw === 'attendance_comment') {
|
||||
$typeRaw = 'attendance';
|
||||
|
||||
$rawVal = $cleanComment($row['comment'] ?? '');
|
||||
if ($typeRaw === 'attendance') {
|
||||
// Attendance comments are stored in score_comments.comment.
|
||||
// Do not use comment_review here, because it can be blank while the PDF comment exists.
|
||||
$commentVal = $rawVal;
|
||||
} else {
|
||||
// For non-attendance comments, prefer reviewed text but fall back to the saved comment.
|
||||
$reviewVal = $hasCommentReview ? $cleanComment($row['comment_review'] ?? '') : '';
|
||||
$commentVal = $reviewVal !== '' ? $reviewVal : $rawVal;
|
||||
}
|
||||
$reviewVal = $hasCommentReview ? trim((string)($row['comment_review'] ?? '')) : '';
|
||||
$commentVal = $hasCommentReview ? $reviewVal : trim((string)($row['comment'] ?? ''));
|
||||
if ($commentVal === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rowSemester = $hasCommentSemester ? $normalizeSemester($row['semester'] ?? '') : '';
|
||||
$priority = 1;
|
||||
if ($wantedSemester !== '' && $rowSemester === $wantedSemester) {
|
||||
$priority = 3;
|
||||
} elseif ($rowSemester === '') {
|
||||
$priority = 2;
|
||||
}
|
||||
|
||||
$existingPriority = $commentPriorityByStudent[$sid][$typeRaw] ?? 0;
|
||||
if (!isset($commentsByStudent[$sid][$typeRaw]) || $priority >= $existingPriority) {
|
||||
$commentsByStudent[$sid][$typeRaw] = $commentVal;
|
||||
$commentPriorityByStudent[$sid][$typeRaw] = $priority;
|
||||
}
|
||||
}
|
||||
|
||||
$isNumeric = static fn($v) => $v !== null && $v !== '' && is_numeric($v);
|
||||
@@ -467,6 +543,20 @@ class ReportCardsController extends PrintablesBaseController
|
||||
if (trim((string)($commentSet['ptap'] ?? '')) === '') {
|
||||
$missing[] = 'PTAP comment';
|
||||
}
|
||||
|
||||
// Keep completeness consistent with the PDF report generation:
|
||||
// the report can auto-generate an attendance comment from attendance_score.
|
||||
if (trim((string)($commentSet['attendance'] ?? '')) === '' && $isNumeric($attendanceScore)) {
|
||||
$autoAttendance = attendance_comment_from_score(
|
||||
(float)$attendanceScore,
|
||||
trim((string)($student['firstname'] ?? ''))
|
||||
);
|
||||
if ($autoAttendance !== null && trim((string)$autoAttendance) !== '') {
|
||||
$commentSet['attendance'] = $autoAttendance;
|
||||
$warnings[] = 'Attendance comment computed from attendance score';
|
||||
}
|
||||
}
|
||||
|
||||
if (trim((string)($commentSet['attendance'] ?? '')) === '') {
|
||||
$missing[] = 'Attendance comment';
|
||||
}
|
||||
@@ -1014,9 +1104,9 @@ $drawRankCell = static function (
|
||||
$pdf->Rect($x, $y, $w, $h);
|
||||
$pdf->SetXY($x + $pad, $y + 3);
|
||||
$pdf->SetFont('Helvetica', 'B', 11);
|
||||
$pdf->Write(5, ' Ranking: ');
|
||||
$pdf->Write(5, ' Class Rank: ');
|
||||
|
||||
$labelWidth = $pdf->GetStringWidth(' Ranking: ');
|
||||
$labelWidth = $pdf->GetStringWidth(' Class Rank: ');
|
||||
$pdf->SetFont('Helvetica', '', 12);
|
||||
$pdf->SetXY($x + 2 + $labelWidth, $y + 3);
|
||||
$pdf->Write(5, $rankValue);
|
||||
@@ -1531,10 +1621,16 @@ $scoresEndY = $pdf->GetY();
|
||||
if ($typeRaw === 'attendance_comment') {
|
||||
$typeRaw = 'attendance';
|
||||
}
|
||||
$rawComment = trim((string)($row['comment'] ?? ''));
|
||||
if ($typeRaw === 'attendance') {
|
||||
// Attendance comments must come from score_comments.comment.
|
||||
$commentVal = $rawComment;
|
||||
} else {
|
||||
$reviewVal = trim((string)($row['comment_review'] ?? ''));
|
||||
$commentVal = $this->db->fieldExists('comment_review', 'score_comments')
|
||||
$commentVal = $this->db->fieldExists('comment_review', 'score_comments') && $reviewVal !== ''
|
||||
? $reviewVal
|
||||
: trim((string)($row['comment'] ?? ''));
|
||||
: $rawComment;
|
||||
}
|
||||
if ($commentVal === '') {
|
||||
continue;
|
||||
}
|
||||
@@ -1732,14 +1828,14 @@ $scoresEndY = $pdf->GetY();
|
||||
];
|
||||
}
|
||||
|
||||
private function calculateTermRanking(
|
||||
private function calculateTermRanking(
|
||||
int $studentId,
|
||||
int $sectionCode,
|
||||
?int $sectionId,
|
||||
string $schoolYear,
|
||||
?string $semester,
|
||||
?float $studentScore
|
||||
): ?array {
|
||||
): ?array {
|
||||
if ($studentId <= 0 || $schoolYear === '' || $studentScore === null) {
|
||||
return null;
|
||||
}
|
||||
@@ -1753,15 +1849,42 @@ $scoresEndY = $pdf->GetY();
|
||||
return null;
|
||||
}
|
||||
|
||||
/*
|
||||
* Rank must be limited to the actual selected class roster.
|
||||
* Do NOT rank by every semester_scores row that happens to share class_section_id,
|
||||
* because old/mismatched score rows can inflate the denominator (for example 18 students
|
||||
* in 3-A showing as "out of 32"). The roster is the source of truth for class size.
|
||||
*/
|
||||
$rosterRows = $this->fetchStudentsByClass($sectionCode, $schoolYear);
|
||||
if (empty($rosterRows) && $sectionId && $sectionId !== $sectionCode) {
|
||||
$rosterRows = $this->fetchStudentsByClass($sectionId, $schoolYear);
|
||||
}
|
||||
|
||||
$rosterByStudent = [];
|
||||
foreach ($rosterRows as $row) {
|
||||
$sid = (int)($row['id'] ?? 0);
|
||||
if ($sid <= 0) {
|
||||
continue;
|
||||
}
|
||||
$rosterByStudent[$sid] = [
|
||||
'firstname' => trim((string)($row['firstname'] ?? '')),
|
||||
'lastname' => trim((string)($row['lastname'] ?? '')),
|
||||
];
|
||||
}
|
||||
|
||||
if (empty($rosterByStudent) || !isset($rosterByStudent[$studentId])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$rosterStudentIds = array_keys($rosterByStudent);
|
||||
|
||||
$semesterForRank = trim((string)$semester);
|
||||
$rankByFinalScore = $this->normalizeSemester($semesterForRank) === 'spring';
|
||||
|
||||
$builder = $this->db->table('semester_scores ss')
|
||||
->select('ss.student_id, ss.semester, ss.semester_score, ss.updated_at, ss.id, s.firstname, s.lastname')
|
||||
->join('students s', 's.id = ss.student_id', 'inner')
|
||||
->where('s.is_active', 1)
|
||||
->select('ss.student_id, ss.semester, ss.semester_score, ss.updated_at, ss.id')
|
||||
->where('ss.school_year', $schoolYear)
|
||||
->whereIn('ss.class_section_id', $sectionIds)
|
||||
->whereIn('ss.student_id', $rosterStudentIds)
|
||||
->orderBy('ss.updated_at', 'DESC')
|
||||
->orderBy('ss.id', 'DESC');
|
||||
|
||||
@@ -1770,41 +1893,49 @@ $scoresEndY = $pdf->GetY();
|
||||
}
|
||||
|
||||
$rows = $builder->get()->getResultArray();
|
||||
|
||||
if (empty($rows)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$scoresByStudent = [];
|
||||
$studentIds = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$sid = (int)($row['student_id'] ?? 0);
|
||||
if ($sid <= 0 || isset($scoresByStudent[$sid])) {
|
||||
|
||||
if ($sid <= 0 || !isset($rosterByStudent[$sid]) || isset($scoresByStudent[$sid])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$scoreVal = $row['semester_score'] ?? null;
|
||||
|
||||
if (!is_numeric($scoreVal)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rawScore = (float)$scoreVal;
|
||||
|
||||
$scoresByStudent[$sid] = [
|
||||
'student_id' => $sid,
|
||||
'score' => round((float)$scoreVal, 4),
|
||||
'firstname' => trim((string)($row['firstname'] ?? '')),
|
||||
'lastname' => trim((string)($row['lastname'] ?? '')),
|
||||
'score' => $rawScore,
|
||||
'rank_score' => round($rawScore, 1),
|
||||
'firstname' => $rosterByStudent[$sid]['firstname'],
|
||||
'lastname' => $rosterByStudent[$sid]['lastname'],
|
||||
];
|
||||
$studentIds[] = $sid;
|
||||
}
|
||||
|
||||
if (empty($scoresByStudent) || !isset($scoresByStudent[$studentId])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// For Spring, rank by final year average:
|
||||
// (first semester score + second semester score) / 2.
|
||||
if ($rankByFinalScore) {
|
||||
$studentIds = array_keys($scoresByStudent);
|
||||
|
||||
$firstRowsBuilder = $this->db->table('semester_scores ss')
|
||||
->select('ss.student_id, ss.semester_score, ss.updated_at, ss.id')
|
||||
->select('ss.student_id, ss.semester, ss.semester_score, ss.updated_at, ss.id')
|
||||
->where('ss.school_year', $schoolYear)
|
||||
->whereIn('ss.class_section_id', $sectionIds)
|
||||
->whereIn('ss.student_id', $studentIds)
|
||||
->orderBy('ss.updated_at', 'DESC')
|
||||
->orderBy('ss.id', 'DESC');
|
||||
@@ -1814,14 +1945,18 @@ $scoresEndY = $pdf->GetY();
|
||||
}
|
||||
|
||||
$firstRows = $firstRowsBuilder->get()->getResultArray();
|
||||
|
||||
$firstScoresByStudent = [];
|
||||
|
||||
foreach ($firstRows as $row) {
|
||||
$sid = (int)($row['student_id'] ?? 0);
|
||||
if ($sid <= 0 || isset($firstScoresByStudent[$sid])) {
|
||||
|
||||
if ($sid <= 0 || !isset($rosterByStudent[$sid]) || isset($firstScoresByStudent[$sid])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$scoreVal = $row['semester_score'] ?? null;
|
||||
|
||||
if (!is_numeric($scoreVal)) {
|
||||
continue;
|
||||
}
|
||||
@@ -1835,30 +1970,48 @@ $scoresEndY = $pdf->GetY();
|
||||
continue;
|
||||
}
|
||||
|
||||
$rankRow['score'] = round(((float)$firstScoresByStudent[$sid] + (float)$rankRow['score']) / 2, 4);
|
||||
$avg = ((float)$firstScoresByStudent[$sid] + (float)$rankRow['score']) / 2;
|
||||
|
||||
$rankRow['score'] = $avg;
|
||||
$rankRow['rank_score'] = round($avg, 1);
|
||||
}
|
||||
|
||||
unset($rankRow);
|
||||
|
||||
if (empty($scoresByStudent) || !isset($scoresByStudent[$studentId])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$scoresByStudent[$studentId]['score'] = round((float)$studentScore, 4);
|
||||
// Force the selected student to use the exact score already computed for the report.
|
||||
// Then rank using the displayed precision: one decimal.
|
||||
$scoresByStudent[$studentId]['score'] = (float)$studentScore;
|
||||
$scoresByStudent[$studentId]['rank_score'] = round((float)$studentScore, 1);
|
||||
} else {
|
||||
// Fall: also force selected student to match the report-card computed score.
|
||||
$scoresByStudent[$studentId]['score'] = (float)$studentScore;
|
||||
$scoresByStudent[$studentId]['rank_score'] = round((float)$studentScore, 1);
|
||||
}
|
||||
|
||||
$rankable = array_values($scoresByStudent);
|
||||
|
||||
usort($rankable, static function (array $a, array $b): int {
|
||||
$scoreCmp = $b['score'] <=> $a['score'];
|
||||
// Highest displayed/rank score first.
|
||||
$scoreCmp = $b['rank_score'] <=> $a['rank_score'];
|
||||
|
||||
if ($scoreCmp !== 0) {
|
||||
return $scoreCmp;
|
||||
}
|
||||
|
||||
// Tie-breakers only control display order.
|
||||
// They do NOT change rank.
|
||||
$lastCmp = strcasecmp($a['lastname'], $b['lastname']);
|
||||
|
||||
if ($lastCmp !== 0) {
|
||||
return $lastCmp;
|
||||
}
|
||||
|
||||
$firstCmp = strcasecmp($a['firstname'], $b['firstname']);
|
||||
|
||||
if ($firstCmp !== 0) {
|
||||
return $firstCmp;
|
||||
}
|
||||
@@ -1868,24 +2021,32 @@ $scoresEndY = $pdf->GetY();
|
||||
|
||||
$position = null;
|
||||
$previousScore = null;
|
||||
|
||||
foreach ($rankable as $index => $row) {
|
||||
if ($previousScore === null || abs($row['score'] - $previousScore) > 0.0001) {
|
||||
$currentScore = (float)$row['rank_score'];
|
||||
|
||||
// Competition ranking:
|
||||
// 1, 1, 3, 4...
|
||||
// Same score = same rank.
|
||||
if ($previousScore === null || abs($currentScore - $previousScore) > 0.0001) {
|
||||
$position = $index + 1;
|
||||
$previousScore = $row['score'];
|
||||
$previousScore = $currentScore;
|
||||
}
|
||||
|
||||
if ((int)$row['student_id'] === $studentId) {
|
||||
$total = count($rankable);
|
||||
|
||||
return [
|
||||
'position' => $position,
|
||||
'total' => $total,
|
||||
'display' => $this->formatOrdinal($position) . ' of ' . $total,
|
||||
'score' => $currentScore,
|
||||
'display' => $this->formatOrdinal($position) . ' out of ' . $total,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function formatOrdinal(?int $value): string
|
||||
{
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\View;
|
||||
|
||||
/**
|
||||
* Compatibility wrapper for older references.
|
||||
*
|
||||
* School-year lifecycle behavior lives in App\Controllers\Administrator,
|
||||
* where status changes are exposed only as dedicated actions.
|
||||
*/
|
||||
class SchoolYearController extends \App\Controllers\Administrator\SchoolYearController
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\View;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Libraries\Tuition\TuitionForecastService;
|
||||
|
||||
class TuitionForecastController extends BaseController
|
||||
{
|
||||
protected TuitionForecastService $forecastService;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->forecastService = new TuitionForecastService();
|
||||
helper(['url']);
|
||||
}
|
||||
|
||||
public function index()
|
||||
{
|
||||
$schoolYear = trim((string) ($this->request->getGet('school_year') ?? ''));
|
||||
$semester = trim((string) ($this->request->getGet('semester') ?? ''));
|
||||
$mode = (string) ($this->request->getGet('calculator_mode') ?? 'compare');
|
||||
$filters = $this->buildOptionsFromRequest('get');
|
||||
$result = $this->forecastService->calculate($schoolYear, $semester, $mode, $filters);
|
||||
|
||||
return view('administrator/tuition_forecast', [
|
||||
'title' => 'Tuition Collection Forecast',
|
||||
'schoolYears' => $this->forecastService->getAvailableSchoolYears(),
|
||||
'semesters' => $this->forecastService->getAvailableSemesters(),
|
||||
'filters' => [
|
||||
'school_year' => $result['school_year'],
|
||||
'semester' => $result['semester'],
|
||||
'calculator_mode' => $result['calculator_mode'],
|
||||
] + $result['options'],
|
||||
'result' => $result,
|
||||
]);
|
||||
}
|
||||
|
||||
public function calculate()
|
||||
{
|
||||
$schoolYear = trim((string) ($this->request->getPost('school_year') ?? ''));
|
||||
$semester = trim((string) ($this->request->getPost('semester') ?? ''));
|
||||
$mode = (string) ($this->request->getPost('calculator_mode') ?? 'compare');
|
||||
|
||||
return $this->response->setJSON(
|
||||
$this->forecastService->calculate($schoolYear, $semester, $mode, $this->buildOptionsFromRequest('post'))
|
||||
);
|
||||
}
|
||||
|
||||
public function exportCsv()
|
||||
{
|
||||
$schoolYear = trim((string) ($this->request->getGet('school_year') ?? ''));
|
||||
$semester = trim((string) ($this->request->getGet('semester') ?? ''));
|
||||
$mode = (string) ($this->request->getGet('calculator_mode') ?? 'compare');
|
||||
$result = $this->forecastService->calculate($schoolYear, $semester, $mode, $this->buildOptionsFromRequest('get'));
|
||||
|
||||
$filename = sprintf(
|
||||
'tuition_forecast_%s_%s_%s.csv',
|
||||
preg_replace('/[^A-Za-z0-9_-]+/', '-', $result['school_year']) ?: 'school-year',
|
||||
preg_replace('/[^A-Za-z0-9_-]+/', '-', $result['semester']) ?: 'all-year',
|
||||
$result['calculator_mode']
|
||||
);
|
||||
|
||||
$handle = fopen('php://temp', 'w+');
|
||||
if ($handle === false) {
|
||||
throw new \RuntimeException('Unable to create CSV export.');
|
||||
}
|
||||
|
||||
fputcsv($handle, ['School Year', $result['school_year']]);
|
||||
fputcsv($handle, ['Semester', $result['semester'] !== '' ? $result['semester'] : 'All Year']);
|
||||
fputcsv($handle, ['Calculator Mode', $result['calculator_mode']]);
|
||||
fputcsv($handle, []);
|
||||
fputcsv($handle, ['Summary']);
|
||||
fputcsv($handle, ['Families', 'Students', 'Billable Students', 'Grade Unit Price', 'Youth Unit Price', 'Old Projected Income', 'New Projected Income', 'Difference']);
|
||||
fputcsv($handle, [
|
||||
$result['summary']['family_count'],
|
||||
$result['summary']['student_count'],
|
||||
$result['summary']['billable_student_count'],
|
||||
$result['summary']['unit_price'],
|
||||
$result['summary']['youth_unit_price'],
|
||||
$result['summary']['old_projected_income'] ?? $result['summary']['old_projected_tuition'],
|
||||
$result['summary']['new_projected_income'] ?? $result['summary']['new_projected_tuition'],
|
||||
$result['summary']['difference'],
|
||||
]);
|
||||
fputcsv($handle, []);
|
||||
fputcsv($handle, ['Families']);
|
||||
fputcsv($handle, ['Parent/Family', 'Student Count', 'Billable Student Count', 'Old Tuition Total', 'New Tuition Total', 'Difference', 'Warnings']);
|
||||
|
||||
foreach ($result['families'] as $family) {
|
||||
fputcsv($handle, [
|
||||
$family['parent_name'] ?? '',
|
||||
$family['student_count'] ?? 0,
|
||||
$family['billable_student_count'] ?? 0,
|
||||
$family['old_total'] ?? '0.00',
|
||||
$family['new_total'] ?? '0.00',
|
||||
$family['difference'] ?? '0.00',
|
||||
implode(' | ', $family['warnings'] ?? []),
|
||||
]);
|
||||
|
||||
fputcsv($handle, ['Student Name', 'Grade', 'Billable', 'Excluded Reason', 'Old Rule', 'Old Amount', 'New Rule', 'New Amount']);
|
||||
foreach ($family['student_details'] as $detail) {
|
||||
fputcsv($handle, [
|
||||
$detail['student_name'] ?? '',
|
||||
$detail['grade_level'] ?? '',
|
||||
!empty($detail['billable']) ? 'Yes' : 'No',
|
||||
$detail['excluded_reason'] ?? '',
|
||||
$detail['old_rule'] ?? '',
|
||||
$detail['old_amount'] ?? '0.00',
|
||||
$detail['new_rule'] ?? '',
|
||||
$detail['new_amount'] ?? '0.00',
|
||||
]);
|
||||
}
|
||||
fputcsv($handle, []);
|
||||
}
|
||||
|
||||
rewind($handle);
|
||||
$csv = stream_get_contents($handle) ?: '';
|
||||
fclose($handle);
|
||||
|
||||
return $this->response
|
||||
->setHeader('Content-Type', 'text/csv; charset=UTF-8')
|
||||
->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
|
||||
->setBody($csv);
|
||||
}
|
||||
|
||||
protected function buildOptionsFromRequest(string $method): array
|
||||
{
|
||||
$source = $method === 'post' ? 'getPost' : 'getGet';
|
||||
|
||||
return [
|
||||
'include_withdrawn_mode' => (string) ($this->request->{$source}('include_withdrawn_mode') ?? 'refund_deadline'),
|
||||
'include_payment_pending' => $this->request->{$source}('include_payment_pending') ?? '0',
|
||||
'include_event_only' => $this->request->{$source}('include_event_only') ?? '0',
|
||||
'include_paid_invoices' => $this->request->{$source}('include_paid_invoices') ?? '0',
|
||||
'unit_price' => $this->request->{$source}('unit_price') ?? '',
|
||||
'youth_unit_price' => $this->request->{$source}('youth_unit_price') ?? '',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -106,14 +106,12 @@ class WhatsappController extends BaseController
|
||||
$existing = $this->linkModel->where([
|
||||
'class_section_id' => $sectionId,
|
||||
'school_year' => $this->schoolYear,
|
||||
'semester' => $this->semester,
|
||||
])->first();
|
||||
|
||||
$payload = [
|
||||
'class_section_id' => $sectionId,
|
||||
'class_section_name' => $sectionName,
|
||||
'school_year' => $this->schoolYear,
|
||||
'semester' => $this->semester,
|
||||
'invite_link' => trim($inviteLink),
|
||||
'active' => $active,
|
||||
];
|
||||
@@ -434,8 +432,6 @@ class WhatsappController extends BaseController
|
||||
sp.secondparent_lastname AS sp_lastname,
|
||||
sp.secondparent_email AS sp_email,
|
||||
sp.secondparent_phone AS sp_phone,
|
||||
sp.school_year AS sp_school_year,
|
||||
sp.semester AS sp_semester,
|
||||
|
||||
u.id AS u_id,
|
||||
u.firstname AS u_firstname,
|
||||
@@ -448,14 +444,6 @@ class WhatsappController extends BaseController
|
||||
|
||||
$b->join('users u', 'u.id = sp.firstparent_id', 'left');
|
||||
|
||||
// Scope by term using parents table (authoritative for the pairing)
|
||||
if ($schoolYear !== '') {
|
||||
$b->where('sp.school_year', $schoolYear);
|
||||
}
|
||||
if ($semester !== '') {
|
||||
$b->where('sp.semester', $semester);
|
||||
}
|
||||
|
||||
$rows = $b->get()->getResultArray();
|
||||
|
||||
// Flatten into a single contacts list (primary + second parent as separate rows)
|
||||
@@ -606,11 +594,10 @@ class WhatsappController extends BaseController
|
||||
$pb->join('students s', 's.id = sc.student_id', 'inner'); // adjust if your table is named `student` (singular)
|
||||
$pb->join('users u', 'u.id = s.parent_id', 'inner'); // primary parent lives on students.parent_id
|
||||
|
||||
// Second parent row for the same term (allow NULL/'' semester if you sometimes omit it)
|
||||
// Second parent row for the primary parent.
|
||||
$pb->join(
|
||||
'parents sp',
|
||||
"sp.firstparent_id = u.id
|
||||
AND sp.school_year = sc.school_year",
|
||||
'sp.firstparent_id = u.id',
|
||||
'left'
|
||||
);
|
||||
|
||||
@@ -1202,7 +1189,7 @@ class WhatsappController extends BaseController
|
||||
|
||||
/**
|
||||
* Class mode:
|
||||
* - Given classSectionId, find students (student_class) for the term
|
||||
* - Given classSectionId, find students (student_class) for the year
|
||||
* - Map to primaries (users) and second-parents (parents)
|
||||
* - Return one bundle **per primary parent** (so each parent gets their own email)
|
||||
*/
|
||||
@@ -1215,7 +1202,6 @@ class WhatsappController extends BaseController
|
||||
$stuRows = $this->db->table('student_class')
|
||||
->select('student_id')
|
||||
->where('school_year', $this->schoolYear)
|
||||
->where('semester', $this->semester)
|
||||
->where('class_section_id', $classSectionId)
|
||||
->get()->getResultArray();
|
||||
if (empty($stuRows)) return [];
|
||||
@@ -1302,7 +1288,7 @@ class WhatsappController extends BaseController
|
||||
|
||||
/**
|
||||
* All mode:
|
||||
* - Iterate all distinct class_section_id in student_class (for the term)
|
||||
* - Iterate all distinct class_section_id in student_class (for the year)
|
||||
* - Reuse class bundles per section and flatten
|
||||
*/
|
||||
private function bundlesForAllParentsAllClasses(array $linkBySection): array
|
||||
@@ -1310,7 +1296,6 @@ class WhatsappController extends BaseController
|
||||
$secRows = $this->db->table('student_class')
|
||||
->select('DISTINCT class_section_id', false)
|
||||
->where('school_year', $this->schoolYear)
|
||||
->where('semester', $this->semester)
|
||||
->orderBy('class_section_id', 'ASC')
|
||||
->get()->getResultArray();
|
||||
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class FinancialSystemLedgerCleanup extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
$this->addInstallmentSequenceColumn();
|
||||
$this->backfillInstallmentSequence();
|
||||
$this->ensurePaymentDateHasTime();
|
||||
$this->ensureIndexes();
|
||||
$this->repairPaymentInvoiceTerms();
|
||||
$this->normalizePaymentStatuses();
|
||||
$this->ensureConfigurationDefaults();
|
||||
$this->archivePaypalTables();
|
||||
$this->refreshFinancialNavItems();
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
$this->restorePaypalTables();
|
||||
|
||||
if ($this->db->tableExists('payments') && $this->db->fieldExists('installment_seq', 'payments')) {
|
||||
$this->forge->dropColumn('payments', 'installment_seq');
|
||||
}
|
||||
|
||||
$this->dropIndexIfExists('payments', 'idx_payments_invoice_id');
|
||||
$this->dropIndexIfExists('payments', 'idx_payments_parent_year');
|
||||
$this->dropIndexIfExists('payments', 'idx_payments_parent_year_semester');
|
||||
$this->dropIndexIfExists('payments', 'uniq_payments_transaction_id');
|
||||
$this->dropIndexIfExists('invoices', 'idx_invoices_parent_year_semester');
|
||||
$this->dropIndexIfExists('discount_usages', 'idx_discount_usages_invoice_id');
|
||||
$this->dropIndexIfExists('discount_usages', 'idx_discount_usages_parent_year_semester');
|
||||
$this->dropIndexIfExists('refunds', 'idx_refunds_invoice_id');
|
||||
$this->dropIndexIfExists('refunds', 'idx_refunds_parent_year_semester_status');
|
||||
$this->dropIndexIfExists('additional_charges', 'idx_additional_charges_invoice_id');
|
||||
$this->dropIndexIfExists('additional_charges', 'idx_additional_charges_parent_year_semester_status');
|
||||
$this->dropIndexIfExists('invoice_event', 'idx_invoice_event_invoice_id');
|
||||
|
||||
if ($this->db->tableExists('nav_items')) {
|
||||
$forecastRow = $this->db->table('nav_items')
|
||||
->select('id')
|
||||
->where('url', 'administrator/tuition-forecast')
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if ($forecastRow && $this->db->tableExists('role_nav_items')) {
|
||||
$this->db->table('role_nav_items')
|
||||
->where('nav_item_id', (int) $forecastRow['id'])
|
||||
->delete();
|
||||
}
|
||||
|
||||
$this->db->table('nav_items')
|
||||
->where('url', 'administrator/tuition-forecast')
|
||||
->delete();
|
||||
}
|
||||
}
|
||||
|
||||
protected function addInstallmentSequenceColumn(): void
|
||||
{
|
||||
if ($this->db->tableExists('payments') && !$this->db->fieldExists('installment_seq', 'payments')) {
|
||||
$this->forge->addColumn('payments', [
|
||||
'installment_seq' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'null' => true,
|
||||
'after' => 'number_of_installments',
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
protected function backfillInstallmentSequence(): void
|
||||
{
|
||||
if (!$this->db->tableExists('payments') || !$this->db->fieldExists('installment_seq', 'payments')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db->query(
|
||||
'UPDATE `payments`
|
||||
SET `installment_seq` = `number_of_installments`
|
||||
WHERE `installment_seq` IS NULL'
|
||||
);
|
||||
}
|
||||
|
||||
protected function ensurePaymentDateHasTime(): void
|
||||
{
|
||||
if (!$this->db->tableExists('payments') || !$this->db->fieldExists('payment_date', 'payments')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db->query('ALTER TABLE `payments` MODIFY `payment_date` DATETIME NOT NULL');
|
||||
}
|
||||
|
||||
protected function ensureIndexes(): void
|
||||
{
|
||||
$this->addIndexIfMissing('payments', 'idx_payments_invoice_id', ['invoice_id']);
|
||||
$this->dropIndexIfExists('payments', 'idx_payments_parent_year_semester');
|
||||
$this->addIndexIfMissing('payments', 'idx_payments_parent_year', ['parent_id', 'school_year']);
|
||||
$this->addIndexIfMissing('invoices', 'idx_invoices_parent_year_semester', ['parent_id', 'school_year', 'semester']);
|
||||
$this->addIndexIfMissing('discount_usages', 'idx_discount_usages_invoice_id', ['invoice_id']);
|
||||
$this->addIndexIfMissing('discount_usages', 'idx_discount_usages_parent_year_semester', ['parent_id', 'school_year', 'semester']);
|
||||
$this->addIndexIfMissing('refunds', 'idx_refunds_invoice_id', ['invoice_id']);
|
||||
$this->addIndexIfMissing('refunds', 'idx_refunds_parent_year_semester_status', ['parent_id', 'school_year', 'semester', 'status']);
|
||||
$this->addIndexIfMissing('additional_charges', 'idx_additional_charges_invoice_id', ['invoice_id']);
|
||||
$this->addIndexIfMissing('additional_charges', 'idx_additional_charges_parent_year_semester_status', ['parent_id', 'school_year', 'semester', 'status']);
|
||||
$this->addIndexIfMissing('invoice_event', 'idx_invoice_event_invoice_id', ['invoice_id']);
|
||||
|
||||
if ($this->db->tableExists('payments') && $this->db->fieldExists('transaction_id', 'payments') && !$this->hasDuplicateTransactionIds()) {
|
||||
$this->addIndexIfMissing('payments', 'uniq_payments_transaction_id', ['transaction_id'], true);
|
||||
}
|
||||
}
|
||||
|
||||
protected function repairPaymentInvoiceTerms(): void
|
||||
{
|
||||
if (!$this->db->tableExists('payments') || !$this->db->tableExists('invoices')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db->query(
|
||||
'UPDATE `payments` p
|
||||
JOIN `invoices` i ON i.`id` = p.`invoice_id`
|
||||
SET p.`school_year` = i.`school_year`
|
||||
WHERE COALESCE(p.`school_year`, \'\') <> COALESCE(i.`school_year`, \'\')'
|
||||
);
|
||||
}
|
||||
|
||||
protected function normalizePaymentStatuses(): void
|
||||
{
|
||||
if (!$this->db->tableExists('payments') || !$this->db->fieldExists('status', 'payments')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db->query(
|
||||
"UPDATE `payments`
|
||||
SET `status` = 'recorded'
|
||||
WHERE LOWER(TRIM(`status`)) IN ('paid', 'partially paid', 'payment recorded', 'full', 'completed')"
|
||||
);
|
||||
}
|
||||
|
||||
protected function ensureConfigurationDefaults(): void
|
||||
{
|
||||
if (!$this->db->tableExists('configuration')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$defaults = [
|
||||
'tuition_calculator_version' => 'old',
|
||||
'youth_fee' => '200.00',
|
||||
'new_tuition_full_amount' => '370.00',
|
||||
'new_tuition_youth_amount' => '200.00',
|
||||
'new_tuition_second_student_discount' => '50.00',
|
||||
'new_tuition_third_student_discount' => '50.00',
|
||||
'new_tuition_fourth_plus_discount' => '100.00',
|
||||
];
|
||||
|
||||
foreach ($defaults as $key => $value) {
|
||||
$row = $this->db->table('configuration')
|
||||
->select('id, config_value')
|
||||
->where('config_key', $key)
|
||||
->orderBy('id', 'ASC')
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if (!$row) {
|
||||
$this->db->table('configuration')->insert([
|
||||
'config_key' => $key,
|
||||
'config_value' => $value,
|
||||
]);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (trim((string) ($row['config_value'] ?? '')) === '') {
|
||||
$this->db->table('configuration')
|
||||
->where('config_key', $key)
|
||||
->update(['config_value' => $value]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected function archivePaypalTables(): void
|
||||
{
|
||||
$this->renameTableIfPresent('paypal_payments', 'archived_paypal_payments');
|
||||
$this->renameTableIfPresent('paypal_transactions', 'archived_paypal_transactions');
|
||||
}
|
||||
|
||||
protected function restorePaypalTables(): void
|
||||
{
|
||||
$this->renameTableIfPresent('archived_paypal_payments', 'paypal_payments');
|
||||
$this->renameTableIfPresent('archived_paypal_transactions', 'paypal_transactions');
|
||||
}
|
||||
|
||||
protected function refreshFinancialNavItems(): void
|
||||
{
|
||||
if (!$this->db->tableExists('nav_items')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$parentColumn = null;
|
||||
if ($this->db->fieldExists('menu_parent_id', 'nav_items')) {
|
||||
$parentColumn = 'menu_parent_id';
|
||||
} elseif ($this->db->fieldExists('parent_id', 'nav_items')) {
|
||||
$parentColumn = 'parent_id';
|
||||
}
|
||||
|
||||
if ($parentColumn === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db->table('nav_items')
|
||||
->groupStart()
|
||||
->where('url', 'administrator/paypal_transactions')
|
||||
->orWhere('url', 'admin/paypal-transactions')
|
||||
->orWhere('label', 'PaypalTransactions')
|
||||
->orWhere('label', 'PayPal Transactions')
|
||||
->groupEnd()
|
||||
->delete();
|
||||
|
||||
$financialRow = $this->db->table('nav_items')
|
||||
->select('id')
|
||||
->where('label', 'Financial')
|
||||
->where($parentColumn, null)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if (!$financialRow) {
|
||||
return;
|
||||
}
|
||||
|
||||
$forecastUrl = 'administrator/tuition-forecast';
|
||||
$existing = $this->db->table('nav_items')
|
||||
->select('id')
|
||||
->where('url', $forecastUrl)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if ($existing) {
|
||||
$forecastId = (int) $existing['id'];
|
||||
} else {
|
||||
$this->db->table('nav_items')->insert([
|
||||
$parentColumn => (int) $financialRow['id'],
|
||||
'label' => 'Tuition Forecast',
|
||||
'url' => $forecastUrl,
|
||||
'sort_order' => 4,
|
||||
'is_enabled' => 1,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
$forecastId = (int) $this->db->insertID();
|
||||
}
|
||||
|
||||
if ($forecastId <= 0 || !$this->db->tableExists('role_nav_items') || !$this->db->tableExists('roles')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$roles = $this->db->table('roles')
|
||||
->select('id')
|
||||
->whereIn('name', ['administrator', 'administrative staff', 'principal', 'vice_principal', 'head of department (finance)'])
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
foreach ($roles as $role) {
|
||||
$roleId = (int) ($role['id'] ?? 0);
|
||||
if ($roleId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$exists = $this->db->table('role_nav_items')
|
||||
->where('role_id', $roleId)
|
||||
->where('nav_item_id', $forecastId)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if ($exists) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->db->table('role_nav_items')->insert([
|
||||
'role_id' => $roleId,
|
||||
'nav_item_id' => $forecastId,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
protected function renameTableIfPresent(string $from, string $to): void
|
||||
{
|
||||
if (!$this->db->tableExists($from) || $this->db->tableExists($to)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db->query(sprintf('RENAME TABLE `%s` TO `%s`', $from, $to));
|
||||
}
|
||||
|
||||
protected function addIndexIfMissing(string $table, string $indexName, array $columns, bool $unique = false): void
|
||||
{
|
||||
if (!$this->db->tableExists($table) || $this->indexExists($table, $indexName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$quotedColumns = implode(', ', array_map(static fn (string $column): string => '`' . $column . '`', $columns));
|
||||
$type = $unique ? 'UNIQUE INDEX' : 'INDEX';
|
||||
$sql = sprintf('ALTER TABLE `%s` ADD %s `%s` (%s)', $table, $type, $indexName, $quotedColumns);
|
||||
$this->db->query($sql);
|
||||
}
|
||||
|
||||
protected function dropIndexIfExists(string $table, string $indexName): void
|
||||
{
|
||||
if (!$this->db->tableExists($table) || !$this->indexExists($table, $indexName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db->query(sprintf('ALTER TABLE `%s` DROP INDEX `%s`', $table, $indexName));
|
||||
}
|
||||
|
||||
protected function indexExists(string $table, string $indexName): bool
|
||||
{
|
||||
if (!$this->db->tableExists($table)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$rows = $this->db->query(sprintf('SHOW INDEX FROM `%s`', $table))->getResultArray();
|
||||
foreach ($rows as $row) {
|
||||
if (($row['Key_name'] ?? null) === $indexName) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function hasDuplicateTransactionIds(): bool
|
||||
{
|
||||
$row = $this->db->table('payments')
|
||||
->select('transaction_id')
|
||||
->where('transaction_id IS NOT NULL', null, false)
|
||||
->where('transaction_id !=', '')
|
||||
->groupBy('transaction_id')
|
||||
->having('COUNT(*) >', 1, false)
|
||||
->get(1)
|
||||
->getRowArray();
|
||||
|
||||
return $row !== null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class UpdateYouthTuitionDefaults extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
if (!$this->db->tableExists('configuration')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->upsertConfig('youth_fee', '200.00', ['180', '180.00']);
|
||||
$this->upsertConfig('new_tuition_youth_amount', '200.00', ['180', '180.00']);
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
if (!$this->db->tableExists('configuration')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->rollbackConfig('youth_fee', '180.00');
|
||||
$this->rollbackConfig('new_tuition_youth_amount', '180.00');
|
||||
}
|
||||
|
||||
protected function upsertConfig(string $key, string $value, array $legacyValues = []): void
|
||||
{
|
||||
$row = $this->db->table('configuration')
|
||||
->select('id, config_value')
|
||||
->where('config_key', $key)
|
||||
->orderBy('id', 'ASC')
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if (!$row) {
|
||||
$this->db->table('configuration')->insert([
|
||||
'config_key' => $key,
|
||||
'config_value' => $value,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$current = trim((string) ($row['config_value'] ?? ''));
|
||||
if ($current === '' || in_array($current, $legacyValues, true)) {
|
||||
$this->db->table('configuration')
|
||||
->where('config_key', $key)
|
||||
->update(['config_value' => $value]);
|
||||
}
|
||||
}
|
||||
|
||||
protected function rollbackConfig(string $key, string $value): void
|
||||
{
|
||||
$this->db->table('configuration')
|
||||
->where('config_key', $key)
|
||||
->where('config_value', '200.00')
|
||||
->update(['config_value' => $value]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class FixSchoolYearColumns extends Migration
|
||||
{
|
||||
/**
|
||||
* Tables that directly own an academic year.
|
||||
*
|
||||
* school_year stays as text by design. Valid values use YYYY-YYYY and
|
||||
* the second year must be exactly the first year + 1.
|
||||
*/
|
||||
private array $yearOwnerTables = [
|
||||
'additional_charges',
|
||||
'archived_paypal_transactions',
|
||||
'attendance_data',
|
||||
'attendance_day',
|
||||
'attendance_record',
|
||||
'attendance_tracking',
|
||||
'badge_print_logs',
|
||||
'below_sixty_decisions',
|
||||
'calendar_events',
|
||||
'certificate_records',
|
||||
'classSection',
|
||||
'class_progress_reports',
|
||||
'competitions',
|
||||
'current_flag',
|
||||
'discount_vouchers',
|
||||
'early_dismissal_signatures',
|
||||
'enrollments',
|
||||
'events',
|
||||
'exams',
|
||||
'exam_drafts',
|
||||
'expenses',
|
||||
'final_exam',
|
||||
'final_score',
|
||||
'flag',
|
||||
'grading_locks',
|
||||
'homework',
|
||||
'inventory_movements',
|
||||
'invoices',
|
||||
'late_slip_logs',
|
||||
'manual_payments',
|
||||
'midterm_exam',
|
||||
'missing_score_overrides',
|
||||
'parent_attendance_reports',
|
||||
'parent_meeting_schedules',
|
||||
'parent_notifications',
|
||||
'participation',
|
||||
'payments',
|
||||
'placement_batches',
|
||||
'print_requests',
|
||||
'project',
|
||||
'quiz',
|
||||
'refunds',
|
||||
'reimbursements',
|
||||
'reimbursement_batches',
|
||||
'report_card_acknowledgements',
|
||||
'scan_log',
|
||||
'score_comments',
|
||||
'semester_scores',
|
||||
'staff_attendance',
|
||||
'student_class',
|
||||
'student_decisions',
|
||||
'teacher_attendance_data',
|
||||
'teacher_class',
|
||||
'teacher_submission_notification_history',
|
||||
'whatsapp_group_links',
|
||||
'whatsapp_group_memberships',
|
||||
];
|
||||
|
||||
/** Tables where school_year is redundant or conceptually incorrect. */
|
||||
private array $tablesWithoutDirectYear = [
|
||||
'chapters',
|
||||
'classes',
|
||||
'class_preparation_log',
|
||||
'class_prep_adjustments',
|
||||
'contactus',
|
||||
'emergency_contacts',
|
||||
'inventory_items',
|
||||
'invoice_students_list',
|
||||
'ip_attempts',
|
||||
'login_activity',
|
||||
'messages',
|
||||
'notifications',
|
||||
'notification_recipients',
|
||||
'parents',
|
||||
'paypal_transactions',
|
||||
'placement_levels',
|
||||
'preferences',
|
||||
'staff',
|
||||
'students',
|
||||
'support_requests',
|
||||
'users',
|
||||
'user_notifications',
|
||||
];
|
||||
|
||||
/** Tables where semester is redundant or conceptually incorrect. */
|
||||
private array $tablesWithoutDirectSemester = [
|
||||
'badge_print_logs',
|
||||
'classes',
|
||||
'contactus',
|
||||
'emergency_contacts',
|
||||
'inventory_items',
|
||||
'invoice_students_list',
|
||||
'ip_attempts',
|
||||
'notification_recipients',
|
||||
'notifications',
|
||||
'parents',
|
||||
'support_requests',
|
||||
'user_notifications',
|
||||
'whatsapp_group_links',
|
||||
];
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
if ($this->db->DBDriver !== 'MySQLi') {
|
||||
throw new \RuntimeException(
|
||||
'This migration targets MySQL 8 because it uses enforced CHECK constraints.'
|
||||
);
|
||||
}
|
||||
|
||||
// These annual entities lacked a school_year column in the audited schema.
|
||||
foreach (['class_progress_reports', 'exams', 'print_requests'] as $table) {
|
||||
if ($this->db->tableExists($table) && ! $this->db->fieldExists('school_year', $table)) {
|
||||
// Nullable avoids inventing a year for existing rows.
|
||||
// Backfill it, then make it NOT NULL in a later migration.
|
||||
$this->forge->addColumn($table, [
|
||||
'school_year' => [
|
||||
'type' => 'VARCHAR',
|
||||
'constraint' => 9,
|
||||
'null' => true,
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate and normalize every direct owner to VARCHAR(9).
|
||||
foreach ($this->yearOwnerTables as $table) {
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->assertValidSchoolYears($table, 'school_year');
|
||||
$this->normalizeYearColumn($table, 'school_year');
|
||||
$this->ensureYearCheckConstraint($table, 'school_year');
|
||||
$this->ensureYearIndex($table, 'school_year');
|
||||
}
|
||||
|
||||
// Promotion is a transition and legitimately owns both source and target years.
|
||||
if ($this->db->tableExists('promotion_queue')) {
|
||||
foreach (['school_year_from', 'school_year_to'] as $column) {
|
||||
if (! $this->db->fieldExists($column, 'promotion_queue')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->assertValidSchoolYears('promotion_queue', $column);
|
||||
$this->normalizeYearColumn('promotion_queue', $column);
|
||||
$this->ensureYearCheckConstraint('promotion_queue', $column);
|
||||
$this->ensureYearIndex('promotion_queue', $column);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove redundant columns. Dependent non-primary indexes are removed first.
|
||||
foreach ($this->tablesWithoutDirectYear as $table) {
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->dropIndexesContainingColumn($table, 'school_year');
|
||||
$this->dropChecksContainingColumn($table, 'school_year');
|
||||
$this->forge->dropColumn($table, 'school_year');
|
||||
}
|
||||
|
||||
foreach ($this->tablesWithoutDirectSemester as $table) {
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('semester', $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->dropIndexesContainingColumn($table, 'semester');
|
||||
$this->dropChecksContainingColumn($table, 'semester');
|
||||
$this->forge->dropColumn($table, 'semester');
|
||||
}
|
||||
|
||||
foreach ($this->yearOwnerTables as $table) {
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->ensureYearIndex($table, 'school_year');
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
throw new \RuntimeException(
|
||||
'This migration is intentionally irreversible because dropping school_year columns destroys data. Restore from backup instead of pretending rollback can resurrect it.'
|
||||
);
|
||||
}
|
||||
|
||||
private function assertValidSchoolYears(string $table, string $column): void
|
||||
{
|
||||
$tableName = $this->quoteIdentifier($table);
|
||||
$columnName = $this->quoteIdentifier($column);
|
||||
|
||||
$invalid = $this->db->query(
|
||||
"SELECT COUNT(*) AS aggregate
|
||||
FROM {$tableName}
|
||||
WHERE {$columnName} IS NOT NULL
|
||||
AND (
|
||||
{$columnName} NOT REGEXP '^[0-9]{4}-[0-9]{4}$'
|
||||
OR CAST(RIGHT({$columnName}, 4) AS UNSIGNED)
|
||||
<> CAST(LEFT({$columnName}, 4) AS UNSIGNED) + 1
|
||||
)"
|
||||
)->getRow();
|
||||
|
||||
if ((int) ($invalid->aggregate ?? 0) > 0) {
|
||||
throw new \RuntimeException(
|
||||
"Cannot migrate {$table}.{$column}: found {$invalid->aggregate} invalid school-year value(s). Expected YYYY-YYYY with consecutive years, for example 2025-2026."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function normalizeYearColumn(string $table, string $column): void
|
||||
{
|
||||
$metadata = $this->db->query(
|
||||
'SELECT IS_NULLABLE, COLLATION_NAME
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?',
|
||||
[$table, $column]
|
||||
)->getRow();
|
||||
|
||||
if ($metadata === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$nullable = $metadata->IS_NULLABLE === 'YES' ? 'NULL' : 'NOT NULL';
|
||||
$collation = $metadata->COLLATION_NAME && preg_match('/^[A-Za-z0-9_]+$/', $metadata->COLLATION_NAME)
|
||||
? ' COLLATE ' . $metadata->COLLATION_NAME
|
||||
: '';
|
||||
|
||||
$this->db->query(sprintf(
|
||||
'ALTER TABLE %s MODIFY COLUMN %s VARCHAR(9)%s %s',
|
||||
$this->quoteIdentifier($table),
|
||||
$this->quoteIdentifier($column),
|
||||
$collation,
|
||||
$nullable
|
||||
));
|
||||
}
|
||||
|
||||
private function ensureYearCheckConstraint(string $table, string $column): void
|
||||
{
|
||||
$constraint = $this->objectName('chk_sy', $table, $column);
|
||||
|
||||
$exists = $this->db->query(
|
||||
'SELECT COUNT(*) AS aggregate
|
||||
FROM information_schema.TABLE_CONSTRAINTS
|
||||
WHERE CONSTRAINT_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND CONSTRAINT_NAME = ?
|
||||
AND CONSTRAINT_TYPE = \'CHECK\'',
|
||||
[$table, $constraint]
|
||||
)->getRow();
|
||||
|
||||
if ((int) ($exists->aggregate ?? 0) > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$columnName = $this->quoteIdentifier($column);
|
||||
|
||||
$this->db->query(sprintf(
|
||||
"ALTER TABLE %s ADD CONSTRAINT %s CHECK (
|
||||
%s IS NULL OR (
|
||||
%s REGEXP '^[0-9]{4}-[0-9]{4}$'
|
||||
AND CAST(RIGHT(%s, 4) AS UNSIGNED)
|
||||
= CAST(LEFT(%s, 4) AS UNSIGNED) + 1
|
||||
)
|
||||
)",
|
||||
$this->quoteIdentifier($table),
|
||||
$this->quoteIdentifier($constraint),
|
||||
$columnName,
|
||||
$columnName,
|
||||
$columnName,
|
||||
$columnName
|
||||
));
|
||||
}
|
||||
|
||||
private function ensureYearIndex(string $table, string $column): void
|
||||
{
|
||||
$indexed = $this->db->query(
|
||||
'SELECT COUNT(*) AS aggregate
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?',
|
||||
[$table, $column]
|
||||
)->getRow();
|
||||
|
||||
if ((int) ($indexed->aggregate ?? 0) > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$index = $this->objectName('idx_sy', $table, $column);
|
||||
|
||||
$this->db->query(sprintf(
|
||||
'ALTER TABLE %s ADD INDEX %s (%s)',
|
||||
$this->quoteIdentifier($table),
|
||||
$this->quoteIdentifier($index),
|
||||
$this->quoteIdentifier($column)
|
||||
));
|
||||
}
|
||||
|
||||
private function dropIndexesContainingColumn(string $table, string $column): void
|
||||
{
|
||||
$indexes = $this->db->query(
|
||||
'SELECT DISTINCT INDEX_NAME
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?
|
||||
AND INDEX_NAME <> \'PRIMARY\'',
|
||||
[$table, $column]
|
||||
)->getResult();
|
||||
|
||||
foreach ($indexes as $index) {
|
||||
$this->db->query(sprintf(
|
||||
'ALTER TABLE %s DROP INDEX %s',
|
||||
$this->quoteIdentifier($table),
|
||||
$this->quoteIdentifier($index->INDEX_NAME)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private function dropChecksContainingColumn(string $table, string $column): void
|
||||
{
|
||||
$checks = $this->db->query(
|
||||
'SELECT tc.CONSTRAINT_NAME
|
||||
FROM information_schema.TABLE_CONSTRAINTS tc
|
||||
INNER JOIN information_schema.CHECK_CONSTRAINTS cc
|
||||
ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
|
||||
AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
|
||||
WHERE tc.CONSTRAINT_SCHEMA = DATABASE()
|
||||
AND tc.TABLE_NAME = ?
|
||||
AND tc.CONSTRAINT_TYPE = \'CHECK\'
|
||||
AND cc.CHECK_CLAUSE LIKE ?',
|
||||
[$table, '%' . $column . '%']
|
||||
)->getResult();
|
||||
|
||||
foreach ($checks as $check) {
|
||||
$this->db->query(sprintf(
|
||||
'ALTER TABLE %s DROP CHECK %s',
|
||||
$this->quoteIdentifier($table),
|
||||
$this->quoteIdentifier($check->CONSTRAINT_NAME)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private function objectName(string $prefix, string $table, string $column): string
|
||||
{
|
||||
// MySQL identifiers are limited to 64 characters.
|
||||
return substr($prefix . '_' . $table . '_' . $column . '_' . substr(sha1($table . '.' . $column), 0, 8), 0, 64);
|
||||
}
|
||||
|
||||
private function quoteIdentifier(string $identifier): string
|
||||
{
|
||||
return '`' . str_replace('`', '``', $identifier) . '`';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
use RuntimeException;
|
||||
|
||||
final class EnsureSchoolYearOnFinancialTables extends Migration
|
||||
{
|
||||
/** @var array<string, bool> table => nullable */
|
||||
private array $tables = [
|
||||
'discount_usages' => false,
|
||||
'event_charges' => true,
|
||||
'invoice_event' => true,
|
||||
'payment_error' => true,
|
||||
'payment_notification_logs' => true,
|
||||
'payment_transactions' => true,
|
||||
'reimbursement_batch_items' => true,
|
||||
];
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
if ($this->db->DBDriver !== 'MySQLi') {
|
||||
throw new RuntimeException('This migration requires MySQL/MariaDB through the MySQLi driver.');
|
||||
}
|
||||
|
||||
foreach ($this->tables as $table => $nullable) {
|
||||
if (! $this->db->tableExists($table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $this->db->fieldExists('school_year', $table)) {
|
||||
$this->forge->addColumn($table, [
|
||||
'school_year' => [
|
||||
'type' => 'VARCHAR',
|
||||
'constraint' => 9,
|
||||
'null' => $nullable,
|
||||
'after' => $this->afterColumn($table),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
$this->backfillSchoolYear($table);
|
||||
$this->assertValidYears($table);
|
||||
|
||||
$nullSql = $nullable ? 'NULL' : 'NOT NULL';
|
||||
$this->db->query(
|
||||
sprintf(
|
||||
'ALTER TABLE `%s` MODIFY `school_year` VARCHAR(9) %s',
|
||||
str_replace('`', '``', $table),
|
||||
$nullSql
|
||||
)
|
||||
);
|
||||
|
||||
$this->ensureIndex($table);
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// These columns are part of the business model and must not be dropped on rollback.
|
||||
}
|
||||
|
||||
private function assertValidYears(string $table): void
|
||||
{
|
||||
$sql = sprintf(
|
||||
"SELECT COUNT(*) AS invalid_count
|
||||
FROM `%s`
|
||||
WHERE `school_year` IS NOT NULL
|
||||
AND (
|
||||
`school_year` NOT REGEXP '^[0-9]{4}-[0-9]{4}$'
|
||||
OR CAST(RIGHT(`school_year`, 4) AS UNSIGNED)
|
||||
<> CAST(LEFT(`school_year`, 4) AS UNSIGNED) + 1
|
||||
)",
|
||||
str_replace('`', '``', $table)
|
||||
);
|
||||
|
||||
$row = $this->db->query($sql)->getRowArray();
|
||||
$invalid = (int) ($row['invalid_count'] ?? 0);
|
||||
|
||||
if ($invalid > 0) {
|
||||
throw new RuntimeException(
|
||||
"Cannot normalize {$table}.school_year: {$invalid} invalid value(s). Expected YYYY-YYYY, for example 2025-2026."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function backfillSchoolYear(string $table): void
|
||||
{
|
||||
if ($table === 'discount_usages' && $this->db->tableExists('invoices')) {
|
||||
$this->db->query(
|
||||
"UPDATE `discount_usages` du
|
||||
INNER JOIN `invoices` i ON i.`id` = du.`invoice_id`
|
||||
SET du.`school_year` = i.`school_year`
|
||||
WHERE (du.`school_year` IS NULL OR TRIM(du.`school_year`) = '')
|
||||
AND i.`school_year` REGEXP '^[0-9]{4}-[0-9]{4}$'
|
||||
AND CAST(RIGHT(i.`school_year`, 4) AS UNSIGNED)
|
||||
= CAST(LEFT(i.`school_year`, 4) AS UNSIGNED) + 1"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function ensureIndex(string $table): void
|
||||
{
|
||||
$indexName = 'idx_' . $table . '_school_year';
|
||||
if (strlen($indexName) > 64) {
|
||||
$indexName = 'idx_' . substr(hash('sha256', $table . '_school_year'), 0, 24);
|
||||
}
|
||||
|
||||
$row = $this->db->query(
|
||||
'SELECT COUNT(*) AS index_count
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?',
|
||||
[$table, 'school_year']
|
||||
)->getRowArray();
|
||||
|
||||
if ((int) ($row['index_count'] ?? 0) === 0) {
|
||||
$this->db->query(sprintf(
|
||||
'CREATE INDEX `%s` ON `%s` (`school_year`)',
|
||||
str_replace('`', '``', $indexName),
|
||||
str_replace('`', '``', $table)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private function afterColumn(string $table): string
|
||||
{
|
||||
$preferred = ['semester', 'invoice_id', 'payment_id', 'batch_id'];
|
||||
foreach ($preferred as $column) {
|
||||
if ($this->db->fieldExists($column, $table)) {
|
||||
return $column;
|
||||
}
|
||||
}
|
||||
|
||||
return 'id';
|
||||
}
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
use RuntimeException;
|
||||
|
||||
final class ApplySchoolYearSemesterAuditCorrections extends Migration
|
||||
{
|
||||
private array $schoolYearIndexTables = [
|
||||
'archived_paypal_transactions',
|
||||
'class_progress_reports',
|
||||
'exams',
|
||||
'missing_score_overrides',
|
||||
'payments',
|
||||
'placement_batches',
|
||||
'print_requests',
|
||||
'report_card_acknowledgements',
|
||||
'semester_scores',
|
||||
'staff_attendance',
|
||||
'teacher_attendance_data',
|
||||
'whatsapp_group_links',
|
||||
];
|
||||
|
||||
private array $semesterDropTables = [
|
||||
'badge_print_logs',
|
||||
'classes',
|
||||
'contactus',
|
||||
'emergency_contacts',
|
||||
'inventory_items',
|
||||
'invoice_students_list',
|
||||
'ip_attempts',
|
||||
'notification_recipients',
|
||||
'notifications',
|
||||
'parents',
|
||||
'support_requests',
|
||||
'user_notifications',
|
||||
'whatsapp_group_links',
|
||||
];
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
if ($this->db->DBDriver !== 'MySQLi') {
|
||||
throw new RuntimeException('This migration requires MySQL/MariaDB through the MySQLi driver.');
|
||||
}
|
||||
|
||||
if ($this->db->tableExists('archived_paypal_transactions')
|
||||
&& $this->db->fieldExists('school_year', 'archived_paypal_transactions')) {
|
||||
$this->assertValidSchoolYears('archived_paypal_transactions', 'school_year');
|
||||
$this->normalizeYearColumn('archived_paypal_transactions', 'school_year');
|
||||
$this->ensureYearCheckConstraint('archived_paypal_transactions', 'school_year');
|
||||
}
|
||||
|
||||
foreach ($this->schoolYearIndexTables as $table) {
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->ensureIndex($table, 'school_year');
|
||||
}
|
||||
|
||||
foreach ($this->semesterDropTables as $table) {
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('semester', $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->dropIndexesContainingColumn($table, 'semester');
|
||||
$this->dropChecksContainingColumn($table, 'semester');
|
||||
$this->forge->dropColumn($table, 'semester');
|
||||
}
|
||||
|
||||
foreach ($this->schoolYearIndexTables as $table) {
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->ensureIndex($table, 'school_year');
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
throw new RuntimeException(
|
||||
'This migration is intentionally irreversible because dropping semester columns destroys data.'
|
||||
);
|
||||
}
|
||||
|
||||
private function assertValidSchoolYears(string $table, string $column): void
|
||||
{
|
||||
$tableName = $this->quoteIdentifier($table);
|
||||
$columnName = $this->quoteIdentifier($column);
|
||||
|
||||
$invalid = $this->db->query(
|
||||
"SELECT COUNT(*) AS aggregate
|
||||
FROM {$tableName}
|
||||
WHERE {$columnName} IS NOT NULL
|
||||
AND (
|
||||
{$columnName} NOT REGEXP '^[0-9]{4}-[0-9]{4}$'
|
||||
OR CAST(RIGHT({$columnName}, 4) AS UNSIGNED)
|
||||
<> CAST(LEFT({$columnName}, 4) AS UNSIGNED) + 1
|
||||
)"
|
||||
)->getRow();
|
||||
|
||||
if ((int) ($invalid->aggregate ?? 0) > 0) {
|
||||
throw new RuntimeException(
|
||||
"Cannot migrate {$table}.{$column}: found {$invalid->aggregate} invalid school-year value(s)."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function normalizeYearColumn(string $table, string $column): void
|
||||
{
|
||||
$metadata = $this->db->query(
|
||||
'SELECT IS_NULLABLE, COLLATION_NAME
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?',
|
||||
[$table, $column]
|
||||
)->getRow();
|
||||
|
||||
if ($metadata === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$nullable = $metadata->IS_NULLABLE === 'YES' ? 'NULL' : 'NOT NULL';
|
||||
$collation = $metadata->COLLATION_NAME && preg_match('/^[A-Za-z0-9_]+$/', $metadata->COLLATION_NAME)
|
||||
? ' COLLATE ' . $metadata->COLLATION_NAME
|
||||
: '';
|
||||
|
||||
$this->db->query(sprintf(
|
||||
'ALTER TABLE %s MODIFY COLUMN %s VARCHAR(9)%s %s',
|
||||
$this->quoteIdentifier($table),
|
||||
$this->quoteIdentifier($column),
|
||||
$collation,
|
||||
$nullable
|
||||
));
|
||||
}
|
||||
|
||||
private function ensureYearCheckConstraint(string $table, string $column): void
|
||||
{
|
||||
$constraint = $this->objectName('chk_sy', $table, $column);
|
||||
|
||||
$exists = $this->db->query(
|
||||
'SELECT COUNT(*) AS aggregate
|
||||
FROM information_schema.TABLE_CONSTRAINTS
|
||||
WHERE CONSTRAINT_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND CONSTRAINT_NAME = ?
|
||||
AND CONSTRAINT_TYPE = \'CHECK\'',
|
||||
[$table, $constraint]
|
||||
)->getRow();
|
||||
|
||||
if ((int) ($exists->aggregate ?? 0) > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$columnName = $this->quoteIdentifier($column);
|
||||
|
||||
$this->db->query(sprintf(
|
||||
"ALTER TABLE %s ADD CONSTRAINT %s CHECK (
|
||||
%s IS NULL OR (
|
||||
%s REGEXP '^[0-9]{4}-[0-9]{4}$'
|
||||
AND CAST(RIGHT(%s, 4) AS UNSIGNED)
|
||||
= CAST(LEFT(%s, 4) AS UNSIGNED) + 1
|
||||
)
|
||||
)",
|
||||
$this->quoteIdentifier($table),
|
||||
$this->quoteIdentifier($constraint),
|
||||
$columnName,
|
||||
$columnName,
|
||||
$columnName,
|
||||
$columnName
|
||||
));
|
||||
}
|
||||
|
||||
private function ensureIndex(string $table, string $column): void
|
||||
{
|
||||
$indexed = $this->db->query(
|
||||
'SELECT COUNT(*) AS aggregate
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?',
|
||||
[$table, $column]
|
||||
)->getRow();
|
||||
|
||||
if ((int) ($indexed->aggregate ?? 0) > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db->query(sprintf(
|
||||
'ALTER TABLE %s ADD INDEX %s (%s)',
|
||||
$this->quoteIdentifier($table),
|
||||
$this->quoteIdentifier($this->objectName('idx_sy', $table, $column)),
|
||||
$this->quoteIdentifier($column)
|
||||
));
|
||||
}
|
||||
|
||||
private function dropIndexesContainingColumn(string $table, string $column): void
|
||||
{
|
||||
$indexes = $this->db->query(
|
||||
'SELECT DISTINCT INDEX_NAME
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?
|
||||
AND INDEX_NAME <> \'PRIMARY\'',
|
||||
[$table, $column]
|
||||
)->getResult();
|
||||
|
||||
foreach ($indexes as $index) {
|
||||
$this->db->query(sprintf(
|
||||
'ALTER TABLE %s DROP INDEX %s',
|
||||
$this->quoteIdentifier($table),
|
||||
$this->quoteIdentifier($index->INDEX_NAME)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private function dropChecksContainingColumn(string $table, string $column): void
|
||||
{
|
||||
$checks = $this->db->query(
|
||||
'SELECT tc.CONSTRAINT_NAME
|
||||
FROM information_schema.TABLE_CONSTRAINTS tc
|
||||
INNER JOIN information_schema.CHECK_CONSTRAINTS cc
|
||||
ON cc.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
|
||||
AND cc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
|
||||
WHERE tc.CONSTRAINT_SCHEMA = DATABASE()
|
||||
AND tc.TABLE_NAME = ?
|
||||
AND tc.CONSTRAINT_TYPE = \'CHECK\'
|
||||
AND cc.CHECK_CLAUSE LIKE ?',
|
||||
[$table, '%' . $column . '%']
|
||||
)->getResult();
|
||||
|
||||
foreach ($checks as $check) {
|
||||
$this->db->query(sprintf(
|
||||
'ALTER TABLE %s DROP CHECK %s',
|
||||
$this->quoteIdentifier($table),
|
||||
$this->quoteIdentifier($check->CONSTRAINT_NAME)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private function objectName(string $prefix, string $table, string $column): string
|
||||
{
|
||||
return substr($prefix . '_' . $table . '_' . $column . '_' . substr(sha1($table . '.' . $column), 0, 8), 0, 64);
|
||||
}
|
||||
|
||||
private function quoteIdentifier(string $identifier): string
|
||||
{
|
||||
return '`' . str_replace('`', '``', $identifier) . '`';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
use RuntimeException;
|
||||
|
||||
final class EnsureWhatsappGroupLinksSchoolYearIndex extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if ($this->db->DBDriver !== 'MySQLi') {
|
||||
throw new RuntimeException('This migration requires MySQL/MariaDB through the MySQLi driver.');
|
||||
}
|
||||
|
||||
if (! $this->db->tableExists('whatsapp_group_links')
|
||||
|| ! $this->db->fieldExists('school_year', 'whatsapp_group_links')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$indexed = $this->db->query(
|
||||
'SELECT COUNT(*) AS aggregate
|
||||
FROM information_schema.STATISTICS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?',
|
||||
['whatsapp_group_links', 'school_year']
|
||||
)->getRow();
|
||||
|
||||
if ((int) ($indexed->aggregate ?? 0) > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->db->query(
|
||||
'ALTER TABLE `whatsapp_group_links` ADD INDEX `idx_sy_whatsapp_group_links_school_year` (`school_year`)'
|
||||
);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if ($this->db->tableExists('whatsapp_group_links')) {
|
||||
$this->db->query('ALTER TABLE `whatsapp_group_links` DROP INDEX `idx_sy_whatsapp_group_links_school_year`');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class CreateSchoolYears extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! $this->db->tableExists('school_years')) {
|
||||
$this->forge->addField([
|
||||
'id' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'unsigned' => true,
|
||||
'auto_increment' => true,
|
||||
],
|
||||
'name' => [
|
||||
'type' => 'VARCHAR',
|
||||
'constraint' => 9,
|
||||
'null' => false,
|
||||
],
|
||||
'status' => [
|
||||
'type' => 'VARCHAR',
|
||||
'constraint' => 20,
|
||||
'null' => false,
|
||||
'default' => 'draft',
|
||||
],
|
||||
'starts_on' => [
|
||||
'type' => 'DATE',
|
||||
'null' => true,
|
||||
],
|
||||
'ends_on' => [
|
||||
'type' => 'DATE',
|
||||
'null' => true,
|
||||
],
|
||||
'description' => [
|
||||
'type' => 'TEXT',
|
||||
'null' => true,
|
||||
],
|
||||
'registration_starts_on' => [
|
||||
'type' => 'DATE',
|
||||
'null' => true,
|
||||
],
|
||||
'registration_ends_on' => [
|
||||
'type' => 'DATE',
|
||||
'null' => true,
|
||||
],
|
||||
'previous_school_year_id' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'unsigned' => true,
|
||||
'null' => true,
|
||||
],
|
||||
'next_school_year_id' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'unsigned' => true,
|
||||
'null' => true,
|
||||
],
|
||||
'activated_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
'closing_started_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
'closed_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
'archived_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
'created_by' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'unsigned' => true,
|
||||
'null' => true,
|
||||
],
|
||||
'updated_by' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'unsigned' => true,
|
||||
'null' => true,
|
||||
],
|
||||
'created_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
'updated_at' => [
|
||||
'type' => 'DATETIME',
|
||||
'null' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$this->forge->addKey('id', true);
|
||||
$this->forge->addKey('name', false, true);
|
||||
$this->forge->addKey('status');
|
||||
$this->forge->createTable('school_years');
|
||||
} else {
|
||||
$this->ensureSchoolYearColumns();
|
||||
}
|
||||
|
||||
$this->createClosingTables();
|
||||
|
||||
$configuredYear = $this->configuredSchoolYear();
|
||||
|
||||
if ($configuredYear !== null && $this->isValidYearName($configuredYear)) {
|
||||
$existing = $this->db->table('school_years')
|
||||
->where('name', $configuredYear)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if ($existing === null) {
|
||||
$this->db->table('school_years')->insert([
|
||||
'name' => $configuredYear,
|
||||
'status' => 'active',
|
||||
'activated_at' => date('Y-m-d H:i:s'),
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
'updated_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
$this->forge->dropTable('school_year_transition_logs', true);
|
||||
$this->forge->dropTable('school_year_closing_items', true);
|
||||
$this->forge->dropTable('school_year_closing_batches', true);
|
||||
$this->forge->dropTable('school_years', true);
|
||||
}
|
||||
|
||||
private function ensureSchoolYearColumns(): void
|
||||
{
|
||||
$fields = $this->db->getFieldNames('school_years');
|
||||
$add = [];
|
||||
|
||||
$definitions = [
|
||||
'description' => ['type' => 'TEXT', 'null' => true],
|
||||
'registration_starts_on' => ['type' => 'DATE', 'null' => true],
|
||||
'registration_ends_on' => ['type' => 'DATE', 'null' => true],
|
||||
'previous_school_year_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
|
||||
'next_school_year_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
|
||||
'activated_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
'closing_started_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
'closed_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
'archived_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
'created_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
|
||||
'updated_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
|
||||
];
|
||||
|
||||
foreach ($definitions as $field => $definition) {
|
||||
if (! in_array($field, $fields, true)) {
|
||||
$add[$field] = $definition;
|
||||
}
|
||||
}
|
||||
|
||||
if ($add !== []) {
|
||||
$this->forge->addColumn('school_years', $add);
|
||||
}
|
||||
}
|
||||
|
||||
private function createClosingTables(): void
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_closing_batches')) {
|
||||
$this->forge->addField([
|
||||
'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
|
||||
'source_school_year_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
|
||||
'target_school_year_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
|
||||
'status' => ['type' => 'VARCHAR', 'constraint' => 30, 'null' => false, 'default' => 'preview'],
|
||||
'preview_hash' => ['type' => 'CHAR', 'constraint' => 64, 'null' => true],
|
||||
'total_families' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => false, 'default' => 0],
|
||||
'total_positive_balance' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
|
||||
'total_credit_balance' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
|
||||
'started_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
|
||||
'completed_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
|
||||
'started_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
'completed_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
'failed_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
'failure_message' => ['type' => 'TEXT', 'null' => true],
|
||||
'created_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
'updated_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
]);
|
||||
$this->forge->addKey('id', true);
|
||||
$this->forge->addKey(['source_school_year_id', 'status']);
|
||||
$this->forge->createTable('school_year_closing_batches');
|
||||
}
|
||||
|
||||
if (! $this->db->tableExists('school_year_closing_items')) {
|
||||
$this->forge->addField([
|
||||
'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
|
||||
'closing_batch_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
|
||||
'family_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
|
||||
'source_balance' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
|
||||
'credit_amount' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
|
||||
'adjustment_amount' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
|
||||
'carry_forward_amount' => ['type' => 'DECIMAL', 'constraint' => '12,2', 'null' => false, 'default' => '0.00'],
|
||||
'target_invoice_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
|
||||
'target_adjustment_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
|
||||
'status' => ['type' => 'VARCHAR', 'constraint' => 30, 'null' => false, 'default' => 'pending'],
|
||||
'error_message' => ['type' => 'TEXT', 'null' => true],
|
||||
'created_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
'updated_at' => ['type' => 'DATETIME', 'null' => true],
|
||||
]);
|
||||
$this->forge->addKey('id', true);
|
||||
$this->forge->addKey(['closing_batch_id', 'family_id'], false, true);
|
||||
$this->forge->createTable('school_year_closing_items');
|
||||
}
|
||||
|
||||
if (! $this->db->tableExists('school_year_transition_logs')) {
|
||||
$this->forge->addField([
|
||||
'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
|
||||
'school_year_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
|
||||
'from_status' => ['type' => 'VARCHAR', 'constraint' => 20, 'null' => true],
|
||||
'to_status' => ['type' => 'VARCHAR', 'constraint' => 20, 'null' => true],
|
||||
'action' => ['type' => 'VARCHAR', 'constraint' => 80, 'null' => false],
|
||||
'performed_by' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
|
||||
'metadata_json' => ['type' => 'TEXT', 'null' => true],
|
||||
'created_at' => ['type' => 'DATETIME', 'null' => false],
|
||||
]);
|
||||
$this->forge->addKey('id', true);
|
||||
$this->forge->addKey(['school_year_id', 'created_at']);
|
||||
$this->forge->createTable('school_year_transition_logs');
|
||||
}
|
||||
}
|
||||
|
||||
private function configuredSchoolYear(): ?string
|
||||
{
|
||||
if (! $this->db->tableExists('configuration')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$row = $this->db->table('configuration')
|
||||
->select('config_value')
|
||||
->where('config_key', 'school_year')
|
||||
->orderBy('id', 'DESC')
|
||||
->get(1)
|
||||
->getRowArray();
|
||||
|
||||
$value = trim((string) ($row['config_value'] ?? ''));
|
||||
|
||||
return $value !== '' ? $value : null;
|
||||
}
|
||||
|
||||
private function isValidYearName(string $value): bool
|
||||
{
|
||||
if (! preg_match('/^(\d{4})-(\d{4})$/', $value, $matches)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (int) $matches[2] === (int) $matches[1] + 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class AddSchoolYearsNavItem extends Migration
|
||||
{
|
||||
private string $url = 'administrator/school-years';
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
if (! $this->db->tableExists('nav_items')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$parentColumn = $this->parentColumn();
|
||||
$existingQuery = $this->db->table('nav_items')
|
||||
->where('url', $this->url)
|
||||
->get();
|
||||
|
||||
$existing = $existingQuery !== false ? $existingQuery->getRowArray() : null;
|
||||
|
||||
if ($existing !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$parentBuilder = $this->db->table('nav_items')
|
||||
->where('label', 'Configuration');
|
||||
|
||||
if ($parentColumn !== null) {
|
||||
$parentBuilder->where($parentColumn, null);
|
||||
}
|
||||
|
||||
$parentQuery = $parentBuilder->get();
|
||||
$parent = $parentQuery !== false ? $parentQuery->getRowArray() : null;
|
||||
|
||||
$insert = [
|
||||
'label' => 'School Years',
|
||||
'url' => $this->url,
|
||||
'sort_order' => 2,
|
||||
'is_enabled' => 1,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
];
|
||||
|
||||
if ($parentColumn !== null) {
|
||||
$insert[$parentColumn] = $parent['id'] ?? null;
|
||||
}
|
||||
|
||||
$this->db->table('nav_items')->insert($insert);
|
||||
|
||||
$navItemId = (int) $this->db->insertID();
|
||||
|
||||
if (
|
||||
$navItemId <= 0
|
||||
|| ! $this->db->tableExists('role_nav_items')
|
||||
|| ! $this->db->fieldExists('role', 'role_nav_items')
|
||||
|| ! $this->db->fieldExists('nav_item_id', 'role_nav_items')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (['administrator', 'principal', 'vice_principal'] as $role) {
|
||||
$this->db->table('role_nav_items')->insert([
|
||||
'role' => $role,
|
||||
'nav_item_id' => $navItemId,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (! $this->db->tableExists('nav_items')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$query = $this->db->table('nav_items')
|
||||
->where('url', $this->url)
|
||||
->get();
|
||||
|
||||
$row = $query !== false ? $query->getRowArray() : null;
|
||||
|
||||
if ($row === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->db->tableExists('role_nav_items')) {
|
||||
$this->db->table('role_nav_items')
|
||||
->where('nav_item_id', (int) $row['id'])
|
||||
->delete();
|
||||
}
|
||||
|
||||
$this->db->table('nav_items')
|
||||
->where('id', (int) $row['id'])
|
||||
->delete();
|
||||
}
|
||||
|
||||
private function parentColumn(): ?string
|
||||
{
|
||||
if ($this->db->fieldExists('parent_id', 'nav_items')) {
|
||||
return 'parent_id';
|
||||
}
|
||||
|
||||
if ($this->db->fieldExists('menu_parent_id', 'nav_items')) {
|
||||
return 'menu_parent_id';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ class NavSeeder extends Seeder
|
||||
|
||||
// Configuration
|
||||
['parent'=>'Configuration','label'=>'Add/Edit Configuration','url'=>'configuration/configuration_view','sort_order'=>1],
|
||||
['parent'=>'Configuration','label'=>'School Years','url'=>'administrator/school-years','sort_order'=>2],
|
||||
|
||||
// Staffing
|
||||
['parent'=>'Staffing','label'=>'Staff Profile','url'=>'staff/index','sort_order'=>1],
|
||||
@@ -86,9 +87,9 @@ class NavSeeder extends Seeder
|
||||
['parent'=>'Financial','label'=>'Discount Management','url'=>'discounts/list','sort_order'=>1],
|
||||
['parent'=>'Financial','label'=>'Expenses Management','url'=>'expenses/index','sort_order'=>2],
|
||||
['parent'=>'Financial','label'=>'Financial Report','url'=>'payment/financial_report','sort_order'=>3],
|
||||
['parent'=>'Financial','label'=>'Invoices Management','url'=>'invoice_payment/invoice_management','sort_order'=>4],
|
||||
['parent'=>'Financial','label'=>'Manual Payment','url'=>'payment/manual_pay','sort_order'=>5],
|
||||
['parent'=>'Financial','label'=>'PaypalTransactions','url'=>'administrator/paypal_transactions','sort_order'=>6],
|
||||
['parent'=>'Financial','label'=>'Tuition Forecast','url'=>'administrator/tuition-forecast','sort_order'=>4],
|
||||
['parent'=>'Financial','label'=>'Invoices Management','url'=>'invoice_payment/invoice_management','sort_order'=>5],
|
||||
['parent'=>'Financial','label'=>'Manual Payment','url'=>'payment/manual_pay','sort_order'=>6],
|
||||
['parent'=>'Financial','label'=>'Refund Management','url'=>'refunds/list','sort_order'=>7],
|
||||
['parent'=>'Financial','label'=>'Reimbursement Management','url'=>'reimbursements/index','sort_order'=>8],
|
||||
|
||||
|
||||
+79
-26
@@ -35,7 +35,7 @@ class AuthFilter implements FilterInterface
|
||||
public function before(RequestInterface $request, $arguments = null)
|
||||
{
|
||||
$session = session();
|
||||
$userRoles = $session->get('roles'); // not used here, but keep if other code expects it
|
||||
$userRoles = $session->get('roles');
|
||||
$userId = $session->get('user_id');
|
||||
$loginTime = (int) $session->get('login_time');
|
||||
|
||||
@@ -66,35 +66,16 @@ class AuthFilter implements FilterInterface
|
||||
return $this->deny($request, "You don't have permission to use this feature.");
|
||||
}
|
||||
|
||||
// Route arguments: ['filter' => 'auth:permission_name|alt_permission,update']
|
||||
// Route arguments patterns supported:
|
||||
// auth -> default 'read'
|
||||
// auth:read -> CRUD only
|
||||
// auth:create -> CRUD only
|
||||
// auth:update -> CRUD only
|
||||
// auth:delete -> CRUD only
|
||||
// auth:permA|permB,read -> permission + CRUD
|
||||
$requiredPermission = null;
|
||||
$crudAction = 'read';
|
||||
[$requirements, $crudAction] = $this->parseRequirements($arguments);
|
||||
|
||||
if (!empty($arguments)) {
|
||||
$arg0 = strtolower((string) $arguments[0]);
|
||||
|
||||
// If only one argument and it's a CRUD keyword, treat as CRUD-only
|
||||
if (count($arguments) === 1 && in_array($arg0, ['create', 'read', 'update', 'delete'], true)) {
|
||||
$crudAction = $arg0;
|
||||
} else {
|
||||
// Otherwise, first arg is permission(s); optional second is CRUD
|
||||
$requiredPermission = $arguments[0]; // e.g., 'edit_student|manage_students'
|
||||
$crudAction = isset($arguments[1]) ? strtolower((string) $arguments[1]) : 'read';
|
||||
if (!in_array($crudAction, ['create', 'read', 'update', 'delete'], true)) {
|
||||
$crudAction = 'read';
|
||||
}
|
||||
}
|
||||
if (!empty($requirements)) {
|
||||
if ($this->matchesAnyRequirement($requirements, $crudAction, $roleIds, (array) $userRoles)) {
|
||||
return;
|
||||
}
|
||||
|
||||
return $this->deny($request, "You don't have permission to use this feature.");
|
||||
}
|
||||
|
||||
// No explicit route permission: fall back to menu rules
|
||||
if ($this->isAllowedByMenu($request, $roleIds)) {
|
||||
return; // ✅ allowed
|
||||
}
|
||||
@@ -126,6 +107,78 @@ class AuthFilter implements FilterInterface
|
||||
->with('error', 'Your session has expired. Please log in again.');
|
||||
}
|
||||
|
||||
private function parseRequirements(?array $arguments): array
|
||||
{
|
||||
if (empty($arguments)) {
|
||||
return [[], 'read'];
|
||||
}
|
||||
|
||||
$tokens = array_values(array_filter(array_map(static fn($value) => trim((string) $value), $arguments), static fn($value) => $value !== ''));
|
||||
if (empty($tokens)) {
|
||||
return [[], 'read'];
|
||||
}
|
||||
|
||||
$crudAction = 'read';
|
||||
$last = strtolower((string) end($tokens));
|
||||
if (in_array($last, ['create', 'read', 'update', 'delete'], true)) {
|
||||
$crudAction = array_pop($tokens);
|
||||
}
|
||||
|
||||
if (count($tokens) === 1 && in_array(strtolower($tokens[0]), ['create', 'read', 'update', 'delete'], true)) {
|
||||
return [[], strtolower($tokens[0])];
|
||||
}
|
||||
|
||||
return [$tokens, strtolower((string) $crudAction)];
|
||||
}
|
||||
|
||||
private function matchesAnyRequirement(array $requirements, string $crudAction, array $roleIds, array $sessionRoles): bool
|
||||
{
|
||||
$normalizedRoles = array_map(static fn($role) => strtolower(trim((string) $role)), $sessionRoles);
|
||||
|
||||
foreach ($requirements as $requirement) {
|
||||
$alternatives = array_values(array_filter(array_map(static fn($value) => trim((string) $value), explode('|', (string) $requirement))));
|
||||
if (empty($alternatives)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($alternatives as $alternative) {
|
||||
$candidate = strtolower($alternative);
|
||||
if (in_array($candidate, $normalizedRoles, true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($this->userHasNamedPermission($roleIds, $alternative, $crudAction)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function userHasNamedPermission(array $roleIds, string $permissionName, string $crudAction): bool
|
||||
{
|
||||
if (empty($roleIds)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$rows = $this->db->table('role_permissions rp')
|
||||
->join('permissions p', 'p.id = rp.permission_id')
|
||||
->select('rp.*')
|
||||
->whereIn('rp.role_id', $roleIds)
|
||||
->where('LOWER(p.name)', strtolower($permissionName))
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
foreach ($rows as $row) {
|
||||
if ($this->hasPermission($row, $crudAction)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
|
||||
{
|
||||
// No-op
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filters;
|
||||
|
||||
use CodeIgniter\Filters\FilterInterface;
|
||||
use CodeIgniter\HTTP\IncomingRequest;
|
||||
use CodeIgniter\HTTP\RequestInterface;
|
||||
use CodeIgniter\HTTP\ResponseInterface;
|
||||
use Throwable;
|
||||
|
||||
final class RequireSchoolYearFilter implements FilterInterface
|
||||
{
|
||||
public function before(RequestInterface $request, $arguments = null)
|
||||
{
|
||||
if (! $request instanceof IncomingRequest) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
service('schoolYearContext')->resolve($request);
|
||||
return null;
|
||||
} catch (Throwable $e) {
|
||||
log_message('warning', 'School-year request rejected: {message}', [
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return service('response')
|
||||
->setStatusCode(400)
|
||||
->setJSON([
|
||||
'status' => 400,
|
||||
'error' => 'Invalid school year',
|
||||
'message' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,28 @@ if (!function_exists('attendance_comment_template_for_score')) {
|
||||
}
|
||||
}
|
||||
|
||||
return attendance_comment_template_match($templates, $score);
|
||||
}
|
||||
}
|
||||
|
||||
if (!function_exists('attendance_comment_template_match')) {
|
||||
function attendance_comment_template_match(array $templates, float $score): ?array
|
||||
{
|
||||
if ($templates === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Attendance scores are percentage values; clamp to the expected domain
|
||||
// so minor calculation drift above 100 or below 0 does not skip a template.
|
||||
$score = max(0.0, min(100.0, $score));
|
||||
|
||||
usort($templates, static function (array $a, array $b): int {
|
||||
$aMin = isset($a['min_score']) ? (float) $a['min_score'] : 0.0;
|
||||
$bMin = isset($b['min_score']) ? (float) $b['min_score'] : 0.0;
|
||||
|
||||
return $aMin <=> $bMin;
|
||||
});
|
||||
|
||||
foreach ($templates as $template) {
|
||||
$min = isset($template['min_score']) ? (float) $template['min_score'] : 0.0;
|
||||
$max = isset($template['max_score']) ? (float) $template['max_score'] : 100.0;
|
||||
@@ -55,6 +77,18 @@ if (!function_exists('attendance_comment_template_for_score')) {
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
// Some configured bands use integer boundaries like 60-69 and 70-79,
|
||||
// while attendance scores contain decimals like 69.23. When the score
|
||||
// lands in that fractional gap, fall back to the nearest lower band.
|
||||
$candidate = null;
|
||||
foreach ($templates as $template) {
|
||||
$min = isset($template['min_score']) ? (float) $template['min_score'] : 0.0;
|
||||
if ($score < $min) {
|
||||
break;
|
||||
}
|
||||
$candidate = $template;
|
||||
}
|
||||
|
||||
return $candidate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Interfaces;
|
||||
|
||||
interface TuitionCalculatorInterface
|
||||
{
|
||||
public function calculateFamilyTuition(array $students, array $config): array;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Libraries;
|
||||
|
||||
use CodeIgniter\Files\File;
|
||||
use CodeIgniter\HTTP\Files\UploadedFile;
|
||||
|
||||
final class FinancialAttachmentService
|
||||
{
|
||||
private const MAX_BYTES = 5242880;
|
||||
private const ALLOWED_MIMES = [
|
||||
'application/pdf',
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
];
|
||||
private const ALLOWED_EXTENSIONS = [
|
||||
'jpg',
|
||||
'jpeg',
|
||||
'pdf',
|
||||
'png',
|
||||
];
|
||||
|
||||
public function saveUploadedFile($file, string $subdir): ?string
|
||||
{
|
||||
if (!$file instanceof UploadedFile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!$file->isValid() || $file->hasMoved()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$size = (int) ($file->getSize() ?? 0);
|
||||
if ($size <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$mime = strtolower((string) $file->getMimeType());
|
||||
$ext = strtolower((string) $file->getClientExtension());
|
||||
|
||||
if (!in_array($mime, self::ALLOWED_MIMES, true) || !in_array($ext, self::ALLOWED_EXTENSIONS, true)) {
|
||||
throw new \RuntimeException('Unsupported file type. Use PDF, JPG, or PNG.');
|
||||
}
|
||||
|
||||
if ($size > self::MAX_BYTES) {
|
||||
throw new \RuntimeException('File too large. Maximum size is 5 MB.');
|
||||
}
|
||||
|
||||
$dir = $this->ensureSubdir($subdir);
|
||||
$name = $file->getRandomName();
|
||||
$file->move($dir, $name);
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
public function resolvePath(string $subdir, string $filename): ?string
|
||||
{
|
||||
$safeName = basename($filename);
|
||||
if ($safeName === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = $this->ensureSubdir($subdir) . DIRECTORY_SEPARATOR . $safeName;
|
||||
|
||||
return is_file($path) ? $path : null;
|
||||
}
|
||||
|
||||
public function ensureSubdir(string $subdir): string
|
||||
{
|
||||
$path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . trim($subdir, '/');
|
||||
if (!is_dir($path) && !mkdir($path, 0775, true) && !is_dir($path)) {
|
||||
throw new \RuntimeException('Unable to prepare upload directory.');
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public function detectMime(string $path): string
|
||||
{
|
||||
if (function_exists('finfo_open')) {
|
||||
$handle = finfo_open(FILEINFO_MIME_TYPE);
|
||||
if ($handle) {
|
||||
$mime = finfo_file($handle, $path);
|
||||
finfo_close($handle);
|
||||
if (is_string($mime) && $mime !== '') {
|
||||
return $mime;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (function_exists('mime_content_type')) {
|
||||
$mime = mime_content_type($path);
|
||||
if (is_string($mime) && $mime !== '') {
|
||||
return $mime;
|
||||
}
|
||||
}
|
||||
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace App\Libraries;
|
||||
|
||||
final class FinancialStatus
|
||||
{
|
||||
public const INVOICE_UNPAID = 'unpaid';
|
||||
public const INVOICE_PARTIALLY_PAID = 'partially_paid';
|
||||
public const INVOICE_PAID = 'paid';
|
||||
public const INVOICE_OVERPAID = 'overpaid';
|
||||
public const INVOICE_CANCELLED = 'cancelled';
|
||||
|
||||
public const PAYMENT_RECORDED = 'recorded';
|
||||
public const PAYMENT_VOIDED = 'voided';
|
||||
public const PAYMENT_FAILED = 'failed';
|
||||
public const PAYMENT_REFUNDED = 'refunded';
|
||||
public const PAYMENT_CHARGEBACK = 'chargeback';
|
||||
public const PAYMENT_DECLINED = 'declined';
|
||||
public const PAYMENT_REVERSED = 'reversed';
|
||||
public const PAYMENT_CANCELED = 'canceled';
|
||||
public const PAYMENT_CANCELLED = 'cancelled';
|
||||
|
||||
public const PAYMENT_TRANSACTION_STATUSES = [
|
||||
self::PAYMENT_RECORDED,
|
||||
self::PAYMENT_VOIDED,
|
||||
self::PAYMENT_REFUNDED,
|
||||
self::PAYMENT_FAILED,
|
||||
self::PAYMENT_REVERSED,
|
||||
self::PAYMENT_CHARGEBACK,
|
||||
];
|
||||
|
||||
public const INVOICE_STATUSES = [
|
||||
self::INVOICE_UNPAID,
|
||||
self::INVOICE_PARTIALLY_PAID,
|
||||
self::INVOICE_PAID,
|
||||
self::INVOICE_OVERPAID,
|
||||
self::INVOICE_CANCELLED,
|
||||
];
|
||||
|
||||
public const REFUND_PENDING = 'pending';
|
||||
public const REFUND_APPROVED = 'approved';
|
||||
public const REFUND_REJECTED = 'rejected';
|
||||
public const REFUND_PARTIALLY_PAID = 'partially_paid';
|
||||
public const REFUND_PAID = 'paid';
|
||||
public const REFUND_VOIDED = 'voided';
|
||||
|
||||
public const ADDITIONAL_CHARGE_PENDING = 'pending';
|
||||
public const ADDITIONAL_CHARGE_APPLIED = 'applied';
|
||||
public const ADDITIONAL_CHARGE_VOIDED = 'voided';
|
||||
|
||||
public const EXCLUDED_PAYMENT_STATUSES = [
|
||||
self::PAYMENT_VOIDED,
|
||||
self::PAYMENT_FAILED,
|
||||
self::PAYMENT_REFUNDED,
|
||||
self::PAYMENT_CHARGEBACK,
|
||||
self::PAYMENT_DECLINED,
|
||||
self::PAYMENT_REVERSED,
|
||||
self::PAYMENT_CANCELED,
|
||||
self::PAYMENT_CANCELLED,
|
||||
'void',
|
||||
];
|
||||
|
||||
public const REFUND_REDUCES_INVOICE_STATUSES = [
|
||||
self::REFUND_PARTIALLY_PAID,
|
||||
self::REFUND_PAID,
|
||||
'partial',
|
||||
'paid',
|
||||
'Partial',
|
||||
'Paid',
|
||||
];
|
||||
|
||||
public static function normalizeInvoiceStatus(?string $status): string
|
||||
{
|
||||
return match (self::normalize($status)) {
|
||||
'paid', 'full' => self::INVOICE_PAID,
|
||||
'partially paid', 'partially_paid', 'partial' => self::INVOICE_PARTIALLY_PAID,
|
||||
'overpaid' => self::INVOICE_OVERPAID,
|
||||
'cancelled', 'canceled', 'cancelled invoice', 'canceled invoice' => self::INVOICE_CANCELLED,
|
||||
default => self::INVOICE_UNPAID,
|
||||
};
|
||||
}
|
||||
|
||||
public static function normalizePaymentStatus(?string $status): string
|
||||
{
|
||||
return match (self::normalize($status)) {
|
||||
'completed', 'paid', 'full', 'recorded' => self::PAYMENT_RECORDED,
|
||||
'void', 'voided' => self::PAYMENT_VOIDED,
|
||||
'failed' => self::PAYMENT_FAILED,
|
||||
'refunded' => self::PAYMENT_REFUNDED,
|
||||
'chargeback' => self::PAYMENT_CHARGEBACK,
|
||||
'declined' => self::PAYMENT_DECLINED,
|
||||
'reversed' => self::PAYMENT_REVERSED,
|
||||
'cancelled' => self::PAYMENT_CANCELLED,
|
||||
'canceled' => self::PAYMENT_CANCELED,
|
||||
default => self::normalize($status),
|
||||
};
|
||||
}
|
||||
|
||||
public static function normalizeRefundStatus(?string $status): string
|
||||
{
|
||||
return match (self::normalize($status)) {
|
||||
'approved' => self::REFUND_APPROVED,
|
||||
'rejected' => self::REFUND_REJECTED,
|
||||
'partial', 'partially paid', 'partially_paid' => self::REFUND_PARTIALLY_PAID,
|
||||
'paid', 'full' => self::REFUND_PAID,
|
||||
'void', 'voided' => self::REFUND_VOIDED,
|
||||
default => self::REFUND_PENDING,
|
||||
};
|
||||
}
|
||||
|
||||
public static function normalize(?string $status): string
|
||||
{
|
||||
$value = strtolower(trim((string) $status));
|
||||
$value = str_replace('_', ' ', $value);
|
||||
$value = preg_replace('/\s+/', ' ', $value) ?? $value;
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
<?php
|
||||
|
||||
namespace App\Libraries;
|
||||
|
||||
use App\Interfaces\TuitionCalculatorInterface;
|
||||
use App\Libraries\Tuition\NewTuitionCalculatorService;
|
||||
use App\Libraries\Tuition\OldTuitionCalculatorService;
|
||||
use App\Models\AdditionalChargeModel;
|
||||
use App\Models\ClassSectionModel;
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\DiscountUsageModel;
|
||||
use App\Models\EnrollmentModel;
|
||||
use App\Models\EventChargesModel;
|
||||
use App\Models\InvoiceEventModel;
|
||||
use App\Models\InvoiceModel;
|
||||
use App\Models\PaymentModel;
|
||||
use App\Models\RefundModel;
|
||||
use App\Models\StudentClassModel;
|
||||
use App\Models\StudentModel;
|
||||
|
||||
class InvoiceLedgerService
|
||||
{
|
||||
protected InvoiceModel $invoiceModel;
|
||||
protected PaymentModel $paymentModel;
|
||||
protected RefundModel $refundModel;
|
||||
protected DiscountUsageModel $discountUsageModel;
|
||||
protected AdditionalChargeModel $additionalChargeModel;
|
||||
protected ConfigurationModel $configurationModel;
|
||||
protected EnrollmentModel $enrollmentModel;
|
||||
protected StudentClassModel $studentClassModel;
|
||||
protected ClassSectionModel $classSectionModel;
|
||||
protected EventChargesModel $eventChargesModel;
|
||||
protected InvoiceEventModel $invoiceEventModel;
|
||||
protected StudentModel $studentModel;
|
||||
protected TuitionCalculatorInterface $oldCalculator;
|
||||
protected TuitionCalculatorInterface $newCalculator;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->invoiceModel = new InvoiceModel();
|
||||
$this->paymentModel = new PaymentModel();
|
||||
$this->refundModel = new RefundModel();
|
||||
$this->discountUsageModel = new DiscountUsageModel();
|
||||
$this->additionalChargeModel = new AdditionalChargeModel();
|
||||
$this->configurationModel = new ConfigurationModel();
|
||||
$this->enrollmentModel = new EnrollmentModel();
|
||||
$this->studentClassModel = new StudentClassModel();
|
||||
$this->classSectionModel = new ClassSectionModel();
|
||||
$this->eventChargesModel = new EventChargesModel();
|
||||
$this->invoiceEventModel = new InvoiceEventModel();
|
||||
$this->studentModel = new StudentModel();
|
||||
$this->oldCalculator = new OldTuitionCalculatorService();
|
||||
$this->newCalculator = new NewTuitionCalculatorService();
|
||||
}
|
||||
|
||||
public function calculateInvoice(int $invoiceId): array
|
||||
{
|
||||
$invoice = $this->loadInvoice($invoiceId);
|
||||
if ($invoice === null) {
|
||||
throw new \RuntimeException('Invoice not found.');
|
||||
}
|
||||
|
||||
$tuitionTotal = $this->calculateTuitionTotal($invoice);
|
||||
$eventTotal = $this->calculateEventTotal($invoice);
|
||||
$additionalTotal = $this->calculateAdditionalCharges($invoiceId);
|
||||
$discountRawTotal = $this->calculateDiscounts($invoiceId);
|
||||
$paidTotal = $this->calculateValidPayments($invoiceId);
|
||||
$refundPaidTotal = $this->calculatePaidRefunds($invoiceId);
|
||||
|
||||
$tuitionCents = $this->toCents($tuitionTotal);
|
||||
$eventCents = $this->toCents($eventTotal);
|
||||
$additionalCents = $this->toCents($additionalTotal);
|
||||
$discountRawCents = $this->toCents($discountRawTotal);
|
||||
$paidCents = $this->toCents($paidTotal);
|
||||
$refundPaidCents = $this->toCents($refundPaidTotal);
|
||||
|
||||
$discountBaseCents = max(0, $tuitionCents + $additionalCents);
|
||||
$discountCents = min($discountRawCents, $discountBaseCents);
|
||||
$totalAmountCents = $tuitionCents + $eventCents + $additionalCents;
|
||||
$balanceCents = max(0, $totalAmountCents - $discountCents - $paidCents - $refundPaidCents);
|
||||
|
||||
if ($balanceCents === 0) {
|
||||
$status = FinancialStatus::INVOICE_PAID;
|
||||
} elseif ($paidCents > 0 || $discountCents > 0 || $refundPaidCents > 0) {
|
||||
$status = FinancialStatus::INVOICE_PARTIALLY_PAID;
|
||||
} else {
|
||||
$status = FinancialStatus::INVOICE_UNPAID;
|
||||
}
|
||||
|
||||
return [
|
||||
'invoice_id' => $invoiceId,
|
||||
'tuition_total' => $this->fromCents($tuitionCents),
|
||||
'event_total' => $this->fromCents($eventCents),
|
||||
'additional_total' => $this->fromCents($additionalCents),
|
||||
'discount_total' => $this->fromCents($discountCents),
|
||||
'discount_raw_total' => $this->fromCents($discountRawCents),
|
||||
'paid_amount' => $this->fromCents($paidCents),
|
||||
'refund_paid_total' => $this->fromCents($refundPaidCents),
|
||||
'total_amount' => $this->fromCents($totalAmountCents),
|
||||
'balance' => $this->fromCents($balanceCents),
|
||||
'status' => $status,
|
||||
'has_discount' => $discountCents > 0 ? 1 : 0,
|
||||
];
|
||||
}
|
||||
|
||||
public function recalculateInvoice(int $invoiceId): array
|
||||
{
|
||||
$calculation = $this->calculateInvoice($invoiceId);
|
||||
$payload = [
|
||||
'total_amount' => $calculation['total_amount'],
|
||||
'paid_amount' => $calculation['paid_amount'],
|
||||
'balance' => $calculation['balance'],
|
||||
'status' => $calculation['status'],
|
||||
'has_discount' => $calculation['has_discount'],
|
||||
'updated_at' => utc_now(),
|
||||
];
|
||||
|
||||
if ($this->invoiceModel->db->fieldExists('discount', $this->invoiceModel->table)) {
|
||||
$payload['discount'] = $calculation['discount_total'];
|
||||
}
|
||||
|
||||
$this->invoiceModel->update($invoiceId, $payload);
|
||||
|
||||
return $calculation;
|
||||
}
|
||||
|
||||
protected function loadInvoice(int $invoiceId): ?array
|
||||
{
|
||||
return $this->invoiceModel->find($invoiceId);
|
||||
}
|
||||
|
||||
protected function calculateTuitionTotal(array $invoice): float
|
||||
{
|
||||
$parentId = (int) ($invoice['parent_id'] ?? 0);
|
||||
$schoolYear = (string) ($invoice['school_year'] ?? '');
|
||||
if ($parentId <= 0 || $schoolYear === '') {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
$students = $this->loadTuitionStudents($parentId, $schoolYear);
|
||||
$config = $this->getTuitionConfig();
|
||||
$calculator = $this->resolveActiveCalculator();
|
||||
|
||||
return (float) ($calculator->calculateFamilyTuition($students, $config)['total'] ?? 0.0);
|
||||
}
|
||||
|
||||
protected function calculateEventTotal(array $invoice): float
|
||||
{
|
||||
$invoiceId = (int) ($invoice['id'] ?? 0);
|
||||
$invoiceEventRows = $this->invoiceEventModel
|
||||
->select('COALESCE(SUM(amount),0) AS total_amount')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->findAll();
|
||||
|
||||
if (!empty($invoiceEventRows)) {
|
||||
$total = (float) ($invoiceEventRows[0]['total_amount'] ?? 0);
|
||||
if ($total > 0) {
|
||||
return $total;
|
||||
}
|
||||
}
|
||||
|
||||
$rows = $this->eventChargesModel
|
||||
->select('COALESCE(SUM(charged),0) AS total_amount')
|
||||
->where('parent_id', (int) ($invoice['parent_id'] ?? 0))
|
||||
->where('school_year', (string) ($invoice['school_year'] ?? ''))
|
||||
->where('semester', (string) ($invoice['semester'] ?? ''))
|
||||
->findAll();
|
||||
|
||||
return (float) ($rows[0]['total_amount'] ?? 0);
|
||||
}
|
||||
|
||||
protected function calculateAdditionalCharges(int $invoiceId): float
|
||||
{
|
||||
$rows = $this->additionalChargeModel
|
||||
->select('COALESCE(SUM(amount),0) AS total_amount')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->whereNotIn('status', ['void', FinancialStatus::ADDITIONAL_CHARGE_VOIDED, 'cancelled', 'canceled'])
|
||||
->findAll();
|
||||
|
||||
return (float) ($rows[0]['total_amount'] ?? 0);
|
||||
}
|
||||
|
||||
protected function calculateDiscounts(int $invoiceId): float
|
||||
{
|
||||
$row = $this->discountUsageModel
|
||||
->select('COALESCE(SUM(discount_amount),0) AS total_amount')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->first();
|
||||
|
||||
return (float) ($row['total_amount'] ?? 0);
|
||||
}
|
||||
|
||||
protected function calculateValidPayments(int $invoiceId): float
|
||||
{
|
||||
$query = $this->paymentModel
|
||||
->select('COALESCE(SUM(paid_amount),0) AS total_amount')
|
||||
->where('invoice_id', $invoiceId);
|
||||
|
||||
if ($this->paymentModel->db->fieldExists('status', $this->paymentModel->table)) {
|
||||
$query->groupStart()
|
||||
->whereNotIn('status', FinancialStatus::EXCLUDED_PAYMENT_STATUSES)
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
if ($this->paymentModel->db->fieldExists('is_void', $this->paymentModel->table)) {
|
||||
$query->groupStart()
|
||||
->where('is_void', 0)
|
||||
->orWhere('is_void IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
$row = $query->first();
|
||||
|
||||
return (float) ($row['total_amount'] ?? 0);
|
||||
}
|
||||
|
||||
protected function calculatePaidRefunds(int $invoiceId): float
|
||||
{
|
||||
$row = $this->refundModel
|
||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_amount')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->whereIn('status', FinancialStatus::REFUND_REDUCES_INVOICE_STATUSES)
|
||||
->first();
|
||||
|
||||
return (float) ($row['total_amount'] ?? 0);
|
||||
}
|
||||
|
||||
protected function loadTuitionStudents(int $parentId, string $schoolYear): array
|
||||
{
|
||||
$enrollments = $this->enrollmentModel
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
|
||||
if (empty($enrollments)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$refundDeadline = (string) ($this->configurationModel->getConfig('refund_deadline') ?? '');
|
||||
$includeWithdrawn = !$this->isWithinRefundWindow($refundDeadline);
|
||||
$eligibleStatuses = ['enrolled', 'payment pending'];
|
||||
|
||||
if ($includeWithdrawn) {
|
||||
array_push($eligibleStatuses, 'withdrawn', 'refund pending', 'withdraw under review');
|
||||
}
|
||||
|
||||
$students = [];
|
||||
foreach ($enrollments as $enrollment) {
|
||||
$status = strtolower(trim((string) ($enrollment['enrollment_status'] ?? '')));
|
||||
$studentId = (int) ($enrollment['student_id'] ?? 0);
|
||||
if ($studentId <= 0 || !in_array($status, $eligibleStatuses, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$this->studentClassModel->hasNonEventAssignment($studentId, $schoolYear)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$gradeName = $this->resolveGradeName($studentId, $schoolYear, $enrollment['class_section_id'] ?? null);
|
||||
$student = $this->studentModel->find($studentId) ?? [];
|
||||
|
||||
$students[] = [
|
||||
'student_id' => $studentId,
|
||||
'student_name' => trim(((string) ($student['firstname'] ?? '')) . ' ' . ((string) ($student['lastname'] ?? ''))),
|
||||
'grade_level' => $gradeName,
|
||||
];
|
||||
}
|
||||
|
||||
return $students;
|
||||
}
|
||||
|
||||
protected function resolveGradeName(int $studentId, string $schoolYear, $classSectionId = null): string
|
||||
{
|
||||
$sectionId = $classSectionId;
|
||||
if (empty($sectionId)) {
|
||||
$row = $this->studentClassModel
|
||||
->select('class_section_id')
|
||||
->where('student_id', $studentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->orderBy('updated_at', 'DESC')
|
||||
->first();
|
||||
$sectionId = $row['class_section_id'] ?? null;
|
||||
}
|
||||
|
||||
if (empty($sectionId)) {
|
||||
return 'N/A';
|
||||
}
|
||||
|
||||
$name = $this->classSectionModel->getClassSectionNameBySectionId($sectionId);
|
||||
|
||||
return is_string($name) && $name !== '' ? strtoupper(trim($name)) : 'N/A';
|
||||
}
|
||||
|
||||
protected function resolveActiveCalculator(): TuitionCalculatorInterface
|
||||
{
|
||||
$version = strtolower(trim((string) ($this->configurationModel->getConfig('tuition_calculator_version') ?? 'old')));
|
||||
|
||||
return $version === 'new' ? $this->newCalculator : $this->oldCalculator;
|
||||
}
|
||||
|
||||
protected function getTuitionConfig(): array
|
||||
{
|
||||
return [
|
||||
'grade_fee' => $this->configurationModel->getConfig('grade_fee'),
|
||||
'first_student_fee' => $this->configurationModel->getConfig('first_student_fee'),
|
||||
'second_student_fee' => $this->configurationModel->getConfig('second_student_fee'),
|
||||
'youth_fee' => $this->configurationModel->getConfig('youth_fee'),
|
||||
'new_tuition_full_amount' => $this->configurationModel->getConfig('new_tuition_full_amount'),
|
||||
'new_tuition_youth_amount' => $this->configurationModel->getConfig('new_tuition_youth_amount'),
|
||||
'new_tuition_second_student_discount' => $this->configurationModel->getConfig('new_tuition_second_student_discount'),
|
||||
'new_tuition_third_student_discount' => $this->configurationModel->getConfig('new_tuition_third_student_discount'),
|
||||
'new_tuition_fourth_plus_discount' => $this->configurationModel->getConfig('new_tuition_fourth_plus_discount'),
|
||||
];
|
||||
}
|
||||
|
||||
protected function isWithinRefundWindow(string $refundDeadline): bool
|
||||
{
|
||||
if ($refundDeadline === '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
$timeZone = new \DateTimeZone((string) (config('School')->attendance['timezone'] ?? user_timezone()));
|
||||
$today = new \DateTimeImmutable('today', $timeZone);
|
||||
$deadline = new \DateTimeImmutable($refundDeadline, $timeZone);
|
||||
|
||||
return $today <= $deadline;
|
||||
} catch (\Throwable $e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
protected function toCents($amount): int
|
||||
{
|
||||
return (int) round(((float) $amount) * 100);
|
||||
}
|
||||
|
||||
protected function fromCents(int $cents): string
|
||||
{
|
||||
return number_format($cents / 100, 2, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Libraries\Tuition;
|
||||
|
||||
final class GradeLevelParser
|
||||
{
|
||||
public static function parse($grade, int $gradeFee = 9): int
|
||||
{
|
||||
if (is_numeric($grade)) {
|
||||
return (int) $grade;
|
||||
}
|
||||
|
||||
if (!is_string($grade)) {
|
||||
return 999;
|
||||
}
|
||||
|
||||
$value = strtoupper(trim($grade));
|
||||
$value = preg_replace('/\s+/', ' ', $value) ?? $value;
|
||||
$value = str_replace(['.', '_', '-'], ['', '', ' '], $value);
|
||||
|
||||
if (in_array($value, ['K', 'KG', 'K G', 'KINDER', 'KINDERGARTEN'], true)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (in_array($value, ['PK', 'P K', 'PREK', 'PRE K', 'PRE KINDER', 'PREKINDER'], true)) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (preg_match('/^Y(?:OUTH)?\s*(\d+)?$/', $value, $matches)) {
|
||||
$offset = isset($matches[1]) && $matches[1] !== '' ? max(1, (int) $matches[1]) : 1;
|
||||
return $gradeFee + $offset;
|
||||
}
|
||||
|
||||
if (preg_match('/^(?:GR?ADE\s*)?(\d{1,2})\s*([A-Z]*)$/', $value, $matches)) {
|
||||
return (int) $matches[1];
|
||||
}
|
||||
|
||||
return 999;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Libraries\Tuition;
|
||||
|
||||
use App\Interfaces\TuitionCalculatorInterface;
|
||||
|
||||
final class NewTuitionCalculatorService implements TuitionCalculatorInterface
|
||||
{
|
||||
public function calculateFamilyTuition(array $students, array $config): array
|
||||
{
|
||||
$gradeFee = (int) ($config['grade_fee'] ?? 9);
|
||||
$fullAmountCents = $this->toCents($config['new_tuition_full_amount'] ?? 370);
|
||||
$youthAmountCents = $this->toCents($config['new_tuition_youth_amount'] ?? $config['youth_fee'] ?? 200);
|
||||
$secondDiscountCents = $this->toCents($config['new_tuition_second_student_discount'] ?? 50);
|
||||
$thirdDiscountCents = $this->toCents($config['new_tuition_third_student_discount'] ?? 50);
|
||||
$fourthPlusDiscountCents = $this->toCents($config['new_tuition_fourth_plus_discount'] ?? 100);
|
||||
|
||||
usort($students, function (array $left, array $right) use ($gradeFee): int {
|
||||
$leftLevel = GradeLevelParser::parse($left['grade_level'] ?? null, $gradeFee);
|
||||
$rightLevel = GradeLevelParser::parse($right['grade_level'] ?? null, $gradeFee);
|
||||
|
||||
return [$leftLevel, (int) ($left['student_id'] ?? 0)] <=> [$rightLevel, (int) ($right['student_id'] ?? 0)];
|
||||
});
|
||||
|
||||
$details = [];
|
||||
$regularPosition = 0;
|
||||
|
||||
foreach (array_values($students) as $student) {
|
||||
$level = GradeLevelParser::parse($student['grade_level'] ?? null, $gradeFee);
|
||||
|
||||
if ($level > $gradeFee) {
|
||||
$position = null;
|
||||
$discountCents = 0;
|
||||
$rule = 'new_youth_unit_price';
|
||||
$baseAmountCents = $youthAmountCents;
|
||||
} else {
|
||||
$regularPosition++;
|
||||
$position = $regularPosition;
|
||||
|
||||
if ($position === 1) {
|
||||
$discountCents = 0;
|
||||
$rule = 'new_first_student_full_amount';
|
||||
} elseif ($position === 2) {
|
||||
$discountCents = $secondDiscountCents;
|
||||
$rule = 'new_second_student_discount';
|
||||
} elseif ($position === 3) {
|
||||
$discountCents = $thirdDiscountCents;
|
||||
$rule = 'new_third_student_discount';
|
||||
} else {
|
||||
$discountCents = $fourthPlusDiscountCents;
|
||||
$rule = 'new_fourth_plus_student_discount';
|
||||
}
|
||||
|
||||
$baseAmountCents = $fullAmountCents;
|
||||
}
|
||||
|
||||
$amountCents = max(0, $baseAmountCents - $discountCents);
|
||||
|
||||
$details[] = [
|
||||
'student_id' => (int) ($student['student_id'] ?? 0),
|
||||
'student_name' => (string) ($student['student_name'] ?? ''),
|
||||
'grade_level' => $student['grade_level'] ?? null,
|
||||
'family_position' => $position,
|
||||
'full_amount' => $this->fromCents($baseAmountCents),
|
||||
'discount' => $this->fromCents($discountCents),
|
||||
'rule' => $rule,
|
||||
'amount' => $this->fromCents($amountCents),
|
||||
];
|
||||
}
|
||||
|
||||
$total = array_sum(array_map(fn (array $detail): int => $this->toCents($detail['amount']), $details));
|
||||
|
||||
return [
|
||||
'calculator' => 'new',
|
||||
'total' => $this->fromCents($total),
|
||||
'details' => $details,
|
||||
];
|
||||
}
|
||||
|
||||
private function toCents($amount): int
|
||||
{
|
||||
return (int) round(((float) $amount) * 100);
|
||||
}
|
||||
|
||||
private function fromCents(int $cents): string
|
||||
{
|
||||
return number_format($cents / 100, 2, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Libraries\Tuition;
|
||||
|
||||
use App\Interfaces\TuitionCalculatorInterface;
|
||||
|
||||
final class OldTuitionCalculatorService implements TuitionCalculatorInterface
|
||||
{
|
||||
public function calculateFamilyTuition(array $students, array $config): array
|
||||
{
|
||||
$gradeFee = (int) ($config['grade_fee'] ?? 9);
|
||||
$firstStudentFee = $this->toCents($config['first_student_fee'] ?? 370);
|
||||
$secondStudentFee = $this->toCents($config['second_student_fee'] ?? 200);
|
||||
$youthFee = $this->toCents($config['youth_fee'] ?? 200);
|
||||
|
||||
usort($students, function (array $left, array $right) use ($gradeFee): int {
|
||||
$leftLevel = GradeLevelParser::parse($left['grade_level'] ?? null, $gradeFee);
|
||||
$rightLevel = GradeLevelParser::parse($right['grade_level'] ?? null, $gradeFee);
|
||||
|
||||
return [$leftLevel, (int) ($left['student_id'] ?? 0)] <=> [$rightLevel, (int) ($right['student_id'] ?? 0)];
|
||||
});
|
||||
|
||||
$regularCount = 0;
|
||||
$details = [];
|
||||
|
||||
foreach ($students as $student) {
|
||||
$level = GradeLevelParser::parse($student['grade_level'] ?? null, $gradeFee);
|
||||
|
||||
if ($level > $gradeFee) {
|
||||
$amountCents = $youthFee;
|
||||
$rule = 'old_youth_fee';
|
||||
} else {
|
||||
$regularCount++;
|
||||
$amountCents = $regularCount === 1 ? $firstStudentFee : $secondStudentFee;
|
||||
$rule = $regularCount === 1 ? 'old_first_student_fee' : 'old_second_student_fee';
|
||||
}
|
||||
|
||||
$details[] = [
|
||||
'student_id' => (int) ($student['student_id'] ?? 0),
|
||||
'student_name' => (string) ($student['student_name'] ?? ''),
|
||||
'grade_level' => $student['grade_level'] ?? null,
|
||||
'rule' => $rule,
|
||||
'amount' => $this->fromCents($amountCents),
|
||||
];
|
||||
}
|
||||
|
||||
$total = array_sum(array_map(fn (array $detail): int => $this->toCents($detail['amount']), $details));
|
||||
|
||||
return [
|
||||
'calculator' => 'old',
|
||||
'total' => $this->fromCents($total),
|
||||
'details' => $details,
|
||||
];
|
||||
}
|
||||
|
||||
private function toCents($amount): int
|
||||
{
|
||||
return (int) round(((float) $amount) * 100);
|
||||
}
|
||||
|
||||
private function fromCents(int $cents): string
|
||||
{
|
||||
return number_format($cents / 100, 2, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,663 @@
|
||||
<?php
|
||||
|
||||
namespace App\Libraries\Tuition;
|
||||
|
||||
use App\Libraries\FinancialStatus;
|
||||
use App\Models\ClassSectionModel;
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\EnrollmentModel;
|
||||
use App\Models\PaymentModel;
|
||||
use App\Models\RefundModel;
|
||||
use App\Models\StudentClassModel;
|
||||
use App\Models\UserModel;
|
||||
|
||||
class TuitionForecastService
|
||||
{
|
||||
protected ConfigurationModel $configurationModel;
|
||||
protected EnrollmentModel $enrollmentModel;
|
||||
protected StudentClassModel $studentClassModel;
|
||||
protected ClassSectionModel $classSectionModel;
|
||||
protected PaymentModel $paymentModel;
|
||||
protected RefundModel $refundModel;
|
||||
protected UserModel $userModel;
|
||||
protected OldTuitionCalculatorService $oldCalculator;
|
||||
protected NewTuitionCalculatorService $newCalculator;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->configurationModel = new ConfigurationModel();
|
||||
$this->enrollmentModel = new EnrollmentModel();
|
||||
$this->studentClassModel = new StudentClassModel();
|
||||
$this->classSectionModel = new ClassSectionModel();
|
||||
$this->paymentModel = new PaymentModel();
|
||||
$this->refundModel = new RefundModel();
|
||||
$this->userModel = new UserModel();
|
||||
$this->oldCalculator = new OldTuitionCalculatorService();
|
||||
$this->newCalculator = new NewTuitionCalculatorService();
|
||||
}
|
||||
|
||||
public function calculate(string $schoolYear, string $semester, string $mode = 'compare', array $options = []): array
|
||||
{
|
||||
$schoolYear = trim($schoolYear) !== '' ? trim($schoolYear) : $this->getDefaultSchoolYear();
|
||||
$semester = trim($semester) !== '' ? trim($semester) : $this->getDefaultSemester();
|
||||
$mode = $this->normalizeMode($mode);
|
||||
$options = $this->normalizeOptions($options);
|
||||
$this->unitPriceOverride = $options['unit_price'];
|
||||
$this->youthUnitPriceOverride = $options['youth_unit_price'];
|
||||
$tuitionConfig = $this->getTuitionConfig();
|
||||
$familyRows = [];
|
||||
$summary = [
|
||||
'family_count' => 0,
|
||||
'student_count' => 0,
|
||||
'billable_student_count' => 0,
|
||||
'old_projected_tuition' => '0.00',
|
||||
'new_projected_tuition' => '0.00',
|
||||
'old_projected_income' => '0.00',
|
||||
'new_projected_income' => '0.00',
|
||||
'difference' => '0.00',
|
||||
'projected_tuition' => '0.00',
|
||||
'projected_income' => '0.00',
|
||||
'unit_price' => '0.00',
|
||||
'youth_unit_price' => '0.00',
|
||||
];
|
||||
|
||||
$oldProjectedCents = 0;
|
||||
$newProjectedCents = 0;
|
||||
$studentCount = 0;
|
||||
$billableStudentCount = 0;
|
||||
|
||||
foreach ($this->loadFamilies($schoolYear, $semester) as $family) {
|
||||
$parentId = (int) ($family['parent_id'] ?? 0);
|
||||
if ($parentId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$studentContext = $this->loadFamilyStudents($parentId, $schoolYear, $semester, $options);
|
||||
$students = $studentContext['students'];
|
||||
$allStudents = $studentContext['all_students'];
|
||||
$warnings = $studentContext['warnings'];
|
||||
|
||||
if (empty($allStudents)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$oldResult = $this->oldCalculator->calculateFamilyTuition($students, $tuitionConfig);
|
||||
$newResult = $this->newCalculator->calculateFamilyTuition($students, $tuitionConfig);
|
||||
|
||||
$oldTotalCents = $this->toCents($oldResult['total'] ?? 0);
|
||||
$newTotalCents = $this->toCents($newResult['total'] ?? 0);
|
||||
|
||||
$mergedDetails = $this->mergeStudentDetails($allStudents, $oldResult['details'] ?? [], $newResult['details'] ?? []);
|
||||
$studentCount += count($allStudents);
|
||||
$billableStudentCount += count($students);
|
||||
$oldProjectedCents += $oldTotalCents;
|
||||
$newProjectedCents += $newTotalCents;
|
||||
|
||||
$familyRows[] = [
|
||||
'parent_id' => $parentId,
|
||||
'parent_name' => $family['parent_name'] ?? ('Parent #' . $parentId),
|
||||
'student_count' => count($allStudents),
|
||||
'billable_student_count' => count($students),
|
||||
'old_total' => $this->fromCents($oldTotalCents),
|
||||
'new_total' => $this->fromCents($newTotalCents),
|
||||
'difference' => $this->fromCents($newTotalCents - $oldTotalCents),
|
||||
'warnings' => array_values(array_unique($warnings)),
|
||||
'student_details' => $mergedDetails,
|
||||
];
|
||||
}
|
||||
|
||||
usort($familyRows, static fn (array $left, array $right): int => strcmp((string) ($left['parent_name'] ?? ''), (string) ($right['parent_name'] ?? '')));
|
||||
|
||||
$summary['family_count'] = count($familyRows);
|
||||
$summary['student_count'] = $studentCount;
|
||||
$summary['billable_student_count'] = $billableStudentCount;
|
||||
$summary['old_projected_tuition'] = $this->fromCents($oldProjectedCents);
|
||||
$summary['new_projected_tuition'] = $this->fromCents($newProjectedCents);
|
||||
$summary['old_projected_income'] = $summary['old_projected_tuition'];
|
||||
$summary['new_projected_income'] = $summary['new_projected_tuition'];
|
||||
$summary['difference'] = $this->fromCents($newProjectedCents - $oldProjectedCents);
|
||||
$summary['projected_tuition'] = $mode === 'old' ? $summary['old_projected_tuition'] : $summary['new_projected_tuition'];
|
||||
$summary['projected_income'] = $mode === 'old' ? $summary['old_projected_income'] : $summary['new_projected_income'];
|
||||
$summary['unit_price'] = number_format((float) ($tuitionConfig['new_tuition_full_amount'] ?? 0), 2, '.', '');
|
||||
$summary['youth_unit_price'] = number_format((float) ($tuitionConfig['new_tuition_youth_amount'] ?? 0), 2, '.', '');
|
||||
|
||||
return [
|
||||
'school_year' => $schoolYear,
|
||||
'semester' => $semester,
|
||||
'calculator_mode' => $mode,
|
||||
'options' => $options,
|
||||
'summary' => $summary,
|
||||
'families' => $familyRows,
|
||||
];
|
||||
}
|
||||
|
||||
public function getAvailableSchoolYears(): array
|
||||
{
|
||||
$values = [];
|
||||
|
||||
if ($this->enrollmentModel->db->tableExists('enrollments')) {
|
||||
$rows = $this->enrollmentModel->db->table('enrollments')
|
||||
->select('school_year')
|
||||
->where('school_year IS NOT NULL', null, false)
|
||||
->where('school_year !=', '')
|
||||
->groupBy('school_year')
|
||||
->orderBy('school_year', 'DESC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$value = trim((string) ($row['school_year'] ?? ''));
|
||||
if ($value !== '') {
|
||||
$values[$value] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->paymentModel->db->tableExists('invoices')) {
|
||||
$rows = $this->paymentModel->db->table('invoices')
|
||||
->select('school_year')
|
||||
->where('school_year IS NOT NULL', null, false)
|
||||
->where('school_year !=', '')
|
||||
->groupBy('school_year')
|
||||
->orderBy('school_year', 'DESC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$value = trim((string) ($row['school_year'] ?? ''));
|
||||
if ($value !== '') {
|
||||
$values[$value] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($values === []) {
|
||||
$default = $this->getDefaultSchoolYear();
|
||||
if ($default !== '') {
|
||||
$values[$default] = $default;
|
||||
}
|
||||
}
|
||||
|
||||
krsort($values);
|
||||
|
||||
return array_values($values);
|
||||
}
|
||||
|
||||
public function getAvailableSemesters(): array
|
||||
{
|
||||
$values = [];
|
||||
|
||||
if ($this->enrollmentModel->db->tableExists('enrollments')) {
|
||||
$rows = $this->enrollmentModel->db->table('enrollments')
|
||||
->select('semester')
|
||||
->where('semester IS NOT NULL', null, false)
|
||||
->where('semester !=', '')
|
||||
->groupBy('semester')
|
||||
->orderBy('semester', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$value = trim((string) ($row['semester'] ?? ''));
|
||||
if ($value !== '') {
|
||||
$values[$value] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($values === []) {
|
||||
$default = $this->getDefaultSemester();
|
||||
if ($default !== '') {
|
||||
$values[$default] = $default;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($values);
|
||||
}
|
||||
|
||||
protected function normalizeMode(string $mode): string
|
||||
{
|
||||
$value = strtolower(trim($mode));
|
||||
|
||||
return in_array($value, ['old', 'new'], true) ? $value : 'compare';
|
||||
}
|
||||
|
||||
protected function normalizeOptions(array $options): array
|
||||
{
|
||||
$includeWithdrawnMode = strtolower(trim((string) ($options['include_withdrawn_mode'] ?? 'refund_deadline')));
|
||||
if (!in_array($includeWithdrawnMode, ['refund_deadline', 'include', 'exclude'], true)) {
|
||||
$includeWithdrawnMode = 'refund_deadline';
|
||||
}
|
||||
|
||||
return [
|
||||
'include_withdrawn_mode' => $includeWithdrawnMode,
|
||||
'include_payment_pending' => $this->toBool($options['include_payment_pending'] ?? true),
|
||||
'include_event_only' => $this->toBool($options['include_event_only'] ?? false),
|
||||
'include_paid_invoices' => $this->toBool($options['include_paid_invoices'] ?? true),
|
||||
'unit_price' => $this->normalizeMoney($options['unit_price'] ?? null),
|
||||
'youth_unit_price' => $this->normalizeMoney($options['youth_unit_price'] ?? null),
|
||||
];
|
||||
}
|
||||
|
||||
protected function loadFamilies(string $schoolYear, string $semester): array
|
||||
{
|
||||
$builder = $this->enrollmentModel->db->table('enrollments e')
|
||||
->select("e.parent_id, CONCAT(COALESCE(u.lastname, ''), ', ', COALESCE(u.firstname, '')) AS parent_name", false)
|
||||
->join('users u', 'u.id = e.parent_id', 'left')
|
||||
->where('e.school_year', $schoolYear)
|
||||
->groupBy('e.parent_id')
|
||||
->orderBy('parent_name', 'ASC');
|
||||
|
||||
$this->applyEnrollmentSemesterFilter($builder, 'e', $semester);
|
||||
|
||||
return $builder->get()->getResultArray();
|
||||
}
|
||||
|
||||
protected function loadFamilyStudents(int $parentId, string $schoolYear, string $semester, array $options): array
|
||||
{
|
||||
$rows = $this->enrollmentModel->db->table('enrollments e')
|
||||
->select('e.*, s.firstname, s.lastname, s.is_active')
|
||||
->join('students s', 's.id = e.student_id', 'left')
|
||||
->where('e.parent_id', $parentId)
|
||||
->where('e.school_year', $schoolYear)
|
||||
->orderBy('e.updated_at', 'DESC')
|
||||
->orderBy('e.id', 'DESC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$latestByStudent = [];
|
||||
foreach ($rows as $row) {
|
||||
$studentId = (int) ($row['student_id'] ?? 0);
|
||||
if ($studentId <= 0 || isset($latestByStudent[$studentId])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$this->matchesEnrollmentSemester($row, $semester)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$latestByStudent[$studentId] = $row;
|
||||
}
|
||||
|
||||
ksort($latestByStudent);
|
||||
|
||||
$withinRefundWindow = $this->isWithinRefundWindow((string) ($this->configurationModel->getConfig('refund_deadline') ?? ''));
|
||||
$students = [];
|
||||
$allStudents = [];
|
||||
$warnings = [];
|
||||
$eventOnlyCount = 0;
|
||||
$missingClassCount = 0;
|
||||
$inactiveCount = 0;
|
||||
$pendingSkippedCount = 0;
|
||||
|
||||
foreach ($latestByStudent as $row) {
|
||||
$studentId = (int) ($row['student_id'] ?? 0);
|
||||
$studentName = trim(((string) ($row['firstname'] ?? '')) . ' ' . ((string) ($row['lastname'] ?? '')));
|
||||
$studentLabel = $studentName !== '' ? $studentName : ('Student #' . $studentId);
|
||||
|
||||
if ((int) ($row['is_active'] ?? 1) === 0) {
|
||||
$inactiveCount++;
|
||||
$allStudents[] = [
|
||||
'student_id' => $studentId,
|
||||
'student_name' => $studentLabel,
|
||||
'grade_level' => 'N/A',
|
||||
'billable' => false,
|
||||
'excluded_reason' => 'inactive',
|
||||
];
|
||||
continue;
|
||||
}
|
||||
|
||||
$inclusion = $this->resolveEnrollmentInclusion($row, $options, $withinRefundWindow);
|
||||
if (!$inclusion['include']) {
|
||||
if (($inclusion['reason'] ?? '') === 'payment_pending_excluded') {
|
||||
$pendingSkippedCount++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
$classFlags = $this->resolveStudentClassFlags($studentId, $schoolYear);
|
||||
$gradeName = $this->resolveGradeName($studentId, $schoolYear, $row['class_section_id'] ?? null);
|
||||
$studentBase = [
|
||||
'student_id' => $studentId,
|
||||
'student_name' => $studentLabel,
|
||||
'grade_level' => $gradeName,
|
||||
'billable' => false,
|
||||
'excluded_reason' => null,
|
||||
];
|
||||
|
||||
if (!$classFlags['has_any_assignment']) {
|
||||
$missingClassCount++;
|
||||
$studentBase['excluded_reason'] = 'missing_class_assignment';
|
||||
$allStudents[] = $studentBase;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$classFlags['has_non_event_assignment']) {
|
||||
$eventOnlyCount++;
|
||||
$studentBase['excluded_reason'] = 'event_only';
|
||||
$allStudents[] = $studentBase;
|
||||
if ($options['include_event_only']) {
|
||||
$warnings[] = $studentLabel . ' is event-only and excluded from tuition billing.';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($gradeName === 'N/A') {
|
||||
$warnings[] = $studentLabel . ' has no resolved class section grade.';
|
||||
}
|
||||
|
||||
$studentBase['billable'] = true;
|
||||
$allStudents[] = $studentBase;
|
||||
$students[] = [
|
||||
'student_id' => $studentId,
|
||||
'student_name' => $studentLabel,
|
||||
'grade_level' => $gradeName,
|
||||
];
|
||||
}
|
||||
|
||||
if ($eventOnlyCount > 0) {
|
||||
$warnings[] = $eventOnlyCount . ' event-only student(s) excluded from tuition.';
|
||||
}
|
||||
|
||||
if ($missingClassCount > 0) {
|
||||
$warnings[] = $missingClassCount . ' student(s) missing class assignments.';
|
||||
}
|
||||
|
||||
if ($inactiveCount > 0) {
|
||||
$warnings[] = $inactiveCount . ' inactive student(s) skipped.';
|
||||
}
|
||||
|
||||
if ($pendingSkippedCount > 0) {
|
||||
$warnings[] = $pendingSkippedCount . ' payment-pending student(s) skipped by filter.';
|
||||
}
|
||||
|
||||
if ($this->toCents($this->configurationModel->getConfig('new_tuition_full_amount') ?? 0) <= 0) {
|
||||
$warnings[] = 'New tuition full amount is missing or zero.';
|
||||
}
|
||||
|
||||
return [
|
||||
'students' => $students,
|
||||
'all_students' => $allStudents,
|
||||
'warnings' => array_values(array_unique($warnings)),
|
||||
];
|
||||
}
|
||||
|
||||
protected function resolveEnrollmentInclusion(array $row, array $options, bool $withinRefundWindow): array
|
||||
{
|
||||
$admissionStatus = strtolower(trim((string) ($row['admission_status'] ?? '')));
|
||||
$enrollmentStatus = strtolower(trim((string) ($row['enrollment_status'] ?? '')));
|
||||
|
||||
if ($admissionStatus === 'denied' || $enrollmentStatus === 'admission under review') {
|
||||
return ['include' => false, 'reason' => 'not_admitted'];
|
||||
}
|
||||
|
||||
if ($enrollmentStatus === 'payment pending') {
|
||||
return ['include' => $options['include_payment_pending'], 'reason' => 'payment_pending_excluded'];
|
||||
}
|
||||
|
||||
if ($enrollmentStatus === 'enrolled') {
|
||||
return ['include' => true, 'reason' => null];
|
||||
}
|
||||
|
||||
if (in_array($enrollmentStatus, ['withdrawn', 'refund pending', 'withdraw under review'], true)) {
|
||||
if ($options['include_withdrawn_mode'] === 'include') {
|
||||
return ['include' => true, 'reason' => null];
|
||||
}
|
||||
|
||||
if ($options['include_withdrawn_mode'] === 'exclude') {
|
||||
return ['include' => false, 'reason' => 'withdrawn_excluded'];
|
||||
}
|
||||
|
||||
return ['include' => !$withinRefundWindow, 'reason' => 'refund_deadline_excluded'];
|
||||
}
|
||||
|
||||
return ['include' => $admissionStatus === 'accepted', 'reason' => 'accepted_only'];
|
||||
}
|
||||
|
||||
protected function resolveStudentClassFlags(int $studentId, string $schoolYear): array
|
||||
{
|
||||
$rows = $this->studentClassModel->where('student_id', $studentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
|
||||
$hasAnyAssignment = !empty($rows);
|
||||
$hasNonEventAssignment = false;
|
||||
$hasEventOnlyAssignment = false;
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$isEventOnly = (int) ($row['is_event_only'] ?? 0) === 1;
|
||||
$hasEventOnlyAssignment = $hasEventOnlyAssignment || $isEventOnly;
|
||||
$hasNonEventAssignment = $hasNonEventAssignment || !$isEventOnly;
|
||||
}
|
||||
|
||||
return [
|
||||
'has_any_assignment' => $hasAnyAssignment,
|
||||
'has_non_event_assignment' => $hasNonEventAssignment,
|
||||
'has_event_only_assignment' => $hasEventOnlyAssignment,
|
||||
];
|
||||
}
|
||||
|
||||
protected function resolveGradeName(int $studentId, string $schoolYear, $classSectionId = null): string
|
||||
{
|
||||
$sectionId = $classSectionId;
|
||||
|
||||
if (empty($sectionId)) {
|
||||
$row = $this->studentClassModel
|
||||
->select('class_section_id')
|
||||
->where('student_id', $studentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->where('is_event_only', 0)
|
||||
->orderBy('updated_at', 'DESC')
|
||||
->first();
|
||||
$sectionId = $row['class_section_id'] ?? null;
|
||||
}
|
||||
|
||||
if (empty($sectionId)) {
|
||||
return 'N/A';
|
||||
}
|
||||
|
||||
$name = $this->classSectionModel->getClassSectionNameBySectionId($sectionId);
|
||||
|
||||
return is_string($name) && trim($name) !== '' ? strtoupper(trim($name)) : 'N/A';
|
||||
}
|
||||
|
||||
protected function calculateAlreadyCollected(int $parentId, string $schoolYear, string $semester): int
|
||||
{
|
||||
$paymentBuilder = $this->paymentModel->db->table('payments')
|
||||
->select('COALESCE(SUM(paid_amount),0) AS total_amount')
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $schoolYear);
|
||||
|
||||
if ($semester !== '') {
|
||||
$paymentBuilder->where('semester', $semester);
|
||||
}
|
||||
|
||||
if ($this->paymentModel->db->fieldExists('status', 'payments')) {
|
||||
$paymentBuilder->groupStart()
|
||||
->whereNotIn('status', FinancialStatus::EXCLUDED_PAYMENT_STATUSES)
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
if ($this->paymentModel->db->fieldExists('is_void', 'payments')) {
|
||||
$paymentBuilder->groupStart()
|
||||
->where('is_void', 0)
|
||||
->orWhere('is_void IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
$paymentRow = $paymentBuilder->get()->getRowArray();
|
||||
$paidCents = $this->toCents($paymentRow['total_amount'] ?? 0);
|
||||
|
||||
$refundBuilder = $this->refundModel->db->table('refunds')
|
||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_amount')
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->whereIn('status', FinancialStatus::REFUND_REDUCES_INVOICE_STATUSES);
|
||||
|
||||
if ($semester !== '' && $this->refundModel->db->fieldExists('semester', 'refunds')) {
|
||||
$refundBuilder->where('semester', $semester);
|
||||
}
|
||||
|
||||
$refundRow = $refundBuilder->get()->getRowArray();
|
||||
$refundCents = $this->toCents($refundRow['total_amount'] ?? 0);
|
||||
|
||||
return max(0, $paidCents - $refundCents);
|
||||
}
|
||||
|
||||
protected function mergeStudentDetails(array $allStudents, array $oldDetails, array $newDetails): array
|
||||
{
|
||||
$oldMap = [];
|
||||
foreach ($oldDetails as $detail) {
|
||||
$oldMap[(int) ($detail['student_id'] ?? 0)] = $detail;
|
||||
}
|
||||
|
||||
$newMap = [];
|
||||
foreach ($newDetails as $detail) {
|
||||
$newMap[(int) ($detail['student_id'] ?? 0)] = $detail;
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
foreach ($allStudents as $student) {
|
||||
$studentId = (int) ($student['student_id'] ?? 0);
|
||||
$old = $oldMap[$studentId] ?? null;
|
||||
$new = $newMap[$studentId] ?? null;
|
||||
|
||||
$rows[] = [
|
||||
'student_id' => $studentId,
|
||||
'student_name' => $student['student_name'] ?? '',
|
||||
'grade_level' => $student['grade_level'] ?? 'N/A',
|
||||
'billable' => (bool) ($student['billable'] ?? false),
|
||||
'excluded_reason' => $student['excluded_reason'] ?? null,
|
||||
'old_rule' => $old['rule'] ?? null,
|
||||
'old_amount' => $old['amount'] ?? '0.00',
|
||||
'new_rule' => $new['rule'] ?? null,
|
||||
'new_amount' => $new['amount'] ?? '0.00',
|
||||
];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
protected function getTuitionConfig(): array
|
||||
{
|
||||
return [
|
||||
'grade_fee' => $this->configurationModel->getConfig('grade_fee'),
|
||||
'first_student_fee' => $this->configurationModel->getConfig('first_student_fee'),
|
||||
'second_student_fee' => $this->configurationModel->getConfig('second_student_fee'),
|
||||
'youth_fee' => $this->configurationModel->getConfig('youth_fee') ?? '200.00',
|
||||
'new_tuition_full_amount' => $this->normalizedUnitPriceOverride(),
|
||||
'new_tuition_youth_amount' => $this->normalizedYouthUnitPriceOverride(),
|
||||
'new_tuition_second_student_discount' => $this->configurationModel->getConfig('new_tuition_second_student_discount'),
|
||||
'new_tuition_third_student_discount' => $this->configurationModel->getConfig('new_tuition_third_student_discount'),
|
||||
'new_tuition_fourth_plus_discount' => $this->configurationModel->getConfig('new_tuition_fourth_plus_discount'),
|
||||
];
|
||||
}
|
||||
|
||||
protected ?string $unitPriceOverride = null;
|
||||
protected ?string $youthUnitPriceOverride = null;
|
||||
|
||||
protected function normalizedUnitPriceOverride(): string
|
||||
{
|
||||
return $this->unitPriceOverride
|
||||
?? (string) ($this->configurationModel->getConfig('new_tuition_full_amount') ?? '0.00');
|
||||
}
|
||||
|
||||
protected function normalizedYouthUnitPriceOverride(): string
|
||||
{
|
||||
return $this->youthUnitPriceOverride
|
||||
?? (string) (
|
||||
$this->configurationModel->getConfig('new_tuition_youth_amount')
|
||||
?? $this->configurationModel->getConfig('youth_fee')
|
||||
?? '200.00'
|
||||
);
|
||||
}
|
||||
|
||||
protected function normalizeMoney($value): ?string
|
||||
{
|
||||
if ($value === null || trim((string) $value) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$normalized = preg_replace('/[^0-9.]+/', '', (string) $value);
|
||||
if ($normalized === '' || !is_numeric($normalized)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$amount = (float) $normalized;
|
||||
|
||||
return $amount > 0 ? number_format($amount, 2, '.', '') : null;
|
||||
}
|
||||
|
||||
protected function isWithinRefundWindow(string $refundDeadline): bool
|
||||
{
|
||||
if ($refundDeadline === '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
$timeZone = new \DateTimeZone((string) (config('School')->attendance['timezone'] ?? user_timezone()));
|
||||
$today = new \DateTimeImmutable('today', $timeZone);
|
||||
$deadline = new \DateTimeImmutable($refundDeadline, $timeZone);
|
||||
|
||||
return $today <= $deadline;
|
||||
} catch (\Throwable $e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
protected function getDefaultSchoolYear(): string
|
||||
{
|
||||
return (string) ($this->configurationModel->getConfig('school_year') ?? '');
|
||||
}
|
||||
|
||||
protected function getDefaultSemester(): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
protected function applyEnrollmentSemesterFilter($builder, string $alias, string $semester): void
|
||||
{
|
||||
if ($semester === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$builder->groupStart()
|
||||
->where($alias . '.semester', $semester)
|
||||
->orWhere($alias . '.semester', '')
|
||||
->orWhere($alias . '.semester IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
protected function matchesEnrollmentSemester(array $row, string $semester): bool
|
||||
{
|
||||
if ($semester === '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
$value = trim((string) ($row['semester'] ?? ''));
|
||||
|
||||
return $value === '' || strcasecmp($value, $semester) === 0;
|
||||
}
|
||||
|
||||
protected function toBool($value): bool
|
||||
{
|
||||
if (is_bool($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$normalized = strtolower(trim((string) $value));
|
||||
|
||||
return in_array($normalized, ['1', 'true', 'yes', 'on'], true);
|
||||
}
|
||||
|
||||
protected function toCents($amount): int
|
||||
{
|
||||
return (int) round(((float) $amount) * 100);
|
||||
}
|
||||
|
||||
protected function fromCents(int $cents): string
|
||||
{
|
||||
return number_format($cents / 100, 2, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -65,7 +65,6 @@ class DecisionEmailListener
|
||||
'parent_name' => $parentName !== '' ? $parentName : 'Parent/Guardian',
|
||||
'student_name' => $studentName !== '' ? $studentName : 'your student',
|
||||
'class_section_name' => $classSection,
|
||||
'semester' => $semester,
|
||||
'school_year' => $schoolYear,
|
||||
'decision' => $decision,
|
||||
'notes' => $notes,
|
||||
|
||||
@@ -35,7 +35,7 @@ class AdditionalChargeModel extends Model
|
||||
'description' => 'permit_empty|string',
|
||||
'amount' => 'required|decimal',
|
||||
'due_date' => 'permit_empty|valid_date',
|
||||
'status' => 'required|in_list[pending,applied]',
|
||||
'status' => 'required|in_list[pending,applied,voided]',
|
||||
'created_by' => 'permit_empty|integer',
|
||||
];
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ class AttendanceDataModel extends Model
|
||||
'date',
|
||||
'status',
|
||||
'reason',
|
||||
'reported',
|
||||
'is_reported',
|
||||
'is_notified',
|
||||
'semester',
|
||||
|
||||
@@ -7,6 +7,6 @@ class ClassPrepAdjustmentModel extends Model
|
||||
{
|
||||
protected $table = 'class_prep_adjustments';
|
||||
protected $allowedFields = [
|
||||
'class_section_id', 'item_name', 'adjustment', 'school_year', 'created_at'
|
||||
'class_section_id', 'item_name', 'adjustment', 'adjustable', 'created_at'
|
||||
];
|
||||
}
|
||||
@@ -11,7 +11,6 @@ class ClassPreparationLogModel extends Model
|
||||
protected $allowedFields = [
|
||||
'class_section_id',
|
||||
'class_section',
|
||||
'school_year',
|
||||
'prep_data',
|
||||
'created_at',
|
||||
];
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Concerns;
|
||||
|
||||
use App\Support\SchoolYear\SchoolYearContext;
|
||||
use CodeIgniter\Model;
|
||||
|
||||
trait SchoolYearScopedModelTrait
|
||||
{
|
||||
public function forSchoolYear(SchoolYearContext|string|int $schoolYear): Model
|
||||
{
|
||||
if ($schoolYear instanceof SchoolYearContext) {
|
||||
if ($this->fieldExists('school_year_id')) {
|
||||
return $this->where($this->table . '.school_year_id', $schoolYear->id());
|
||||
}
|
||||
|
||||
return $this->where($this->table . '.school_year', $schoolYear->yearName());
|
||||
}
|
||||
|
||||
if (is_int($schoolYear)) {
|
||||
return $this->where($this->table . '.school_year_id', $schoolYear);
|
||||
}
|
||||
|
||||
return $this->where($this->table . '.school_year', $schoolYear);
|
||||
}
|
||||
|
||||
private function fieldExists(string $field): bool
|
||||
{
|
||||
return in_array($field, $this->db->getFieldNames($this->table), true);
|
||||
}
|
||||
}
|
||||
@@ -19,8 +19,6 @@ class ContactUsModel extends Model
|
||||
'reciever_id',
|
||||
'subject',
|
||||
'message',
|
||||
'semester',
|
||||
'school_year',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
];
|
||||
@@ -35,8 +33,6 @@ class ContactUsModel extends Model
|
||||
'reciever_id' => 'required|integer',
|
||||
'subject' => 'required|string|max_length[255]',
|
||||
'message' => 'required|string',
|
||||
'semester' => 'required|string|max_length[255]',
|
||||
'school_year' => 'permit_empty|string|max_length[9]'
|
||||
];
|
||||
|
||||
protected $validationMessages = [];
|
||||
@@ -51,10 +47,7 @@ class ContactUsModel extends Model
|
||||
*/
|
||||
public function getMessagesBySemesterAndYear($semester, $school_year)
|
||||
{
|
||||
return $this->where([
|
||||
'semester' => $semester,
|
||||
'school_year' => $school_year
|
||||
])->findAll();
|
||||
return $this->findAll();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,12 +6,19 @@ use CodeIgniter\Model;
|
||||
class EmailTemplateModel extends Model {
|
||||
protected $table = 'email_templates';
|
||||
protected $primaryKey = 'id';
|
||||
protected $allowedFields = ['template_key','name','subject','body','is_active'];
|
||||
protected $allowedFields = ['code', 'variant', 'subject', 'body_html', 'is_active', 'updated_by', 'updated_at'];
|
||||
|
||||
public function getActiveTemplates(): array {
|
||||
return $this->where('is_active', 1)->orderBy('template_key','asc')->findAll();
|
||||
return $this->select('email_templates.*, code AS template_key, code AS name, body_html AS body')
|
||||
->where('is_active', 1)
|
||||
->orderBy('code', 'asc')
|
||||
->findAll();
|
||||
}
|
||||
|
||||
public function findByKey(string $key): ?array {
|
||||
return $this->where('template_key', $key)->where('is_active', 1)->first();
|
||||
return $this->select('email_templates.*, code AS template_key, code AS name, body_html AS body')
|
||||
->where('code', $key)
|
||||
->where('is_active', 1)
|
||||
->first();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,8 +16,6 @@ class EmergencyContactModel extends Model
|
||||
'cellphone',
|
||||
'email',
|
||||
'relation',
|
||||
'semester',
|
||||
'school_year',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
];
|
||||
|
||||
@@ -86,7 +86,7 @@ class EnrollmentModel extends Model
|
||||
/**
|
||||
* Get all enrolled students (full student info) for a given parent.
|
||||
*/
|
||||
public function getEnrolledStudents(int $parentId, string $schoolYear = null, string $semester = null): array
|
||||
public function getEnrolledStudents(int $parentId, ?string $schoolYear = null, ?string $semester = null): array
|
||||
{
|
||||
$builder = $this->select('students.*')
|
||||
->join('students', 'students.id = enrollments.student_id')
|
||||
@@ -106,7 +106,7 @@ class EnrollmentModel extends Model
|
||||
/**
|
||||
* Get student basic info (ID, name, grade) for a given parent where status is enrolled or Payment pending.
|
||||
*/
|
||||
public function getenrolledStudentDetails(int $parentId, string $schoolYear = null): array
|
||||
public function getenrolledStudentDetails(int $parentId, ?string $schoolYear = null): array
|
||||
{
|
||||
$builder = $this->db->table('enrollments')
|
||||
->select('students.id, students.firstname, students.lastname, students.grade_level')
|
||||
|
||||
@@ -28,7 +28,6 @@ class EventChargesModel extends Model
|
||||
'external_parent_email',
|
||||
'semester',
|
||||
'school_year',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
|
||||
@@ -32,7 +32,6 @@ class ExamDraftModel extends Model
|
||||
];
|
||||
|
||||
protected $allowedFields = [
|
||||
'teacher_id',
|
||||
'author_id',
|
||||
'class_section_id',
|
||||
'semester',
|
||||
@@ -40,20 +39,14 @@ class ExamDraftModel extends Model
|
||||
'exam_type',
|
||||
'draft_title',
|
||||
'author_comment',
|
||||
'description',
|
||||
'teacher_file',
|
||||
'teacher_filename',
|
||||
'author_file',
|
||||
'author_filename',
|
||||
'status',
|
||||
'acceptance_type',
|
||||
'review_revision',
|
||||
'reviewer_id',
|
||||
'admin_id',
|
||||
'is_legacy',
|
||||
'reviewer_comment',
|
||||
'reviewer_comments',
|
||||
'admin_comments',
|
||||
'reviewed_at',
|
||||
'final_file',
|
||||
'final_filename',
|
||||
@@ -87,11 +80,9 @@ class ExamDraftModel extends Model
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected array $casts = [
|
||||
'teacher_id' => 'int',
|
||||
'author_id' => 'int',
|
||||
'class_section_id' => 'int',
|
||||
'reviewer_id' => '?int',
|
||||
'admin_id' => '?int',
|
||||
'review_revision' => 'int',
|
||||
'version' => 'int',
|
||||
'previous_draft_id' => '?int',
|
||||
|
||||
@@ -12,9 +12,10 @@ class ExamModel extends Model
|
||||
|
||||
protected $allowedFields = [
|
||||
'student_id',
|
||||
'school_id',
|
||||
'student_school_id',
|
||||
'class_section_id',
|
||||
'exam_name',
|
||||
'school_year',
|
||||
'created_at'
|
||||
];
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ class FinalExamModel extends Model
|
||||
'class_section_id',
|
||||
'updated_by',
|
||||
'score',
|
||||
'comment',
|
||||
'semester',
|
||||
'school_year',
|
||||
'created_at',
|
||||
|
||||
@@ -14,7 +14,7 @@ class FinalScoreModel extends Model
|
||||
'student_id',
|
||||
'school_id',
|
||||
'class_section_id',
|
||||
'teacher_id',
|
||||
'updated_by',
|
||||
'score',
|
||||
'score_letter',
|
||||
'comment',
|
||||
|
||||
@@ -30,10 +30,6 @@ protected $table = 'inventory_items';
|
||||
'sku',
|
||||
'notes',
|
||||
|
||||
// academic tags
|
||||
'semester',
|
||||
'school_year',
|
||||
|
||||
// audit
|
||||
'updated_by',
|
||||
|
||||
@@ -50,7 +46,5 @@ protected $table = 'inventory_items';
|
||||
'name' => 'required|min_length[2]',
|
||||
'quantity' => 'permit_empty|integer',
|
||||
'unit_price' => 'permit_empty|decimal',
|
||||
'semester' => 'permit_empty|in_list[Spring,Fall]',
|
||||
'school_year' => 'permit_empty|max_length[16]', // e.g. 2025-2026
|
||||
];
|
||||
}
|
||||
|
||||
@@ -20,8 +20,6 @@ class InvoiceStudentListModel extends Model
|
||||
'student_lastname',
|
||||
'school_id',
|
||||
'enrolled',
|
||||
'school_year',
|
||||
'semester',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
];
|
||||
|
||||
@@ -13,8 +13,6 @@ class IpAttemptModel extends Model
|
||||
'ip_address',
|
||||
'attempts',
|
||||
'last_attempt_at',
|
||||
'semester',
|
||||
'school_year',
|
||||
'blocked_until'
|
||||
];
|
||||
|
||||
|
||||
@@ -15,7 +15,6 @@ class LoginActivityModel extends Model
|
||||
'logout_time',
|
||||
'ip_address',
|
||||
'user_agent',
|
||||
'school_year',
|
||||
'semester',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
|
||||
@@ -21,8 +21,7 @@ class MessageModel extends Model
|
||||
'priority',
|
||||
'attachment',
|
||||
'status',
|
||||
'semester', // Added field
|
||||
'school_year' // Added field
|
||||
'semester'
|
||||
];
|
||||
|
||||
protected $useTimestamps = false; // Since you're manually handling date fields
|
||||
@@ -150,10 +149,8 @@ class MessageModel extends Model
|
||||
*/
|
||||
public function getMessagesBySemesterAndYear($semester, $school_year = null)
|
||||
{
|
||||
$builder = $this->where('semester', $semester);
|
||||
if ($school_year) {
|
||||
$builder->where('school_year', $school_year);
|
||||
}
|
||||
return $builder->orderBy('sent_datetime', 'DESC')->findAll();
|
||||
return $this->where('semester', $semester)
|
||||
->orderBy('sent_datetime', 'DESC')
|
||||
->findAll();
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,8 @@ class NotificationModel extends Model
|
||||
'status',
|
||||
'action_url',
|
||||
'attachment_path',
|
||||
'semester',
|
||||
'school_year',
|
||||
'expires_at',
|
||||
'sent_at',
|
||||
'scheduled_at'
|
||||
];
|
||||
protected $useTimestamps = true;
|
||||
|
||||
@@ -15,7 +15,5 @@ class ParentModel extends Model
|
||||
'secondparent_email',
|
||||
'secondparent_phone',
|
||||
'firstparent_id',
|
||||
'semester',
|
||||
'school_year',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Model;
|
||||
|
||||
|
||||
class PayPalPaymentModel extends Model
|
||||
{
|
||||
protected $table = 'paypal_payments';
|
||||
protected $primaryKey = 'id';
|
||||
protected $allowedFields = [
|
||||
'webhook_id',
|
||||
'parent_school_id',
|
||||
'order_id',
|
||||
'transaction_id',
|
||||
'status',
|
||||
'amount',
|
||||
'currency',
|
||||
'paypal_fee',
|
||||
'net_amount',
|
||||
'payer_email',
|
||||
'merchant_id',
|
||||
'event_type',
|
||||
'summary',
|
||||
'raw_payload',
|
||||
'synced',
|
||||
'semester',
|
||||
'school_year',
|
||||
'sync_attempts'
|
||||
];
|
||||
|
||||
// Enable timestamps
|
||||
protected $useTimestamps = true;
|
||||
protected $createdField = 'created_at';
|
||||
protected $updatedField = ''; // not used; leave empty if not needed
|
||||
}
|
||||
|
||||
+284
-65
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Database\ConnectionInterface;
|
||||
use CodeIgniter\Model;
|
||||
use CodeIgniter\Validation\ValidationInterface;
|
||||
|
||||
class PaymentModel extends Model
|
||||
{
|
||||
@@ -10,39 +12,68 @@ class PaymentModel extends Model
|
||||
protected $primaryKey = 'id';
|
||||
protected $returnType = 'array';
|
||||
|
||||
/**
|
||||
* Keep this list broad, then filter it in __construct() against the real DB schema.
|
||||
* This prevents CI from trying to insert/update columns that do not exist, such as `balance`.
|
||||
*/
|
||||
protected $allowedFields = [
|
||||
'parent_id',
|
||||
'invoice_id',
|
||||
|
||||
// Legacy invoice snapshot fields. Do not use these as source of truth.
|
||||
'total_amount',
|
||||
|
||||
// Actual payment fields.
|
||||
'paid_amount',
|
||||
'balance',
|
||||
'balance_amount',
|
||||
'balance_after_payment',
|
||||
'number_of_installments',
|
||||
'installment_seq',
|
||||
'transaction_id',
|
||||
'check_file',
|
||||
'check_number',
|
||||
'payment_method',
|
||||
'payment_date',
|
||||
'school_year',
|
||||
'semester',
|
||||
'status',
|
||||
'updated_by'
|
||||
'updated_by',
|
||||
];
|
||||
|
||||
protected $useTimestamps = false;
|
||||
// ❗ Your DB handles created_at / updated_at with default CURRENT_TIMESTAMP
|
||||
// Remove CI4 auto timestamp management unless you modify your DB schema
|
||||
|
||||
/**
|
||||
* Let DB defaults handle created_at / updated_at.
|
||||
* Keep validation strict for actual payment data, but do not require legacy snapshot columns.
|
||||
*/
|
||||
protected $cleanValidationRules = true;
|
||||
|
||||
protected $validationRules = [
|
||||
'parent_id' => 'required|integer',
|
||||
'invoice_id' => 'required|integer',
|
||||
'total_amount' => 'required|decimal',
|
||||
'paid_amount' => 'required|decimal',
|
||||
'balance' => 'required|decimal',
|
||||
'number_of_installments' => 'required|integer',
|
||||
'payment_method' => 'required|max_length[50]', // ✅ Removed 'string'
|
||||
'payment_date' => 'required|valid_date[Y-m-d H:i:s]',
|
||||
'status' => 'required|max_length[50]', // ✅ Removed 'string'
|
||||
|
||||
// Legacy snapshot. Optional because invoice total belongs to invoices table.
|
||||
'total_amount' => 'permit_empty|decimal',
|
||||
|
||||
'paid_amount' => 'required|decimal|greater_than[0]',
|
||||
|
||||
// These are optional because not every live schema has a balance snapshot column.
|
||||
'balance' => 'permit_empty|decimal|greater_than_equal_to[0]',
|
||||
'balance_amount' => 'permit_empty|decimal|greater_than_equal_to[0]',
|
||||
'balance_after_payment' => 'permit_empty|decimal|greater_than_equal_to[0]',
|
||||
|
||||
// Legacy/current sequence columns.
|
||||
'number_of_installments' => 'permit_empty|integer|greater_than[0]',
|
||||
'installment_seq' => 'permit_empty|integer|greater_than[0]',
|
||||
|
||||
'transaction_id' => 'permit_empty|max_length[100]',
|
||||
'payment_method' => 'required|in_list[cash,check,card]',
|
||||
'payment_date' => 'required|valid_date',
|
||||
'school_year' => 'permit_empty|max_length[20]',
|
||||
'status' => 'required|max_length[50]',
|
||||
'check_file' => 'permit_empty|max_length[255]',
|
||||
'check_number' => 'permit_empty|max_length[100]',
|
||||
'updated_by' => 'permit_empty|integer',
|
||||
];
|
||||
|
||||
protected $validationMessages = [
|
||||
@@ -55,111 +86,225 @@ class PaymentModel extends Model
|
||||
'integer' => 'Invoice ID must be an integer.',
|
||||
],
|
||||
'total_amount' => [
|
||||
'required' => 'Total amount is required.',
|
||||
'decimal' => 'Total amount must be a valid decimal.',
|
||||
],
|
||||
'paid_amount' => [
|
||||
'required' => 'Paid amount is required.',
|
||||
'decimal' => 'Paid amount must be a valid decimal.',
|
||||
'greater_than' => 'Paid amount must be greater than zero.',
|
||||
],
|
||||
'balance' => [
|
||||
'required' => 'Balance is required.',
|
||||
'decimal' => 'Balance must be a valid decimal.',
|
||||
'greater_than_equal_to' => 'Balance must not be negative.',
|
||||
],
|
||||
'balance_amount' => [
|
||||
'decimal' => 'Balance amount must be a valid decimal.',
|
||||
'greater_than_equal_to' => 'Balance amount must not be negative.',
|
||||
],
|
||||
'balance_after_payment' => [
|
||||
'decimal' => 'Balance after payment must be a valid decimal.',
|
||||
'greater_than_equal_to' => 'Balance after payment must not be negative.',
|
||||
],
|
||||
'payment_date' => [
|
||||
'required' => 'Payment date is required.',
|
||||
'valid_date' => 'Payment date must be a valid date (Y-m-d H:i:s).',
|
||||
'valid_date' => 'Payment date must be a valid date.',
|
||||
],
|
||||
'payment_method' => [
|
||||
'required' => 'Payment method is required.',
|
||||
'max_length' => 'Payment method must not exceed 50 characters.',
|
||||
'in_list' => 'Payment method must be cash, check, or card.',
|
||||
],
|
||||
'status' => [
|
||||
'required' => 'Status is required.',
|
||||
'max_length' => 'Status must not exceed 50 characters.',
|
||||
],
|
||||
'number_of_installments' => [
|
||||
'required' => 'Number of installments is required.',
|
||||
'integer' => 'Number of installments must be an integer.',
|
||||
'greater_than' => 'Number of installments must be greater than zero.',
|
||||
],
|
||||
'installment_seq' => [
|
||||
'integer' => 'Installment sequence must be an integer.',
|
||||
'greater_than' => 'Installment sequence must be greater than zero.',
|
||||
],
|
||||
'check_number' => [
|
||||
'max_length' => 'Check number must not exceed 100 characters.',
|
||||
]
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Get payments by parent ID.
|
||||
*
|
||||
* @param int $parentId
|
||||
* @return array
|
||||
*/
|
||||
public function getPaymentsByParentId(int $parentId): array
|
||||
private array $paymentColumns = [];
|
||||
|
||||
private array $excludedPaymentStatuses = [
|
||||
'void',
|
||||
'voided',
|
||||
'refunded',
|
||||
'failed',
|
||||
'chargeback',
|
||||
'declined',
|
||||
'reversed',
|
||||
'canceled',
|
||||
'cancelled',
|
||||
];
|
||||
|
||||
public function __construct(?ConnectionInterface $db = null, ?ValidationInterface $validation = null)
|
||||
{
|
||||
return $this->where('parent_id', $parentId)
|
||||
->orderBy('payment_date', 'DESC')
|
||||
->findAll();
|
||||
parent::__construct($db, $validation);
|
||||
|
||||
$this->paymentColumns = $this->getTableColumns($this->table);
|
||||
|
||||
// Remove fields that do not exist in the live DB.
|
||||
// This prevents errors like "Unknown column balance".
|
||||
$this->allowedFields = array_values(array_filter(
|
||||
$this->allowedFields,
|
||||
fn (string $field): bool => in_array($field, $this->paymentColumns, true)
|
||||
));
|
||||
|
||||
// Remove validation rules for columns that do not exist.
|
||||
foreach (array_keys($this->validationRules) as $field) {
|
||||
if (!in_array($field, $this->allowedFields, true)) {
|
||||
unset($this->validationRules[$field]);
|
||||
unset($this->validationMessages[$field]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the total paid amount for a specific parent.
|
||||
* Get payments by parent ID with invoice context.
|
||||
*
|
||||
* @param int $parentId
|
||||
* @return float
|
||||
* The source of truth for invoice total/status/balance is invoices, not payments.
|
||||
*/
|
||||
public function getPaymentsByParentId(int $parentId, ?string $schoolYear = null): array
|
||||
{
|
||||
return $this->parentPaymentHistoryQuery($parentId, $schoolYear)->findAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build parent payment history query with invoice context.
|
||||
*
|
||||
* Kept public so controllers can paginate without duplicating select/join logic.
|
||||
*/
|
||||
public function parentPaymentHistoryQuery(int $parentId, ?string $schoolYear = null): self
|
||||
{
|
||||
$paymentBalanceSelect = $this->getPaymentBalanceSelectExpression('payments');
|
||||
|
||||
$invoiceBalanceSelect = $this->columnExists('invoices', 'balance')
|
||||
? 'invoices.balance AS invoice_current_balance'
|
||||
: '0.00 AS invoice_current_balance';
|
||||
|
||||
$select = [
|
||||
'payments.id',
|
||||
'payments.invoice_id',
|
||||
'invoices.invoice_number',
|
||||
'payments.transaction_id',
|
||||
'payments.paid_amount',
|
||||
'payments.payment_method',
|
||||
'payments.check_number',
|
||||
'payments.check_file',
|
||||
'payments.payment_date',
|
||||
'payments.installment_seq',
|
||||
'payments.number_of_installments',
|
||||
$paymentBalanceSelect,
|
||||
'payments.status AS payment_status',
|
||||
'invoices.total_amount AS invoice_total',
|
||||
$invoiceBalanceSelect,
|
||||
'invoices.status AS invoice_status',
|
||||
'invoices.school_year',
|
||||
];
|
||||
|
||||
$model = new self($this->db);
|
||||
$builder = $model->select(implode(', ', $select), false)
|
||||
->join('invoices', 'invoices.id = payments.invoice_id', 'inner')
|
||||
->where('payments.parent_id', $parentId);
|
||||
|
||||
if ($schoolYear !== null && $schoolYear !== '') {
|
||||
$builder->where('invoices.school_year', $schoolYear);
|
||||
}
|
||||
|
||||
return $builder
|
||||
->orderBy('payments.payment_date', 'DESC')
|
||||
->orderBy('payments.id', 'DESC');
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the total paid amount for a parent in a school year.
|
||||
*
|
||||
* Uses invoices.school_year so old poisoned payment term data does not corrupt totals.
|
||||
*/
|
||||
public function getTotalPaidByParentId(int $parentId, string $schoolYear): float
|
||||
{
|
||||
$db = \Config\Database::connect();
|
||||
|
||||
$result = $db->table('payments')
|
||||
->selectSum('paid_amount', 'total_paid')
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $schoolYear)
|
||||
$result = $this->db->table('payments p')
|
||||
->selectSum('p.paid_amount', 'total_paid')
|
||||
->join('invoices i', 'i.id = p.invoice_id', 'inner')
|
||||
->where('p.parent_id', $parentId)
|
||||
->where('i.school_year', $schoolYear)
|
||||
->where($this->successfulPaymentWhereSql('p.status'), null, false)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
return $result && isset($result['total_paid']) ? (float) $result['total_paid'] : 0.00;
|
||||
return $result && isset($result['total_paid'])
|
||||
? (float) $result['total_paid']
|
||||
: 0.00;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update balance for a specific payment.
|
||||
* Legacy method.
|
||||
*
|
||||
* @param int $paymentId
|
||||
* @param float $amountPaid
|
||||
* @return bool
|
||||
* This should not be used for new payment recording.
|
||||
* New payments should be inserted as immutable payment rows and invoices recalculated by InvoiceLedgerService.
|
||||
*/
|
||||
public function updateBalance(int $paymentId, float $amountPaid): bool
|
||||
{
|
||||
if ($amountPaid <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$payment = $this->find($paymentId);
|
||||
if (!$payment) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$newBalance = $payment['balance'] - $amountPaid;
|
||||
$updateData = [
|
||||
'paid_amount' => round((float) ($payment['paid_amount'] ?? 0) + $amountPaid, 2),
|
||||
];
|
||||
|
||||
return $this->update($paymentId, [
|
||||
'paid_amount' => $payment['paid_amount'] + $amountPaid,
|
||||
'balance' => $newBalance
|
||||
]);
|
||||
$balanceField = $this->getPaymentBalanceField();
|
||||
if ($balanceField !== null && array_key_exists($balanceField, $payment)) {
|
||||
$updateData[$balanceField] = max(
|
||||
0.00,
|
||||
round((float) ($payment[$balanceField] ?? 0) - $amountPaid, 2)
|
||||
);
|
||||
}
|
||||
|
||||
return $this->update($paymentId, $updateData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get payments by school year.
|
||||
*
|
||||
* @param string $schoolYear
|
||||
* @return array
|
||||
* Uses invoice school year when possible because payment.school_year may have old bad data.
|
||||
*/
|
||||
public function getPaymentsByYear(string $schoolYear): array
|
||||
{
|
||||
return $this->where('school_year', $schoolYear)
|
||||
->orderBy('payment_date', 'DESC')
|
||||
$paymentBalanceSelect = $this->getPaymentBalanceSelectExpression('payments');
|
||||
|
||||
$select = [
|
||||
'payments.*',
|
||||
'invoices.invoice_number',
|
||||
'invoices.total_amount AS invoice_total',
|
||||
'invoices.status AS invoice_status',
|
||||
$paymentBalanceSelect,
|
||||
];
|
||||
|
||||
return $this->select(implode(', ', $select), false)
|
||||
->join('invoices', 'invoices.id = payments.invoice_id', 'inner')
|
||||
->where('invoices.school_year', $schoolYear)
|
||||
->orderBy('payments.payment_date', 'DESC')
|
||||
->orderBy('payments.id', 'DESC')
|
||||
->findAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new transaction ID.
|
||||
* Generate a transaction ID.
|
||||
*
|
||||
* @return string
|
||||
* This is okay for legacy/manual use, but a DB UNIQUE KEY on transaction_id is still required.
|
||||
*/
|
||||
public function generateNewTransactionId(): string
|
||||
{
|
||||
@@ -171,41 +316,115 @@ class PaymentModel extends Model
|
||||
->first();
|
||||
|
||||
if ($latest && isset($latest['transaction_id'])) {
|
||||
$lastNumber = (int) str_replace($prefix, '', $latest['transaction_id']);
|
||||
$lastNumber = (int) str_replace($prefix, '', (string) $latest['transaction_id']);
|
||||
$newNumber = $lastNumber + 1;
|
||||
} else {
|
||||
$newNumber = 1;
|
||||
}
|
||||
|
||||
return $prefix . str_pad($newNumber, 6, '0', STR_PAD_LEFT);
|
||||
return $prefix . str_pad((string) $newNumber, 6, '0', STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get latest successful payment per invoice.
|
||||
*
|
||||
* Uses latest payment ID instead of latest date only.
|
||||
* Date-only matching can return duplicates when several payments happen on the same day.
|
||||
*/
|
||||
public function getPaymentsByInvoice($invoiceIds): array
|
||||
{
|
||||
// Normalize input
|
||||
if (!is_array($invoiceIds)) {
|
||||
$invoiceIds = [$invoiceIds];
|
||||
}
|
||||
|
||||
$invoiceIds = array_values(array_filter(array_map('intval', $invoiceIds)));
|
||||
|
||||
if (empty($invoiceIds)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Subquery: latest payment_date per invoice (Full/Partial only)
|
||||
$latestSub = $this->db->table('payments')
|
||||
->select('invoice_id, MAX(payment_date) AS max_date')
|
||||
->whereIn('status', ['Full', 'Paid', 'Partially Paid'])
|
||||
->select('invoice_id, MAX(id) AS max_id')
|
||||
->whereIn('invoice_id', $invoiceIds)
|
||||
->where('paid_amount >', 0)
|
||||
->where($this->successfulPaymentWhereSql('status'), null, false)
|
||||
->groupBy('invoice_id')
|
||||
->getCompiledSelect();
|
||||
|
||||
// Main query: join payments to the latest per invoice
|
||||
$rows = $this->db->table('payments p')
|
||||
->select('p.invoice_id, p.paid_amount AS last_paid_amount, p.payment_date AS last_payment_date, p.status AS last_payment_status')
|
||||
->join("($latestSub) latest", 'latest.invoice_id = p.invoice_id AND latest.max_date = p.payment_date', 'inner', false) // <-- escape=false
|
||||
return $this->db->table('payments p')
|
||||
->select([
|
||||
'p.invoice_id',
|
||||
'p.id AS payment_id',
|
||||
'p.paid_amount AS last_paid_amount',
|
||||
'p.payment_date AS last_payment_date',
|
||||
'p.status AS last_payment_status',
|
||||
'p.transaction_id',
|
||||
'p.payment_method',
|
||||
'p.check_number',
|
||||
])
|
||||
->join(
|
||||
"($latestSub) latest",
|
||||
'latest.invoice_id = p.invoice_id AND latest.max_id = p.id',
|
||||
'inner',
|
||||
false
|
||||
)
|
||||
->whereIn('p.invoice_id', $invoiceIds)
|
||||
->whereIn('p.status', ['Full', 'Paid', 'Partially Paid'])
|
||||
->get()
|
||||
->getResultArray();
|
||||
}
|
||||
|
||||
return $rows;
|
||||
private function getPaymentBalanceField(): ?string
|
||||
{
|
||||
foreach (['balance_after_payment', 'balance', 'balance_amount'] as $field) {
|
||||
if (in_array($field, $this->paymentColumns, true)) {
|
||||
return $field;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function getPaymentBalanceSelectExpression(string $alias = 'payments'): string
|
||||
{
|
||||
$field = $this->getPaymentBalanceField();
|
||||
|
||||
if ($field === null) {
|
||||
return '0.00 AS balance_after_payment';
|
||||
}
|
||||
|
||||
return "{$alias}.{$field} AS balance_after_payment";
|
||||
}
|
||||
|
||||
private function successfulPaymentWhereSql(string $column): string
|
||||
{
|
||||
$escapedStatuses = array_map(
|
||||
fn (string $status): string => $this->db->escape($status),
|
||||
$this->excludedPaymentStatuses
|
||||
);
|
||||
|
||||
return 'LOWER(COALESCE(' . $column . ', \'\')) NOT IN (' . implode(', ', $escapedStatuses) . ')';
|
||||
}
|
||||
|
||||
private function getTableColumns(string $table): array
|
||||
{
|
||||
try {
|
||||
return $this->db->getFieldNames($table);
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', '[PaymentModel] Could not read table columns for {table}: {error}', [
|
||||
'table' => $table,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private function columnExists(string $table, string $column): bool
|
||||
{
|
||||
try {
|
||||
return $this->db->fieldExists($column, $table);
|
||||
} catch (\Throwable $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,18 +18,11 @@ class PaymentTransactionModel extends Model
|
||||
'payment_method',
|
||||
'payment_status',
|
||||
'transaction_fee',
|
||||
'payment_reference',
|
||||
'semester',
|
||||
'school_year',
|
||||
'is_full_payment', // Flag to track full payment status
|
||||
'created_at',
|
||||
'updated_at'
|
||||
'school_year'
|
||||
];
|
||||
|
||||
// Set automatic timestamps
|
||||
protected $useTimestamps = true;
|
||||
protected $createdField = 'created_at';
|
||||
protected $updatedField = 'updated_at';
|
||||
protected $useTimestamps = false;
|
||||
|
||||
// Validation rules
|
||||
protected $validationRules = [
|
||||
@@ -38,8 +31,8 @@ class PaymentTransactionModel extends Model
|
||||
'amount' => 'required|decimal',
|
||||
'payment_method' => 'required|string|max_length[50]',
|
||||
'payment_status' => 'required|string|max_length[50]',
|
||||
'payment_reference' => 'permit_empty|string|max_length[255]',
|
||||
'is_full_payment' => 'required|in_list[0,1]', // 0 for installment, 1 for full payment
|
||||
'semester' => 'permit_empty|string|max_length[30]',
|
||||
'school_year' => 'permit_empty|string|max_length[9]',
|
||||
];
|
||||
|
||||
// Custom error messages
|
||||
@@ -64,13 +57,6 @@ class PaymentTransactionModel extends Model
|
||||
'required' => 'The payment status is required.',
|
||||
'max_length' => 'The payment status must not exceed 50 characters.',
|
||||
],
|
||||
'payment_reference' => [
|
||||
'max_length' => 'The payment reference must not exceed 255 characters.',
|
||||
],
|
||||
'is_full_payment' => [
|
||||
'required' => 'The full payment flag is required.',
|
||||
'in_list' => 'The full payment flag must be either 0 (installment) or 1 (full payment).',
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -106,7 +92,9 @@ class PaymentTransactionModel extends Model
|
||||
*/
|
||||
public function updateTransactionStatus($transactionId, $status)
|
||||
{
|
||||
return $this->update($transactionId, ['payment_status' => $status]);
|
||||
return $this->where('transaction_id', $transactionId)
|
||||
->set(['payment_status' => $status])
|
||||
->update();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -130,7 +118,9 @@ class PaymentTransactionModel extends Model
|
||||
*/
|
||||
public function updateTransactionFee($transactionId, $transactionFee)
|
||||
{
|
||||
return $this->update($transactionId, ['transaction_fee' => $transactionFee]);
|
||||
return $this->where('transaction_id', $transactionId)
|
||||
->set(['transaction_fee' => $transactionFee])
|
||||
->update();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Model;
|
||||
|
||||
class PaypalTransactionModel extends Model
|
||||
{
|
||||
protected $table = 'paypal_transactions';
|
||||
protected $primaryKey = 'id';
|
||||
|
||||
protected $allowedFields = [
|
||||
'transaction_id',
|
||||
'payment_id',
|
||||
'firstname',
|
||||
'lastname',
|
||||
'event_type',
|
||||
'payer_email',
|
||||
'amount',
|
||||
'currency',
|
||||
'status',
|
||||
'payment_method',
|
||||
'transaction_fee',
|
||||
'semester',
|
||||
'school_year',
|
||||
'raw_data'
|
||||
];
|
||||
|
||||
protected $useTimestamps = true;
|
||||
}
|
||||
@@ -12,7 +12,6 @@ class PlacementLevelModel extends Model
|
||||
protected $allowedFields = [
|
||||
'student_id',
|
||||
'level',
|
||||
'school_year',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
'created_at',
|
||||
|
||||
@@ -12,8 +12,8 @@ class PreferencesModel extends Model
|
||||
// Allowed fields to enable mass assignment
|
||||
protected $allowedFields = [
|
||||
'user_id', // Foreign key linking preferences to a user
|
||||
'receive_email_notifications', // Email notifications preference
|
||||
'receive_sms_notifications', // SMS notifications preference
|
||||
'notification_email', // Email notifications preference
|
||||
'notification_sms', // SMS notifications preference
|
||||
'theme', // Theme preference (e.g., light or dark)
|
||||
'language', // Language preference
|
||||
'timezone', // Timezone preference
|
||||
@@ -22,11 +22,6 @@ class PreferencesModel extends Model
|
||||
'menu_custom_bg', // Custom menu background color
|
||||
'menu_custom_text', // Custom menu text color
|
||||
'menu_custom_mode', // Custom menu mode: light|dark
|
||||
'receive_push_notifications', // Push notifications preference
|
||||
'daily_summary_email', // Daily summary email preference
|
||||
'privacy_mode', // Privacy mode setting
|
||||
'marketing_emails', // Marketing emails preference
|
||||
'account_activity_alerts', // Account activity alerts preference
|
||||
'created_at', // Timestamp of when the record was created
|
||||
'updated_at' // Timestamp of when the record was last updated
|
||||
];
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Model;
|
||||
|
||||
class SchoolYearClosingBatchModel extends Model
|
||||
{
|
||||
protected $table = 'school_year_closing_batches';
|
||||
protected $primaryKey = 'id';
|
||||
protected $returnType = 'array';
|
||||
protected $useTimestamps = true;
|
||||
|
||||
protected $allowedFields = [
|
||||
'source_school_year_id',
|
||||
'target_school_year_id',
|
||||
'status',
|
||||
'preview_hash',
|
||||
'total_families',
|
||||
'total_positive_balance',
|
||||
'total_credit_balance',
|
||||
'started_by',
|
||||
'completed_by',
|
||||
'started_at',
|
||||
'completed_at',
|
||||
'failed_at',
|
||||
'failure_message',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Model;
|
||||
|
||||
class SchoolYearClosingItemModel extends Model
|
||||
{
|
||||
protected $table = 'school_year_closing_items';
|
||||
protected $primaryKey = 'id';
|
||||
protected $returnType = 'array';
|
||||
protected $useTimestamps = true;
|
||||
|
||||
protected $allowedFields = [
|
||||
'closing_batch_id',
|
||||
'family_id',
|
||||
'source_balance',
|
||||
'credit_amount',
|
||||
'adjustment_amount',
|
||||
'carry_forward_amount',
|
||||
'target_invoice_id',
|
||||
'target_adjustment_id',
|
||||
'status',
|
||||
'error_message',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Model;
|
||||
|
||||
class SchoolYearModel extends Model
|
||||
{
|
||||
protected $table = 'school_years';
|
||||
protected $primaryKey = 'id';
|
||||
protected $returnType = 'array';
|
||||
protected $useTimestamps = true;
|
||||
|
||||
protected $allowedFields = [
|
||||
'name',
|
||||
'status',
|
||||
'starts_on',
|
||||
'ends_on',
|
||||
'description',
|
||||
'registration_starts_on',
|
||||
'registration_ends_on',
|
||||
'previous_school_year_id',
|
||||
'next_school_year_id',
|
||||
'activated_at',
|
||||
'closing_started_at',
|
||||
'closed_at',
|
||||
'archived_at',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
];
|
||||
|
||||
protected $validationRules = [
|
||||
'name' => 'required|regex_match[/^\d{4}-\d{4}$/]|max_length[9]',
|
||||
'status' => 'required|in_list[draft,active,closing,closed,archived]',
|
||||
'starts_on' => 'permit_empty|valid_date[Y-m-d]',
|
||||
'ends_on' => 'permit_empty|valid_date[Y-m-d]',
|
||||
'registration_starts_on' => 'permit_empty|valid_date[Y-m-d]',
|
||||
'registration_ends_on' => 'permit_empty|valid_date[Y-m-d]',
|
||||
];
|
||||
|
||||
public function active(): ?array
|
||||
{
|
||||
return $this->where('status', 'active')
|
||||
->orderBy('id', 'DESC')
|
||||
->first();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Model;
|
||||
|
||||
class SchoolYearTransitionLogModel extends Model
|
||||
{
|
||||
protected $table = 'school_year_transition_logs';
|
||||
protected $primaryKey = 'id';
|
||||
protected $returnType = 'array';
|
||||
protected $useTimestamps = false;
|
||||
|
||||
protected $allowedFields = [
|
||||
'school_year_id',
|
||||
'from_status',
|
||||
'to_status',
|
||||
'action',
|
||||
'performed_by',
|
||||
'metadata_json',
|
||||
'created_at',
|
||||
];
|
||||
}
|
||||
@@ -12,7 +12,6 @@ class SectionModel extends Model
|
||||
protected $allowedFields = [
|
||||
'section_name',
|
||||
'description',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'updated_by'
|
||||
];
|
||||
|
||||
@@ -21,8 +21,6 @@ class StaffModel extends Model
|
||||
'phone',
|
||||
'role_name',
|
||||
'active_role',
|
||||
'status',
|
||||
'school_year',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
];
|
||||
@@ -44,7 +42,7 @@ class StaffModel extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert or update a staff row keyed by (user_id, school_year).
|
||||
* Insert or update a staff row keyed by user_id.
|
||||
* Ensures created_at is only set on insert and updated_at can be provided by caller.
|
||||
*/
|
||||
public function upsert(array $data): bool
|
||||
@@ -53,27 +51,9 @@ class StaffModel extends Model
|
||||
return false;
|
||||
}
|
||||
|
||||
// If school_year not provided, try to keep existing or fall back to current year string
|
||||
$schoolYear = $data['school_year'] ?? null;
|
||||
unset($data['school_year'], $data['status']);
|
||||
|
||||
if ($schoolYear === null) {
|
||||
// Try to find any existing row by user_id to reuse its school_year
|
||||
$existingAny = $this->where('user_id', $data['user_id'])->orderBy('id', 'DESC')->first();
|
||||
if ($existingAny && isset($existingAny['school_year'])) {
|
||||
$schoolYear = $existingAny['school_year'];
|
||||
$data['school_year'] = $schoolYear;
|
||||
}
|
||||
}
|
||||
|
||||
$existing = null;
|
||||
if ($schoolYear !== null) {
|
||||
$existing = $this->where('user_id', $data['user_id'])
|
||||
->where('school_year', $schoolYear)
|
||||
->first();
|
||||
} else {
|
||||
// If no school_year, treat (user_id) as key
|
||||
$existing = $this->where('user_id', $data['user_id'])->first();
|
||||
}
|
||||
|
||||
$now = utc_now();
|
||||
|
||||
@@ -100,4 +80,3 @@ class StaffModel extends Model
|
||||
return $this->insert($data) !== false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+471
-171
@@ -2,229 +2,529 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use CodeIgniter\Database\BaseBuilder;
|
||||
use CodeIgniter\Model;
|
||||
|
||||
class StudentClassModel extends Model
|
||||
{
|
||||
protected $table = 'student_class';
|
||||
protected $primaryKey = 'id';
|
||||
protected $returnType = 'array';
|
||||
|
||||
protected $useAutoIncrement = true;
|
||||
protected $protectFields = true;
|
||||
|
||||
protected $allowedFields = [
|
||||
'student_id',
|
||||
'school_id',
|
||||
'class_section_id',
|
||||
'school_year',
|
||||
'is_event_only',
|
||||
'description',
|
||||
'updated_by',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'created_at'
|
||||
];
|
||||
|
||||
protected $useTimestamps = true;
|
||||
protected $createdField = 'created_at';
|
||||
protected $updatedField = 'updated_at';
|
||||
|
||||
protected $validationRules = [
|
||||
'student_id' => 'required|integer',
|
||||
'class_section_id'=> 'permit_empty|integer',
|
||||
'school_year' => 'required|max_length[20]',
|
||||
'is_event_only' => 'permit_empty|in_list[0,1]',
|
||||
'updated_by' => 'permit_empty|integer',
|
||||
];
|
||||
|
||||
protected $validationMessages = [];
|
||||
protected $skipValidation = false;
|
||||
protected $cleanValidationRules = true;
|
||||
|
||||
/**
|
||||
* Scope: only students active for classes/attendance.
|
||||
* Create a fresh builder for student_class.
|
||||
*
|
||||
* Using a fresh builder prevents WHERE conditions from a previous model
|
||||
* query from leaking into another query.
|
||||
*/
|
||||
public function active(): self
|
||||
private function freshBuilder(): BaseBuilder
|
||||
{
|
||||
return $this->select('student_class.*')
|
||||
->join('students', 'students.id = student_class.student_id', 'inner')
|
||||
return $this->db->table($this->table);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a fresh builder scoped to active students.
|
||||
*/
|
||||
private function activeStudentsBuilder(): BaseBuilder
|
||||
{
|
||||
return $this->freshBuilder()
|
||||
->select('student_class.*')
|
||||
->join(
|
||||
'students',
|
||||
'students.id = student_class.student_id',
|
||||
'inner'
|
||||
)
|
||||
->where('students.is_active', 1);
|
||||
}
|
||||
|
||||
public function getClassSectionNameByStudentId(int $studentId): ?string
|
||||
/**
|
||||
* Apply the active-student scope to the model.
|
||||
*
|
||||
* Prefer the dedicated retrieval methods below for new code because they
|
||||
* use fresh builders and cannot inherit stale model query state.
|
||||
*/
|
||||
public function active(): self
|
||||
{
|
||||
return $this->db->table($this->table)
|
||||
return $this
|
||||
->select('student_class.*')
|
||||
->join(
|
||||
'students',
|
||||
'students.id = student_class.student_id',
|
||||
'inner'
|
||||
)
|
||||
->where('students.is_active', 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the most recent class section name assigned to a student.
|
||||
*/
|
||||
public function getClassSectionNameByStudentId(
|
||||
int $studentId,
|
||||
?string $schoolYear = null
|
||||
): ?string {
|
||||
$builder = $this->freshBuilder()
|
||||
->select('cs.class_section_name')
|
||||
->join('classSection cs', 'cs.class_section_id = student_class.class_section_id')
|
||||
->join(
|
||||
'classSection cs',
|
||||
'cs.class_section_id = student_class.class_section_id',
|
||||
'inner'
|
||||
)
|
||||
->where('student_class.student_id', $studentId)
|
||||
->get()
|
||||
->getRow('class_section_name');
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
);
|
||||
|
||||
if ($schoolYear !== null && trim($schoolYear) !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Custom findAll() method
|
||||
public function findAll($limit = 0, $offset = 0)
|
||||
{
|
||||
// Optional: Add custom logic before fetching all records
|
||||
|
||||
// Then call the parent findAll method to fetch the records
|
||||
return parent::findAll($limit, $offset);
|
||||
}
|
||||
|
||||
// Method to get all students in a specific class section (optionally scoped to term)
|
||||
public function getClassStudents($classSectionId, ?string $schoolYear = null)
|
||||
{
|
||||
$qb = $this->active()->where('student_class.class_section_id', $classSectionId);
|
||||
if ($schoolYear !== null && $schoolYear !== '') {
|
||||
$qb->where('student_class.school_year', $schoolYear);
|
||||
}
|
||||
return $qb->findAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class section names for a student in a given school year.
|
||||
*
|
||||
* @param int|string $studentId
|
||||
* @param string $schoolYear
|
||||
* @param bool $asArray When true, return an array of names; otherwise a comma-separated string.
|
||||
* @return array|string
|
||||
*/
|
||||
public function getClassSectionsByStudentId($studentId, string $schoolYear, bool $asArray = false)
|
||||
{
|
||||
$rows = $this->db->table('student_class')
|
||||
->select('cs.class_section_name')
|
||||
->join('classSection cs', 'student_class.class_section_id = cs.class_section_id')
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where('student_class.class_section_id IS NOT NULL', null, false)
|
||||
->where('student_class.school_year', $schoolYear)
|
||||
->orderBy('cs.class_section_name', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$names = array_values(array_unique(array_filter(array_map(static function ($row) {
|
||||
return $row['class_section_name'] ?? null;
|
||||
}, $rows))));
|
||||
|
||||
if ($asArray) {
|
||||
return $names;
|
||||
}
|
||||
|
||||
return !empty($names) ? implode(', ', $names) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class section names for a student in a given school year, with optional event flag.
|
||||
*
|
||||
* @param int|string $studentId
|
||||
* @param string $schoolYear
|
||||
* @param bool $asArray When true, return an array of names; otherwise a comma-separated string.
|
||||
* @return array|string
|
||||
*/
|
||||
public function getClassSectionsByStudentIdWithFlags($studentId, string $schoolYear, bool $asArray = false)
|
||||
{
|
||||
$rows = $this->db->table('student_class')
|
||||
->select('cs.class_section_name, student_class.is_event_only')
|
||||
->join('classSection cs', 'student_class.class_section_id = cs.class_section_id')
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where('student_class.class_section_id IS NOT NULL', null, false)
|
||||
->where('student_class.school_year', $schoolYear)
|
||||
->orderBy('cs.class_section_name', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$names = array_values(array_unique(array_filter(array_map(static function ($row) {
|
||||
$name = $row['class_section_name'] ?? null;
|
||||
if (!$name) return null;
|
||||
$isEvent = (int)($row['is_event_only'] ?? 0) === 1;
|
||||
return $isEvent ? ($name . ' (Event)') : $name;
|
||||
}, $rows))));
|
||||
|
||||
if ($asArray) {
|
||||
return $names;
|
||||
}
|
||||
|
||||
return !empty($names) ? implode(', ', $names) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class_section_id values for a student/year.
|
||||
*
|
||||
* @param int|string $studentId
|
||||
* @param string $schoolYear
|
||||
* @return int[]
|
||||
*/
|
||||
public function getClassSectionIdsByStudentId($studentId, string $schoolYear): array
|
||||
{
|
||||
$rows = $this->db->table('student_class')
|
||||
->select('class_section_id')
|
||||
->where('student_id', $studentId)
|
||||
->where('class_section_id IS NOT NULL', null, false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$ids = array_map(static fn($r) => (int)($r['class_section_id'] ?? 0), $rows);
|
||||
return array_values(array_filter(array_unique($ids), static fn($v) => $v > 0));
|
||||
}
|
||||
|
||||
|
||||
public function getStudentsByClassSectionIds(array $classSectionIds)
|
||||
{
|
||||
return $this->select('students.id as student_id, students.firstname, students.lastname, students.school_id, students.is_new,students.photo_consent ,students.age, student_class.school_year, student_class.class_section_id')
|
||||
->join('students', 'students.id = student_class.student_id')
|
||||
->whereIn('student_class.class_section_id', $classSectionIds)
|
||||
->where('students.is_active', 1)
|
||||
->get()
|
||||
->getResultArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the class ID (grade) for a specific student.
|
||||
*
|
||||
* @param int $studentId
|
||||
* @return string class_id or 'N/A'
|
||||
*/
|
||||
public function getStudentGrade(int $studentId): string
|
||||
{
|
||||
$studentClass = $this->where('student_id', $studentId)
|
||||
->where('is_event_only', 0)
|
||||
->orderBy('created_at', 'DESC') // in case of multiple entries, get latest
|
||||
->first();
|
||||
|
||||
if ($studentClass && isset($studentClass['class_section_id'])) {
|
||||
$classSection = $this->db->table('classSection')
|
||||
->where('class_section_id', $studentClass['class_section_id'])
|
||||
$row = $builder
|
||||
->orderBy('student_class.created_at', 'DESC')
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
return $classSection['class_id'] ?? 'N/A';
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
log_message('error', "Student class or section not found for student ID: $studentId");
|
||||
$name = trim((string) ($row['class_section_name'] ?? ''));
|
||||
|
||||
return $name !== '' ? $name : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get active students assigned to a class section.
|
||||
*
|
||||
* student_class is scoped by school year only. It has no semester column.
|
||||
*/
|
||||
public function getClassStudents(
|
||||
int $classSectionId,
|
||||
?string $schoolYear = null
|
||||
): array {
|
||||
$builder = $this->activeStudentsBuilder()
|
||||
->where(
|
||||
'student_class.class_section_id',
|
||||
$classSectionId
|
||||
)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
);
|
||||
|
||||
if ($schoolYear !== null && trim($schoolYear) !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
);
|
||||
}
|
||||
|
||||
return $builder
|
||||
->orderBy('students.lastname', 'ASC')
|
||||
->orderBy('students.firstname', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return student IDs assigned to a class section for a school year.
|
||||
*/
|
||||
public function getStudentIdsByClassSection(
|
||||
int $classSectionId,
|
||||
string $schoolYear
|
||||
): array {
|
||||
$schoolYear = trim($schoolYear);
|
||||
|
||||
$builder = $this->freshBuilder()
|
||||
->select('student_class.student_id')
|
||||
->join(
|
||||
'students',
|
||||
'students.id = student_class.student_id',
|
||||
'inner'
|
||||
)
|
||||
->where(
|
||||
'student_class.class_section_id',
|
||||
$classSectionId
|
||||
)
|
||||
->where('students.is_active', 1)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
);
|
||||
|
||||
if ($schoolYear !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
$schoolYear
|
||||
);
|
||||
}
|
||||
|
||||
$rows = $builder
|
||||
->groupBy('student_class.student_id')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$studentIds = array_map(
|
||||
static fn(array $row): int =>
|
||||
(int) ($row['student_id'] ?? 0),
|
||||
$rows
|
||||
);
|
||||
|
||||
return array_values(array_unique(array_filter(
|
||||
$studentIds,
|
||||
static fn(int $studentId): bool => $studentId > 0
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class section names assigned to a student for a school year.
|
||||
*
|
||||
* @return array|string
|
||||
*/
|
||||
public function getClassSectionsByStudentId(
|
||||
int|string $studentId,
|
||||
string $schoolYear,
|
||||
bool $asArray = false
|
||||
): array|string {
|
||||
$rows = $this->freshBuilder()
|
||||
->select('cs.class_section_name')
|
||||
->join(
|
||||
'classSection cs',
|
||||
'student_class.class_section_id = cs.class_section_id',
|
||||
'inner'
|
||||
)
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
)
|
||||
->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
)
|
||||
->orderBy('cs.class_section_name', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$names = array_map(
|
||||
static fn(array $row): string =>
|
||||
trim((string) ($row['class_section_name'] ?? '')),
|
||||
$rows
|
||||
);
|
||||
|
||||
$names = array_values(array_unique(array_filter(
|
||||
$names,
|
||||
static fn(string $name): bool => $name !== ''
|
||||
)));
|
||||
|
||||
return $asArray ? $names : implode(', ', $names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class section names and indicate event-only assignments.
|
||||
*
|
||||
* @return array|string
|
||||
*/
|
||||
public function getClassSectionsByStudentIdWithFlags(
|
||||
int|string $studentId,
|
||||
string $schoolYear,
|
||||
bool $asArray = false
|
||||
): array|string {
|
||||
$rows = $this->freshBuilder()
|
||||
->select(
|
||||
'cs.class_section_name, student_class.is_event_only'
|
||||
)
|
||||
->join(
|
||||
'classSection cs',
|
||||
'student_class.class_section_id = cs.class_section_id',
|
||||
'inner'
|
||||
)
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
)
|
||||
->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
)
|
||||
->orderBy('cs.class_section_name', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$names = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$name = trim(
|
||||
(string) ($row['class_section_name'] ?? '')
|
||||
);
|
||||
|
||||
if ($name === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((int) ($row['is_event_only'] ?? 0) === 1) {
|
||||
$name .= ' (Event)';
|
||||
}
|
||||
|
||||
$names[] = $name;
|
||||
}
|
||||
|
||||
$names = array_values(array_unique($names));
|
||||
|
||||
return $asArray ? $names : implode(', ', $names);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return class-section IDs assigned to a student for a school year.
|
||||
*
|
||||
* @return int[]
|
||||
*/
|
||||
public function getClassSectionIdsByStudentId(
|
||||
int|string $studentId,
|
||||
string $schoolYear
|
||||
): array {
|
||||
$rows = $this->freshBuilder()
|
||||
->select('student_class.class_section_id')
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
)
|
||||
->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
)
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$ids = array_map(
|
||||
static fn(array $row): int =>
|
||||
(int) ($row['class_section_id'] ?? 0),
|
||||
$rows
|
||||
);
|
||||
|
||||
return array_values(array_unique(array_filter(
|
||||
$ids,
|
||||
static fn(int $id): bool => $id > 0
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return active students for a set of class-section IDs.
|
||||
*/
|
||||
public function getStudentsByClassSectionIds(
|
||||
array $classSectionIds,
|
||||
?string $schoolYear = null
|
||||
): array {
|
||||
$classSectionIds = array_values(array_unique(array_filter(
|
||||
array_map('intval', $classSectionIds),
|
||||
static fn(int $id): bool => $id > 0
|
||||
)));
|
||||
|
||||
if ($classSectionIds === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$builder = $this->freshBuilder()
|
||||
->select([
|
||||
'students.id AS student_id',
|
||||
'students.firstname',
|
||||
'students.lastname',
|
||||
'students.school_id',
|
||||
'students.is_new',
|
||||
'students.photo_consent',
|
||||
'students.age',
|
||||
'student_class.school_year',
|
||||
'student_class.class_section_id',
|
||||
'student_class.is_event_only',
|
||||
])
|
||||
->join(
|
||||
'students',
|
||||
'students.id = student_class.student_id',
|
||||
'inner'
|
||||
)
|
||||
->whereIn(
|
||||
'student_class.class_section_id',
|
||||
$classSectionIds
|
||||
)
|
||||
->where('students.is_active', 1);
|
||||
|
||||
if ($schoolYear !== null && trim($schoolYear) !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
);
|
||||
}
|
||||
|
||||
return $builder
|
||||
->orderBy('students.lastname', 'ASC')
|
||||
->orderBy('students.firstname', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the student's most recent non-event class grade.
|
||||
*/
|
||||
public function getStudentGrade(
|
||||
int $studentId,
|
||||
?string $schoolYear = null
|
||||
): string {
|
||||
$builder = $this->freshBuilder()
|
||||
->select('classSection.class_id')
|
||||
->join(
|
||||
'classSection',
|
||||
'classSection.class_section_id = student_class.class_section_id',
|
||||
'inner'
|
||||
)
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where('student_class.is_event_only', 0)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
);
|
||||
|
||||
if ($schoolYear !== null && trim($schoolYear) !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
);
|
||||
}
|
||||
|
||||
$row = $builder
|
||||
->orderBy('student_class.created_at', 'DESC')
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
$classId = trim((string) ($row['class_id'] ?? ''));
|
||||
|
||||
if ($classId !== '') {
|
||||
return $classId;
|
||||
}
|
||||
|
||||
log_message(
|
||||
'warning',
|
||||
'Student class or section not found for student ID: {studentId}',
|
||||
['studentId' => $studentId]
|
||||
);
|
||||
|
||||
return 'N/A';
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the student has at least one non-event class assignment for the year.
|
||||
* Determine whether a student has a non-event assignment for a year.
|
||||
*/
|
||||
public function hasNonEventAssignment(int $studentId, string $schoolYear): bool
|
||||
{
|
||||
return (bool) $this->where('student_id', $studentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->where('is_event_only', 0)
|
||||
->first();
|
||||
public function hasNonEventAssignment(
|
||||
int $studentId,
|
||||
string $schoolYear
|
||||
): bool {
|
||||
return $this->freshBuilder()
|
||||
->select('student_class.id')
|
||||
->where('student_class.student_id', $studentId)
|
||||
->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
)
|
||||
->where('student_class.is_event_only', 0)
|
||||
->limit(1)
|
||||
->get()
|
||||
->getRowArray() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return student counts per class_section_id, optionally scoped to a school year.
|
||||
* Return active student counts by class section.
|
||||
*
|
||||
* @param string|null $schoolYear
|
||||
* @return array<int|string,int> Map of class_section_id => count
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function getStudentCountsBySection(?string $schoolYear = null): array
|
||||
{
|
||||
$qb = $this->db->table($this->table)
|
||||
->select('class_section_id, COUNT(*) AS total')
|
||||
->join('students', 'students.id = student_class.student_id', 'inner')
|
||||
public function getStudentCountsBySection(
|
||||
?string $schoolYear = null
|
||||
): array {
|
||||
$builder = $this->freshBuilder()
|
||||
->select(
|
||||
'student_class.class_section_id, ' .
|
||||
'COUNT(DISTINCT student_class.student_id) AS total'
|
||||
)
|
||||
->join(
|
||||
'students',
|
||||
'students.id = student_class.student_id',
|
||||
'inner'
|
||||
)
|
||||
->where('students.is_active', 1)
|
||||
->where('student_class.class_section_id IS NOT NULL', null, false)
|
||||
->where(
|
||||
'student_class.class_section_id IS NOT NULL',
|
||||
null,
|
||||
false
|
||||
)
|
||||
->groupBy('student_class.class_section_id');
|
||||
|
||||
if ($schoolYear !== null && $schoolYear !== '') {
|
||||
$qb->where('student_class.school_year', $schoolYear);
|
||||
if ($schoolYear !== null && trim($schoolYear) !== '') {
|
||||
$builder->where(
|
||||
'student_class.school_year',
|
||||
trim($schoolYear)
|
||||
);
|
||||
}
|
||||
|
||||
$rows = $qb->get()->getResultArray();
|
||||
$out = [];
|
||||
foreach ($rows as $r) {
|
||||
$cid = $r['class_section_id'] ?? null;
|
||||
if ($cid === null || $cid === '') continue;
|
||||
$out[$cid] = (int)($r['total'] ?? 0);
|
||||
$rows = $builder
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$counts = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$classSectionId = (int) (
|
||||
$row['class_section_id'] ?? 0
|
||||
);
|
||||
|
||||
if ($classSectionId <= 0) {
|
||||
continue;
|
||||
}
|
||||
return $out;
|
||||
|
||||
$counts[$classSectionId] = (int) (
|
||||
$row['total'] ?? 0
|
||||
);
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,9 @@ class StudentDecisionModel extends Model
|
||||
|
||||
protected $allowedFields = [
|
||||
'student_id',
|
||||
'semester',
|
||||
'school_year',
|
||||
'class_section_name',
|
||||
'semester_score',
|
||||
'year_score',
|
||||
'decision',
|
||||
'source',
|
||||
'notes',
|
||||
|
||||
@@ -19,7 +19,6 @@ class StudentModel extends Model
|
||||
'photo_consent',
|
||||
'is_new',
|
||||
'parent_id',
|
||||
'school_year',
|
||||
'registration_date',
|
||||
'tuition_paid',
|
||||
'year_of_registration',
|
||||
@@ -122,7 +121,9 @@ class StudentModel extends Model
|
||||
|
||||
// school_year filter (skip if null or "all")
|
||||
if ($schoolYear !== null && strtolower($schoolYear) !== 'all') {
|
||||
$builder->where('students.school_year', $schoolYear);
|
||||
$builder
|
||||
->join('student_class sc_filter', 'sc_filter.student_id = students.id', 'inner')
|
||||
->where('sc_filter.school_year', $schoolYear);
|
||||
}
|
||||
|
||||
return $builder
|
||||
@@ -171,12 +172,13 @@ class StudentModel extends Model
|
||||
users.cellphone as phone,
|
||||
students.registration_grade,
|
||||
classSection.class_section_name as current_class,
|
||||
"' . $schoolYear . '" as school_year,
|
||||
student_class.school_year,
|
||||
"' . $semester . '" as semester
|
||||
')
|
||||
->join('users', 'users.id = students.parent_id', 'left')
|
||||
->join('student_class', 'student_class.student_id = students.id', 'left')
|
||||
->join('class_section', 'student_class.class_section_id = classSection.id', 'left')
|
||||
->join('classSection', 'student_class.class_section_id = classSection.class_section_id', 'left')
|
||||
->where('student_class.school_year', $schoolYear)
|
||||
->get()
|
||||
->getResultArray();
|
||||
}
|
||||
@@ -199,7 +201,7 @@ class StudentModel extends Model
|
||||
')
|
||||
->join('student_class', 'students.id = student_class.student_id', 'left')
|
||||
->join('teacher_class', 'student_class.class_section_id = teacher_class.class_section_id', 'left')
|
||||
->join('class_section', 'student_class.class_section_id = classSection.id', 'left')
|
||||
->join('classSection', 'student_class.class_section_id = classSection.class_section_id', 'left')
|
||||
->where('teacher_class.teacher_id', $teacherId)
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
+20
-24
@@ -28,7 +28,6 @@ class UserModel extends Model
|
||||
'failed_attempts',
|
||||
'last_failed_at',
|
||||
'semester',
|
||||
'school_year',
|
||||
'status',
|
||||
'is_suspended',
|
||||
'is_verified',
|
||||
@@ -237,13 +236,21 @@ class UserModel extends Model
|
||||
|
||||
public function getUsersByRoleAndSchoolYear(string $roleName, string $schoolYear): array
|
||||
{
|
||||
return $this->select('users.*')
|
||||
$builder = $this->select('users.*')
|
||||
->join('user_roles', 'user_roles.user_id = users.id')
|
||||
->join('roles', 'roles.id = user_roles.role_id')
|
||||
->where('roles.name', $roleName)
|
||||
->where('users.school_year', $schoolYear)
|
||||
->where('user_roles.deleted_at', null)
|
||||
->findAll();
|
||||
->where('user_roles.deleted_at', null);
|
||||
|
||||
if ($this->roleUsesTeacherAssignments($roleName)) {
|
||||
$builder->join(
|
||||
'teacher_class tc_year',
|
||||
'tc_year.teacher_id = users.id AND tc_year.school_year = ' . $this->db->escape($schoolYear),
|
||||
'inner'
|
||||
);
|
||||
}
|
||||
|
||||
return $builder->groupBy('users.id')->findAll();
|
||||
}
|
||||
|
||||
public function countAdminsBySchoolYear(string $schoolYear): int
|
||||
@@ -260,8 +267,8 @@ class UserModel extends Model
|
||||
)
|
||||
->join('user_roles ur', 'ur.user_id = u.id', 'inner')
|
||||
->join('roles r', 'r.id = ur.role_id', 'inner')
|
||||
->where('u.school_year', $schoolYear)
|
||||
->where('r.is_active', 1)
|
||||
->where('LOWER(r.name) NOT IN ("guest","teacher","teacher_assistant","parent")', null, false)
|
||||
->groupBy('u.id')
|
||||
->having('is_admin', 1);
|
||||
|
||||
@@ -357,28 +364,13 @@ class UserModel extends Model
|
||||
}
|
||||
|
||||
if (!empty($schoolYear)) {
|
||||
// Prefer user_roles.school_year if present (true year-scoped roles)
|
||||
$userRolesFields = [];
|
||||
try {
|
||||
$userRolesFields = $this->db->getFieldNames('user_roles');
|
||||
} catch (\Throwable $e) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
if (in_array('school_year', $userRolesFields, true)) {
|
||||
$builder->where('ur.school_year', $schoolYear);
|
||||
} else {
|
||||
// Fallback: role-aware filter
|
||||
$escYear = $this->db->escape($schoolYear);
|
||||
|
||||
// Include user if:
|
||||
// (A) They are assigned as teacher/TA in teacher_class for that year
|
||||
// OR
|
||||
// (B) They have at least one non-teacher-ish (and non-parent) role (admin/staff/etc.)
|
||||
//
|
||||
// Teacher-ish detection: name contains 'teacher' OR equals 'ta'
|
||||
// (B) They have at least one non-teacher-ish (and non-parent) global role.
|
||||
$builder->groupStart()
|
||||
// A) has teacher assignment that year
|
||||
->where("
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
@@ -387,7 +379,6 @@ class UserModel extends Model
|
||||
AND tc.school_year = {$escYear}
|
||||
)
|
||||
", null, false)
|
||||
// B) OR has any non-teacher-ish, non-parent role
|
||||
->orWhere("
|
||||
EXISTS (
|
||||
SELECT 1
|
||||
@@ -400,11 +391,16 @@ class UserModel extends Model
|
||||
", null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
}
|
||||
|
||||
return $builder
|
||||
->groupBy('users.id')
|
||||
->orderBy($sort === 'roles' ? 'roles' : $sort, $order)
|
||||
->findAll();
|
||||
}
|
||||
|
||||
private function roleUsesTeacherAssignments(string $roleName): bool
|
||||
{
|
||||
$role = strtolower(trim($roleName));
|
||||
return $role === 'ta' || str_contains($role, 'teacher');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,8 +13,6 @@ class UserRoleModel extends Model
|
||||
protected $allowedFields = [
|
||||
'user_id',
|
||||
'role_id',
|
||||
'semester',
|
||||
'school_year',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'updated_by',
|
||||
|
||||
@@ -11,7 +11,6 @@ class WhatsappGroupLinkModel extends Model
|
||||
'class_section_id',
|
||||
'class_section_name',
|
||||
'school_year',
|
||||
'semester',
|
||||
'invite_link',
|
||||
'active',
|
||||
];
|
||||
@@ -22,9 +21,9 @@ class WhatsappGroupLinkModel extends Model
|
||||
*
|
||||
* @param int $sectionId Class/section code (not PK).
|
||||
* @param string $year School year, e.g. "2025-2026".
|
||||
* @param string $sem Semester, e.g. "Fall".
|
||||
* @param string $sem Deprecated/ignored; links are scoped by school year.
|
||||
* @param bool $onlyActive If true, require active=1.
|
||||
* @param bool $allowNullSemester If true, accept rows with semester IS NULL as well.
|
||||
* @param bool $allowNullSemester Deprecated/ignored.
|
||||
*/
|
||||
public function getLinkForSection(
|
||||
int $sectionId,
|
||||
@@ -40,17 +39,6 @@ class WhatsappGroupLinkModel extends Model
|
||||
->where('class_section_id', $sectionId)
|
||||
->where('school_year', $year);
|
||||
|
||||
if ($sem !== '') {
|
||||
if ($allowNullSemester) {
|
||||
$b = $b->groupStart()
|
||||
->where('semester', $sem)
|
||||
->orWhere('semester IS NULL', null, false)
|
||||
->groupEnd();
|
||||
} else {
|
||||
$b = $b->where('semester', $sem);
|
||||
}
|
||||
}
|
||||
|
||||
if ($onlyActive) {
|
||||
$b = $b->where('active', 1);
|
||||
}
|
||||
@@ -70,7 +58,7 @@ class WhatsappGroupLinkModel extends Model
|
||||
* @param string $year
|
||||
* @param string $sem
|
||||
* @param bool|null $onlyActive true: active only, false: inactive only, null: both
|
||||
* @param bool $allowNullSemester If true, include rows with semester IS NULL.
|
||||
* @param bool $allowNullSemester Deprecated/ignored.
|
||||
*/
|
||||
public function getAllForTerm(
|
||||
string $year,
|
||||
@@ -84,17 +72,6 @@ class WhatsappGroupLinkModel extends Model
|
||||
$b = $this->asArray()
|
||||
->where('school_year', $year);
|
||||
|
||||
if ($sem !== '') {
|
||||
if ($allowNullSemester) {
|
||||
$b = $b->groupStart()
|
||||
->where('semester', $sem)
|
||||
->orWhere('semester IS NULL', null, false)
|
||||
->groupEnd();
|
||||
} else {
|
||||
$b = $b->where('semester', $sem);
|
||||
}
|
||||
}
|
||||
|
||||
if ($onlyActive === true) {
|
||||
$b = $b->where('active', 1);
|
||||
} elseif ($onlyActive === false) {
|
||||
@@ -122,7 +99,6 @@ class WhatsappGroupLinkModel extends Model
|
||||
'class_section_id' => $sectionId,
|
||||
'class_section_name' => $sectionName,
|
||||
'school_year' => trim($year),
|
||||
'semester' => trim($sem),
|
||||
'invite_link' => trim($inviteLink),
|
||||
'active' => $active ? 1 : 0,
|
||||
];
|
||||
@@ -131,7 +107,6 @@ class WhatsappGroupLinkModel extends Model
|
||||
$existing = $this->asArray()
|
||||
->where('class_section_id', $sectionId)
|
||||
->where('school_year', $payload['school_year'])
|
||||
->where('semester', $payload['semester'])
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
|
||||
@@ -42,7 +42,7 @@ class WhatsappInviteLogModel extends Model
|
||||
/**
|
||||
* Log a successful send.
|
||||
*/
|
||||
public function logSuccess(int $parentId, string $email, int $classSectionId = null, int $linkId = null): bool
|
||||
public function logSuccess(int $parentId, string $email, ?int $classSectionId = null, ?int $linkId = null): bool
|
||||
{
|
||||
return (bool) $this->insert([
|
||||
'parent_id' => $parentId,
|
||||
@@ -58,7 +58,7 @@ class WhatsappInviteLogModel extends Model
|
||||
/**
|
||||
* Log a failure with error message.
|
||||
*/
|
||||
public function logFailure(int $parentId, string $email, string $error, int $classSectionId = null, int $linkId = null): bool
|
||||
public function logFailure(int $parentId, string $email, string $error, ?int $classSectionId = null, ?int $linkId = null): bool
|
||||
{
|
||||
return (bool) $this->insert([
|
||||
'parent_id' => $parentId,
|
||||
|
||||
@@ -61,7 +61,7 @@ class FeeCalculationService
|
||||
// Retrieve fee configs
|
||||
$firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350);
|
||||
$secondStudentFee = (float) ($configModel->getConfig('second_student_fee') ?? 200);
|
||||
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 180);
|
||||
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 200);
|
||||
|
||||
// Assign tuition_fee to all students (before filtering refunds)
|
||||
$regularCount = 0;
|
||||
@@ -148,7 +148,7 @@ class FeeCalculationService
|
||||
|
||||
$firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350);
|
||||
$secondStudentFee = (float) ($configModel->getConfig('second_student_fee') ?? 200);
|
||||
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 180);
|
||||
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 200);
|
||||
|
||||
// ✅ Pre-fetch and assign grade/class section names before sorting
|
||||
foreach ($students as &$student) {
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SchoolYearClosingBatchModel;
|
||||
use App\Models\SchoolYearClosingItemModel;
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Support\SchoolYear\SchoolYearStatus;
|
||||
use CodeIgniter\Database\BaseConnection;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearClosingService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
private readonly SchoolYearClosingBatchModel $batchModel,
|
||||
private readonly SchoolYearClosingItemModel $itemModel,
|
||||
private readonly SchoolYearManagementService $managementService,
|
||||
private readonly BaseConnection $db,
|
||||
) {
|
||||
}
|
||||
|
||||
public function preview(int $sourceYearId, ?int $targetYearId = null): array
|
||||
{
|
||||
$source = $this->requireYear($sourceYearId);
|
||||
$target = $targetYearId !== null ? $this->schoolYearModel->find($targetYearId) : $this->nextDraftYear((string) $source['name']);
|
||||
$sourceName = (string) $source['name'];
|
||||
|
||||
$finance = $this->financialSummary($sourceName);
|
||||
$overview = [
|
||||
'students' => $this->countBySchoolYear('student_class', $sourceName, 'student_id'),
|
||||
'families' => $this->countFamilies($sourceName),
|
||||
'classes' => $this->countBySchoolYear('classSection', $sourceName, 'class_id'),
|
||||
'teachers' => $this->countBySchoolYear('teacher_class', $sourceName, 'teacher_id'),
|
||||
'invoices' => $finance['invoice_count'],
|
||||
'total_invoiced' => $finance['total_invoiced'],
|
||||
'total_paid' => $finance['total_paid'],
|
||||
'total_outstanding' => $finance['total_outstanding'],
|
||||
];
|
||||
|
||||
$findings = [];
|
||||
if ($target === null) {
|
||||
$findings[] = $this->finding('blocking', 'Missing target year', 'Create a draft target school year before starting closing.');
|
||||
} elseif (! in_array((string) $target['status'], [SchoolYearStatus::DRAFT, SchoolYearStatus::ACTIVE], true)) {
|
||||
$findings[] = $this->finding('blocking', 'Invalid target year', 'The target school year must be draft or active.');
|
||||
}
|
||||
|
||||
foreach ($this->unpaidInvoiceFindings($sourceName) as $finding) {
|
||||
$findings[] = $finding;
|
||||
}
|
||||
|
||||
if ($this->countMissingSchoolYearRows('invoices') > 0) {
|
||||
$findings[] = $this->finding('blocking', 'Invoices missing school year', 'Some invoice records are not assigned to a school year.');
|
||||
}
|
||||
|
||||
$carryForward = $this->carryForwardFamilies($sourceName);
|
||||
$warnings = array_values(array_filter($findings, static fn (array $f): bool => $f['severity'] === 'warning'));
|
||||
$blockers = array_values(array_filter($findings, static fn (array $f): bool => $f['severity'] === 'blocking'));
|
||||
|
||||
$result = [
|
||||
'source' => $source,
|
||||
'target' => $target,
|
||||
'overview' => $overview,
|
||||
'finance' => $finance,
|
||||
'findings' => $findings,
|
||||
'blockers' => $blockers,
|
||||
'warnings' => $warnings,
|
||||
'carry_forward' => $carryForward,
|
||||
'generated_at' => date('Y-m-d H:i:s'),
|
||||
];
|
||||
$result['hash'] = $this->hashPreview($result);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function start(int $sourceYearId, int $targetYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$source = $this->requireYear($sourceYearId);
|
||||
|
||||
if (($source['status'] ?? '') !== SchoolYearStatus::ACTIVE) {
|
||||
throw new InvalidArgumentException('Only an active school year can begin closing.');
|
||||
}
|
||||
|
||||
$preview = $this->preview($sourceYearId, $targetYearId);
|
||||
if ($preview['blockers'] !== []) {
|
||||
throw new InvalidArgumentException('Resolve blocking closing issues before starting closing.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$batchId = $this->batchModel->insert([
|
||||
'source_school_year_id' => $sourceYearId,
|
||||
'target_school_year_id' => $targetYearId,
|
||||
'status' => 'started',
|
||||
'preview_hash' => $preview['hash'],
|
||||
'total_families' => count($preview['carry_forward']),
|
||||
'total_positive_balance' => $preview['finance']['positive_balance'],
|
||||
'total_credit_balance' => $preview['finance']['credit_balance'],
|
||||
'started_by' => $userId,
|
||||
'started_at' => $now,
|
||||
], true);
|
||||
|
||||
foreach ($preview['carry_forward'] as $row) {
|
||||
$this->itemModel->insert([
|
||||
'closing_batch_id' => $batchId,
|
||||
'family_id' => (int) $row['family_id'],
|
||||
'source_balance' => $row['source_balance'],
|
||||
'credit_amount' => $row['credit_amount'],
|
||||
'carry_forward_amount' => $row['carry_forward_amount'],
|
||||
'status' => 'pending',
|
||||
]);
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update($sourceYearId, [
|
||||
'status' => SchoolYearStatus::CLOSING,
|
||||
'closing_started_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::ACTIVE, SchoolYearStatus::CLOSING, 'closing_start', $userId, [
|
||||
'target_school_year_id' => $targetYearId,
|
||||
'closing_batch_id' => $batchId,
|
||||
'preview_hash' => $preview['hash'],
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to start school year closing.');
|
||||
}
|
||||
}
|
||||
|
||||
public function execute(int $sourceYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$batch = $this->latestOpenBatch($sourceYearId);
|
||||
if ($batch === null) {
|
||||
throw new InvalidArgumentException('No open closing batch exists.');
|
||||
}
|
||||
|
||||
$preview = $this->preview($sourceYearId, (int) $batch['target_school_year_id']);
|
||||
if ($preview['hash'] !== (string) $batch['preview_hash']) {
|
||||
throw new InvalidArgumentException('Closing preview has changed. Refresh and restart closing before executing carry-forward.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$items = $this->itemModel->where('closing_batch_id', (int) $batch['id'])->findAll();
|
||||
foreach ($items as $item) {
|
||||
if (($item['status'] ?? '') === 'completed') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->itemModel->update((int) $item['id'], ['status' => 'completed']);
|
||||
}
|
||||
$this->batchModel->update((int) $batch['id'], ['status' => 'executed']);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::CLOSING, 'carry_forward_execute', $userId, [
|
||||
'closing_batch_id' => (int) $batch['id'],
|
||||
'note' => 'Marked previewed carry-forward items complete. Target accounting records require the dedicated opening-balance schema.',
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to execute carry-forward.');
|
||||
}
|
||||
}
|
||||
|
||||
public function complete(int $sourceYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$batch = $this->latestOpenBatch($sourceYearId);
|
||||
if ($batch === null || ($batch['status'] ?? '') !== 'executed') {
|
||||
throw new InvalidArgumentException('Carry-forward must be executed before completing closing.');
|
||||
}
|
||||
|
||||
$pending = $this->itemModel
|
||||
->where('closing_batch_id', (int) $batch['id'])
|
||||
->where('status !=', 'completed')
|
||||
->countAllResults();
|
||||
if ($pending > 0) {
|
||||
throw new InvalidArgumentException('All closing batch items must complete before the year can be closed.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$this->batchModel->update((int) $batch['id'], [
|
||||
'status' => 'completed',
|
||||
'completed_by' => $userId,
|
||||
'completed_at' => $now,
|
||||
]);
|
||||
$this->schoolYearModel->update($sourceYearId, [
|
||||
'status' => SchoolYearStatus::CLOSED,
|
||||
'closed_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::CLOSED, 'closing_complete', $userId, [
|
||||
'closing_batch_id' => (int) $batch['id'],
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to complete closing.');
|
||||
}
|
||||
}
|
||||
|
||||
public function cancel(int $sourceYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$batch = $this->latestOpenBatch($sourceYearId);
|
||||
if ($batch !== null && in_array((string) $batch['status'], ['executed', 'completed'], true)) {
|
||||
throw new InvalidArgumentException('Closing cannot be cancelled after carry-forward has executed.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
if ($batch !== null) {
|
||||
$this->batchModel->update((int) $batch['id'], ['status' => 'cancelled']);
|
||||
}
|
||||
$this->schoolYearModel->update($sourceYearId, [
|
||||
'status' => SchoolYearStatus::ACTIVE,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::ACTIVE, 'closing_cancel', $userId, [
|
||||
'closing_batch_id' => $batch['id'] ?? null,
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to cancel closing.');
|
||||
}
|
||||
}
|
||||
|
||||
public function latestBatch(int $sourceYearId): ?array
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_closing_batches')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->batchModel
|
||||
->where('source_school_year_id', $sourceYearId)
|
||||
->orderBy('id', 'DESC')
|
||||
->first();
|
||||
}
|
||||
|
||||
private function requireYear(int $id): array
|
||||
{
|
||||
$year = $this->schoolYearModel->find($id);
|
||||
if ($year === null) {
|
||||
throw new InvalidArgumentException('School year not found.');
|
||||
}
|
||||
|
||||
return $year;
|
||||
}
|
||||
|
||||
private function nextDraftYear(string $sourceName): ?array
|
||||
{
|
||||
if (! preg_match('/^(\d{4})-(\d{4})$/', $sourceName, $matches)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$nextName = $matches[2] . '-' . ((int) $matches[2] + 1);
|
||||
|
||||
return $this->schoolYearModel
|
||||
->where('name', $nextName)
|
||||
->first();
|
||||
}
|
||||
|
||||
private function financialSummary(string $schoolYear): array
|
||||
{
|
||||
$summary = [
|
||||
'invoice_count' => 0,
|
||||
'total_invoiced' => 0.0,
|
||||
'total_paid' => 0.0,
|
||||
'total_outstanding' => 0.0,
|
||||
'positive_balance' => 0.0,
|
||||
'credit_balance' => 0.0,
|
||||
];
|
||||
|
||||
if (! $this->db->tableExists('invoices')) {
|
||||
return $summary;
|
||||
}
|
||||
|
||||
$row = $this->db->table('invoices')
|
||||
->select('COUNT(*) AS invoice_count')
|
||||
->select('COALESCE(SUM(total_amount), 0) AS total_invoiced')
|
||||
->select('COALESCE(SUM(paid_amount), 0) AS total_paid')
|
||||
->select('COALESCE(SUM(balance), 0) AS total_outstanding')
|
||||
->select('COALESCE(SUM(CASE WHEN balance > 0 THEN balance ELSE 0 END), 0) AS positive_balance', false)
|
||||
->select('COALESCE(SUM(CASE WHEN balance < 0 THEN ABS(balance) ELSE 0 END), 0) AS credit_balance', false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getRowArray() ?? [];
|
||||
|
||||
foreach ($summary as $key => $value) {
|
||||
$summary[$key] = $key === 'invoice_count' ? (int) ($row[$key] ?? 0) : round((float) ($row[$key] ?? 0), 2);
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
private function unpaidInvoiceFindings(string $schoolYear): array
|
||||
{
|
||||
if (! $this->db->tableExists('invoices')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$count = $this->db->table('invoices')
|
||||
->where('school_year', $schoolYear)
|
||||
->where('balance >', 0)
|
||||
->countAllResults();
|
||||
|
||||
return $count > 0
|
||||
? [$this->finding('warning', 'Outstanding balances exist', "{$count} invoice(s) still have a positive balance and will require carry-forward review.")]
|
||||
: [];
|
||||
}
|
||||
|
||||
private function carryForwardFamilies(string $schoolYear): array
|
||||
{
|
||||
if (! $this->db->tableExists('invoices')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->db->table('invoices i')
|
||||
->select('i.parent_id AS family_id')
|
||||
->select('COALESCE(SUM(i.balance), 0) AS source_balance')
|
||||
->where('i.school_year', $schoolYear)
|
||||
->groupBy('i.parent_id')
|
||||
->having('source_balance !=', 0)
|
||||
->orderBy('i.parent_id', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
return array_map(static function (array $row): array {
|
||||
$balance = round((float) $row['source_balance'], 2);
|
||||
|
||||
return [
|
||||
'family_id' => (int) $row['family_id'],
|
||||
'family' => 'Family #' . (int) $row['family_id'],
|
||||
'source_balance' => $balance,
|
||||
'credit_amount' => $balance < 0 ? abs($balance) : 0.0,
|
||||
'adjustment_amount' => 0.0,
|
||||
'carry_forward_amount' => $balance,
|
||||
];
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
private function countBySchoolYear(string $table, string $schoolYear, string $distinctField): int
|
||||
{
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$row = $this->db->table($table)
|
||||
->select("COUNT(DISTINCT {$distinctField}) AS total", false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
return (int) ($row['total'] ?? 0);
|
||||
}
|
||||
|
||||
private function countFamilies(string $schoolYear): int
|
||||
{
|
||||
if ($this->db->tableExists('invoices')) {
|
||||
$row = $this->db->table('invoices')
|
||||
->select('COUNT(DISTINCT parent_id) AS total', false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
return (int) ($row['total'] ?? 0);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private function countMissingSchoolYearRows(string $table): int
|
||||
{
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $this->db->table($table)
|
||||
->groupStart()
|
||||
->where('school_year', null)
|
||||
->orWhere('school_year', '')
|
||||
->groupEnd()
|
||||
->countAllResults();
|
||||
}
|
||||
|
||||
private function latestOpenBatch(int $sourceYearId): ?array
|
||||
{
|
||||
return $this->batchModel
|
||||
->where('source_school_year_id', $sourceYearId)
|
||||
->whereIn('status', ['started', 'executed'])
|
||||
->orderBy('id', 'DESC')
|
||||
->first();
|
||||
}
|
||||
|
||||
private function assertClosingTablesExist(): void
|
||||
{
|
||||
foreach (['school_year_closing_batches', 'school_year_closing_items', 'school_year_transition_logs'] as $table) {
|
||||
if (! $this->db->tableExists($table)) {
|
||||
throw new RuntimeException('School year lifecycle tables are missing. Run database migrations before closing a school year.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function finding(string $severity, string $title, string $detail): array
|
||||
{
|
||||
return [
|
||||
'severity' => $severity,
|
||||
'title' => $title,
|
||||
'detail' => $detail,
|
||||
];
|
||||
}
|
||||
|
||||
private function hashPreview(array $preview): string
|
||||
{
|
||||
return hash('sha256', json_encode([
|
||||
'source_id' => $preview['source']['id'] ?? null,
|
||||
'target_id' => $preview['target']['id'] ?? null,
|
||||
'finance' => $preview['finance'],
|
||||
'carry_forward' => $preview['carry_forward'],
|
||||
'blockers' => $preview['blockers'],
|
||||
], JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Support\SchoolYear\SchoolYearContext;
|
||||
use CodeIgniter\HTTP\IncomingRequest;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearContextService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
) {
|
||||
}
|
||||
|
||||
public function resolve(
|
||||
IncomingRequest $request,
|
||||
?int $routeSchoolYearId = null
|
||||
): SchoolYearContext {
|
||||
$requestedId = $routeSchoolYearId
|
||||
?? $this->normalizeInt($request->getGet('school_year_id'));
|
||||
|
||||
$requestedName = trim((string) $request->getGet('school_year'));
|
||||
|
||||
if ($requestedId !== null && $requestedName !== '') {
|
||||
$row = $this->schoolYearModel->find($requestedId);
|
||||
|
||||
if ($row === null || (string) ($row['name'] ?? '') !== $requestedName) {
|
||||
throw new RuntimeException('Selected school-year parameters conflict.');
|
||||
}
|
||||
|
||||
return $this->fromRow($row, true);
|
||||
}
|
||||
|
||||
if ($requestedId !== null) {
|
||||
$row = $this->schoolYearModel->find($requestedId);
|
||||
|
||||
if ($row === null) {
|
||||
throw new RuntimeException('Selected school year was not found.');
|
||||
}
|
||||
|
||||
return $this->fromRow($row, true);
|
||||
}
|
||||
|
||||
if ($requestedName !== '') {
|
||||
$row = $this->schoolYearModel
|
||||
->where('name', $requestedName)
|
||||
->first();
|
||||
|
||||
if ($row === null) {
|
||||
throw new RuntimeException('Selected school year was not found.');
|
||||
}
|
||||
|
||||
return $this->fromRow($row, true);
|
||||
}
|
||||
|
||||
$sessionYearId = session('selected_school_year_id');
|
||||
|
||||
if (is_numeric($sessionYearId)) {
|
||||
$row = $this->schoolYearModel->find((int) $sessionYearId);
|
||||
|
||||
if ($row !== null) {
|
||||
return $this->fromRow($row, false);
|
||||
}
|
||||
}
|
||||
|
||||
$active = $this->schoolYearModel->active();
|
||||
|
||||
if ($active === null) {
|
||||
throw new RuntimeException('No active school year is configured.');
|
||||
}
|
||||
|
||||
return $this->fromRow($active, false);
|
||||
}
|
||||
|
||||
private function normalizeInt(mixed $value): ?int
|
||||
{
|
||||
if ($value === null || $value === '' || ! ctype_digit((string) $value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
private function fromRow(array $row, bool $explicit): SchoolYearContext
|
||||
{
|
||||
return new SchoolYearContext(
|
||||
id: (int) $row['id'],
|
||||
yearName: (string) $row['name'],
|
||||
status: (string) $row['status'],
|
||||
explicitSelection: $explicit,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\SchoolYearClosingBatchModel;
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Models\SchoolYearTransitionLogModel;
|
||||
use App\Support\SchoolYear\SchoolYearStatus;
|
||||
use CodeIgniter\Database\BaseConnection;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearManagementService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
private readonly ConfigurationModel $configurationModel,
|
||||
private readonly SchoolYearTransitionLogModel $transitionLogModel,
|
||||
private readonly SchoolYearClosingBatchModel $closingBatchModel,
|
||||
private readonly SchoolYearValidationService $validationService,
|
||||
private readonly BaseConnection $db,
|
||||
) {
|
||||
}
|
||||
|
||||
public function createDraft(array $payload, ?int $userId = null): int
|
||||
{
|
||||
$payload = $this->metadataPayload($payload);
|
||||
$payload['status'] = SchoolYearStatus::DRAFT;
|
||||
$payload['created_by'] = $userId;
|
||||
$payload['updated_by'] = $userId;
|
||||
|
||||
$this->validationService->validateMetadata($payload);
|
||||
|
||||
$this->db->transStart();
|
||||
$id = $this->schoolYearModel->insert($payload, true);
|
||||
if ($id !== false) {
|
||||
$this->log((int) $id, null, SchoolYearStatus::DRAFT, 'create', $userId);
|
||||
}
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($id === false || $this->db->transStatus() === false) {
|
||||
throw new RuntimeException($this->firstModelError('Unable to create school year.'));
|
||||
}
|
||||
|
||||
return (int) $id;
|
||||
}
|
||||
|
||||
public function updateMetadata(int $id, array $payload, ?int $userId = null): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
$status = (string) $year['status'];
|
||||
|
||||
if (SchoolYearStatus::isReadonly($status) || $status === SchoolYearStatus::CLOSING) {
|
||||
throw new InvalidArgumentException('This school year is read-only and cannot be edited.');
|
||||
}
|
||||
|
||||
$payload = $this->metadataPayload($payload);
|
||||
$payload['updated_by'] = $userId;
|
||||
$this->validationService->validateMetadata($payload, $id);
|
||||
|
||||
$this->db->transStart();
|
||||
$updated = $this->schoolYearModel->update($id, $payload);
|
||||
if ($updated !== false) {
|
||||
$this->log($id, $status, $status, 'metadata_update', $userId);
|
||||
}
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($updated === false || $this->db->transStatus() === false) {
|
||||
throw new RuntimeException($this->firstModelError('Unable to update school year.'));
|
||||
}
|
||||
}
|
||||
|
||||
public function activate(int $id, ?int $userId = null): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
$from = (string) $year['status'];
|
||||
|
||||
if (! SchoolYearStatus::canTransition($from, SchoolYearStatus::ACTIVE)) {
|
||||
throw new InvalidArgumentException('Only draft or approved reopened school years can be activated.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$activeYears = $this->schoolYearModel->where('status', SchoolYearStatus::ACTIVE)->findAll();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
foreach ($activeYears as $activeYear) {
|
||||
if ((int) $activeYear['id'] === $id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update((int) $activeYear['id'], [
|
||||
'status' => SchoolYearStatus::CLOSING,
|
||||
'closing_started_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->log((int) $activeYear['id'], SchoolYearStatus::ACTIVE, SchoolYearStatus::CLOSING, 'activation_displaced_active_year', $userId, [
|
||||
'activated_school_year_id' => $id,
|
||||
]);
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update($id, [
|
||||
'status' => SchoolYearStatus::ACTIVE,
|
||||
'activated_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->configurationModel->setConfigValueByKey('school_year', (string) $year['name']);
|
||||
$this->log($id, $from, SchoolYearStatus::ACTIVE, 'activate', $userId);
|
||||
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to activate school year.');
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteDraft(int $id, ?int $userId = null): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
if (($year['status'] ?? '') !== SchoolYearStatus::DRAFT) {
|
||||
throw new InvalidArgumentException('Only unused draft school years can be deleted. Archive historical years instead.');
|
||||
}
|
||||
|
||||
if ($this->hasDependentRecords($id, (string) $year['name'])) {
|
||||
throw new InvalidArgumentException('This school year cannot be deleted because related data exists. Archive historical years instead.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$this->log($id, SchoolYearStatus::DRAFT, null, 'delete_draft', $userId);
|
||||
$this->schoolYearModel->delete($id);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to delete draft school year.');
|
||||
}
|
||||
}
|
||||
|
||||
public function archive(int $id, ?int $userId = null): void
|
||||
{
|
||||
$this->transition($id, SchoolYearStatus::ARCHIVED, 'archive', $userId, [
|
||||
'archived_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function reopen(int $id, string $reason, ?int $userId = null): void
|
||||
{
|
||||
if (trim($reason) === '') {
|
||||
throw new InvalidArgumentException('A reopen reason is required.');
|
||||
}
|
||||
|
||||
$this->transition($id, SchoolYearStatus::ACTIVE, 'reopen', $userId, [
|
||||
'metadata' => ['reason' => trim($reason)],
|
||||
]);
|
||||
}
|
||||
|
||||
public function latestTransitionByYear(): array
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_transition_logs')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->transitionLogModel
|
||||
->orderBy('created_at', 'DESC')
|
||||
->findAll();
|
||||
$latest = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$yearId = (int) ($row['school_year_id'] ?? 0);
|
||||
if ($yearId > 0 && ! isset($latest[$yearId])) {
|
||||
$latest[$yearId] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
return $latest;
|
||||
}
|
||||
|
||||
public function log(int $schoolYearId, ?string $from, ?string $to, string $action, ?int $userId = null, array $metadata = []): void
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_transition_logs')) {
|
||||
throw new RuntimeException('School year lifecycle tables are missing. Run database migrations before changing school-year status.');
|
||||
}
|
||||
|
||||
$this->transitionLogModel->insert([
|
||||
'school_year_id' => $schoolYearId,
|
||||
'from_status' => $from,
|
||||
'to_status' => $to,
|
||||
'action' => $action,
|
||||
'performed_by' => $userId,
|
||||
'metadata_json' => $metadata !== [] ? json_encode($metadata, JSON_UNESCAPED_SLASHES) : null,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
|
||||
private function transition(int $id, string $to, string $action, ?int $userId, array $options = []): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
$from = (string) $year['status'];
|
||||
|
||||
if (! SchoolYearStatus::canTransition($from, $to)) {
|
||||
throw new InvalidArgumentException("Cannot transition school year from {$from} to {$to}.");
|
||||
}
|
||||
|
||||
if ($to === SchoolYearStatus::ARCHIVED && ! $this->hasFinalizedClosingBatch($id)) {
|
||||
throw new InvalidArgumentException('A school year can be archived only after a finalized closing batch exists.');
|
||||
}
|
||||
|
||||
if ($to === SchoolYearStatus::ACTIVE) {
|
||||
$otherActive = $this->schoolYearModel
|
||||
->where('status', SchoolYearStatus::ACTIVE)
|
||||
->where('id !=', $id)
|
||||
->first();
|
||||
if ($otherActive !== null) {
|
||||
throw new InvalidArgumentException('Another school year is already active. Activate or close years through the controlled lifecycle first.');
|
||||
}
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$data = [
|
||||
'status' => $to,
|
||||
'updated_by' => $userId,
|
||||
];
|
||||
|
||||
foreach (['archived_at', 'closed_at', 'closing_started_at'] as $field) {
|
||||
if (isset($options[$field])) {
|
||||
$data[$field] = $options[$field];
|
||||
}
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update($id, $data);
|
||||
$this->log($id, $from, $to, $action, $userId, $options['metadata'] ?? []);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to update school year status.');
|
||||
}
|
||||
}
|
||||
|
||||
private function requireYear(int $id): array
|
||||
{
|
||||
$year = $this->schoolYearModel->find($id);
|
||||
if ($year === null) {
|
||||
throw new InvalidArgumentException('School year not found.');
|
||||
}
|
||||
|
||||
return $year;
|
||||
}
|
||||
|
||||
private function metadataPayload(array $payload): array
|
||||
{
|
||||
return [
|
||||
'name' => trim((string) ($payload['name'] ?? '')),
|
||||
'starts_on' => $this->nullableDate($payload['starts_on'] ?? null),
|
||||
'ends_on' => $this->nullableDate($payload['ends_on'] ?? null),
|
||||
'description' => trim((string) ($payload['description'] ?? '')) ?: null,
|
||||
'registration_starts_on' => $this->nullableDate($payload['registration_starts_on'] ?? null),
|
||||
'registration_ends_on' => $this->nullableDate($payload['registration_ends_on'] ?? null),
|
||||
'previous_school_year_id' => $this->nullableInt($payload['previous_school_year_id'] ?? null),
|
||||
];
|
||||
}
|
||||
|
||||
private function nullableDate(mixed $value): ?string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
|
||||
return $value !== '' ? $value : null;
|
||||
}
|
||||
|
||||
private function nullableInt(mixed $value): ?int
|
||||
{
|
||||
return is_numeric($value) && (int) $value > 0 ? (int) $value : null;
|
||||
}
|
||||
|
||||
private function hasDependentRecords(int $id, string $name): bool
|
||||
{
|
||||
if (
|
||||
$this->db->tableExists('school_year_closing_batches')
|
||||
&& $this->closingBatchModel->where('source_school_year_id', $id)->orWhere('target_school_year_id', $id)->first() !== null
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach (['invoices', 'payments', 'student_class', 'teacher_class', 'calendar_events', 'events'] as $table) {
|
||||
if ($this->db->tableExists($table) && $this->db->fieldExists('school_year', $table)) {
|
||||
$count = $this->db->table($table)->where('school_year', $name)->countAllResults();
|
||||
if ($count > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function hasFinalizedClosingBatch(int $sourceSchoolYearId): bool
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_closing_batches')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->closingBatchModel
|
||||
->where('source_school_year_id', $sourceSchoolYearId)
|
||||
->whereIn('status', ['completed', 'closed'])
|
||||
->first() !== null;
|
||||
}
|
||||
|
||||
private function firstModelError(string $fallback): string
|
||||
{
|
||||
$errors = $this->schoolYearModel->errors();
|
||||
$first = reset($errors);
|
||||
|
||||
return is_string($first) && $first !== '' ? $first : $fallback;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SchoolYearModel;
|
||||
use DateTimeImmutable;
|
||||
use InvalidArgumentException;
|
||||
|
||||
final class SchoolYearValidationService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
) {
|
||||
}
|
||||
|
||||
public function validateMetadata(array $payload, ?int $exceptId = null): void
|
||||
{
|
||||
$name = trim((string) ($payload['name'] ?? ''));
|
||||
|
||||
if (! $this->isValidYearName($name)) {
|
||||
throw new InvalidArgumentException('School year must use YYYY-YYYY with consecutive years.');
|
||||
}
|
||||
|
||||
$existing = $this->schoolYearModel->where('name', $name);
|
||||
if ($exceptId !== null) {
|
||||
$existing->where('id !=', $exceptId);
|
||||
}
|
||||
if ($existing->first() !== null) {
|
||||
throw new InvalidArgumentException('That school year already exists.');
|
||||
}
|
||||
|
||||
$startsOn = $this->dateOrNull($payload['starts_on'] ?? null);
|
||||
$endsOn = $this->dateOrNull($payload['ends_on'] ?? null);
|
||||
if ($startsOn !== null && $endsOn !== null && $startsOn >= $endsOn) {
|
||||
throw new InvalidArgumentException('School year start date must be before the end date.');
|
||||
}
|
||||
|
||||
$registrationStarts = $this->dateOrNull($payload['registration_starts_on'] ?? null);
|
||||
$registrationEnds = $this->dateOrNull($payload['registration_ends_on'] ?? null);
|
||||
if ($registrationStarts !== null && $registrationEnds !== null && $registrationStarts > $registrationEnds) {
|
||||
throw new InvalidArgumentException('Registration start date must be on or before the registration end date.');
|
||||
}
|
||||
}
|
||||
|
||||
public function isValidYearName(string $value): bool
|
||||
{
|
||||
if (! preg_match('/^(\d{4})-(\d{4})$/', $value, $matches)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (int) $matches[2] === (int) $matches[1] + 1;
|
||||
}
|
||||
|
||||
private function dateOrNull(mixed $value): ?DateTimeImmutable
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
|
||||
if (! $date instanceof DateTimeImmutable || $date->format('Y-m-d') !== $value) {
|
||||
throw new InvalidArgumentException('Dates must use YYYY-MM-DD.');
|
||||
}
|
||||
|
||||
return $date;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\SchoolYear\SchoolYearContext;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearWriteGuard
|
||||
{
|
||||
public function assertWritable(
|
||||
SchoolYearContext $context,
|
||||
bool $allowDraftForAdmin = false,
|
||||
bool $isAdmin = false
|
||||
): void {
|
||||
if ($context->status() === 'active') {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($context->status() === 'draft' && $allowDraftForAdmin && $isAdmin) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new RuntimeException('The selected school year is read-only.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\SchoolYear;
|
||||
|
||||
final class SchoolYearContext
|
||||
{
|
||||
public function __construct(
|
||||
private readonly int $id,
|
||||
private readonly string $yearName,
|
||||
private readonly string $status,
|
||||
private readonly bool $explicitSelection = false,
|
||||
) {
|
||||
}
|
||||
|
||||
public function id(): int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function yearName(): string
|
||||
{
|
||||
return $this->yearName;
|
||||
}
|
||||
|
||||
public function status(): string
|
||||
{
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->status === 'active';
|
||||
}
|
||||
|
||||
public function isReadonly(): bool
|
||||
{
|
||||
return in_array($this->status, ['closed', 'archived'], true);
|
||||
}
|
||||
|
||||
public function isExplicitSelection(): bool
|
||||
{
|
||||
return $this->explicitSelection;
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'name' => $this->yearName,
|
||||
'status' => $this->status,
|
||||
'readonly' => $this->isReadonly(),
|
||||
'explicitSelection' => $this->explicitSelection,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\SchoolYear;
|
||||
|
||||
final class SchoolYearStatus
|
||||
{
|
||||
public const DRAFT = 'draft';
|
||||
public const ACTIVE = 'active';
|
||||
public const CLOSING = 'closing';
|
||||
public const CLOSED = 'closed';
|
||||
public const ARCHIVED = 'archived';
|
||||
|
||||
public const ALL = [
|
||||
self::DRAFT,
|
||||
self::ACTIVE,
|
||||
self::CLOSING,
|
||||
self::CLOSED,
|
||||
self::ARCHIVED,
|
||||
];
|
||||
|
||||
public const TRANSITIONS = [
|
||||
self::DRAFT => [self::ACTIVE],
|
||||
self::ACTIVE => [self::CLOSING],
|
||||
self::CLOSING => [self::ACTIVE, self::CLOSED],
|
||||
self::CLOSED => [self::ACTIVE, self::ARCHIVED],
|
||||
self::ARCHIVED => [],
|
||||
];
|
||||
|
||||
public static function canTransition(string $from, string $to): bool
|
||||
{
|
||||
return in_array($to, self::TRANSITIONS[$from] ?? [], true);
|
||||
}
|
||||
|
||||
public static function isReadonly(string $status): bool
|
||||
{
|
||||
return in_array($status, [self::CLOSED, self::ARCHIVED], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\SchoolYear;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
final class SchoolYearTableRegistry
|
||||
{
|
||||
public const YEAR_SCOPED = [
|
||||
'additional_charges',
|
||||
'archived_paypal_transactions',
|
||||
'attendance_data',
|
||||
'attendance_day',
|
||||
'attendance_record',
|
||||
'attendance_tracking',
|
||||
'badge_print_logs',
|
||||
'below_sixty_decisions',
|
||||
'calendar_events',
|
||||
'certificate_records',
|
||||
'classSection',
|
||||
'class_progress_reports',
|
||||
'competitions',
|
||||
'current_flag',
|
||||
'discount_vouchers',
|
||||
'early_dismissal_signatures',
|
||||
'enrollments',
|
||||
'events',
|
||||
'exams',
|
||||
'exam_drafts',
|
||||
'expenses',
|
||||
'final_exam',
|
||||
'final_score',
|
||||
'flag',
|
||||
'grading_locks',
|
||||
'homework',
|
||||
'inventory_movements',
|
||||
'invoices',
|
||||
'late_slip_logs',
|
||||
'manual_payments',
|
||||
'midterm_exam',
|
||||
'missing_score_overrides',
|
||||
'parent_attendance_reports',
|
||||
'parent_meeting_schedules',
|
||||
'parent_notifications',
|
||||
'participation',
|
||||
'payments',
|
||||
'payment_transactions',
|
||||
'placement_batches',
|
||||
'print_requests',
|
||||
'project',
|
||||
'quiz',
|
||||
'refunds',
|
||||
'reimbursements',
|
||||
'reimbursement_batches',
|
||||
'report_card_acknowledgements',
|
||||
'scan_log',
|
||||
'score_comments',
|
||||
'semester_scores',
|
||||
'staff_attendance',
|
||||
'student_class',
|
||||
'student_decisions',
|
||||
'teacher_attendance_data',
|
||||
'teacher_class',
|
||||
'teacher_submission_notification_history',
|
||||
'whatsapp_group_links',
|
||||
'whatsapp_group_memberships',
|
||||
];
|
||||
|
||||
public const GLOBAL = [
|
||||
'authorized_users',
|
||||
'cache',
|
||||
'cache_locks',
|
||||
'configuration',
|
||||
'email_templates',
|
||||
'ip_attempts',
|
||||
'login_activity',
|
||||
'migrations',
|
||||
'nav_items',
|
||||
'parent_accounts',
|
||||
'password_reset_requests',
|
||||
'password_resets',
|
||||
'permissions',
|
||||
'personal_access_tokens',
|
||||
'preferences',
|
||||
'role_nav_items',
|
||||
'role_permissions',
|
||||
'roles',
|
||||
'school_years',
|
||||
'sessions',
|
||||
'settings',
|
||||
'user_preferences',
|
||||
'user_roles',
|
||||
'users',
|
||||
];
|
||||
|
||||
public const IDENTITY_WITH_YEAR_RELATION = [
|
||||
'emergency_contacts',
|
||||
'families',
|
||||
'family_guardians',
|
||||
'family_students',
|
||||
'parents',
|
||||
'staff',
|
||||
'student_allergies',
|
||||
'student_medical_conditions',
|
||||
'students',
|
||||
'teachers',
|
||||
];
|
||||
|
||||
public const CONTEXT = [
|
||||
'audit_logs',
|
||||
'communication_logs',
|
||||
'contactus',
|
||||
'finance_notification_logs',
|
||||
'messages',
|
||||
'notification_recipients',
|
||||
'notifications',
|
||||
'payment_notification_logs',
|
||||
'support_requests',
|
||||
'user_notifications',
|
||||
];
|
||||
|
||||
public static function isYearScoped(string $table): bool
|
||||
{
|
||||
return in_array($table, self::YEAR_SCOPED, true);
|
||||
}
|
||||
|
||||
public static function isGlobal(string $table): bool
|
||||
{
|
||||
return in_array($table, self::GLOBAL, true);
|
||||
}
|
||||
|
||||
public static function isIdentityWithYearRelation(string $table): bool
|
||||
{
|
||||
return in_array($table, self::IDENTITY_WITH_YEAR_RELATION, true);
|
||||
}
|
||||
|
||||
public static function isContext(string $table): bool
|
||||
{
|
||||
return in_array($table, self::CONTEXT, true);
|
||||
}
|
||||
|
||||
public static function categoryOf(string $table): string
|
||||
{
|
||||
return match (true) {
|
||||
self::isYearScoped($table) => 'YEAR_SCOPED',
|
||||
self::isGlobal($table) => 'GLOBAL',
|
||||
self::isIdentityWithYearRelation($table) => 'IDENTITY_WITH_YEAR_RELATION',
|
||||
self::isContext($table) => 'CONTEXT',
|
||||
default => throw new InvalidArgumentException(
|
||||
"Table '{$table}' is not registered for school-year behavior."
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user