Compare commits

..

49 Commits

Author SHA1 Message Date
root 6e8da3cc2c fix batch issue 2026-06-08 23:20:06 -04:00
root 384ae8b719 fix the forecast tuition 2026-06-07 00:27:27 -04:00
root 654453222f financial fix 2026-06-06 23:30:41 -04:00
root a18e8b92a6 fix batch 2026-06-04 23:09:58 -04:00
root 6444b61416 fix financial issues 2026-06-01 02:08:27 -04:00
root 090cb88573 fix attendance coemment in report card 2026-05-30 17:12:10 -04:00
root 95bcefc3a9 fix decision email 2026-05-30 16:55:20 -04:00
root f24f4311e8 fix delibration and below 60 2026-05-30 15:00:16 -04:00
root 89913d7473 add trophy winner name print 2026-05-30 03:58:59 -04:00
root 079c869477 fix ties 2026-05-30 03:29:48 -04:00
root 9ee75fe4cc fix decisions and rank 2026-05-30 03:19:10 -04:00
root fcfa56b3f5 fix below 60 pages 2026-05-30 02:17:47 -04:00
root 39ab0d113e fix score comments 2026-05-29 01:52:17 -04:00
root ce56c96cdd fix paste button for comment review spring 2026-05-29 00:18:12 -04:00
root b4a06903e2 fix certificate qr code verification 2026-05-28 02:15:08 -04:00
root 0654668530 fix report ranking 2026-05-28 01:55:34 -04:00
root 3737b3522d fix reportcard and certificate 2026-05-27 14:11:08 -04:00
root c294d7bed7 fix logo 2026-05-26 23:14:55 -04:00
root 5ed65a867c report cadr and trophy 2026-05-26 05:11:10 -04:00
root 22d6f960ea move qr code inside the certificate 2026-05-26 03:09:48 -04:00
root cc0b83c1b9 fix attendance spring days 2026-05-26 03:03:03 -04:00
root 31976752da fix font 2026-05-26 02:13:39 -04:00
root 0bf8d13777 fix certificates 2026-05-26 01:44:57 -04:00
root 4ae62e37a3 test new server 2026-05-22 00:58:43 -04:00
root d8fdbeb4c3 fix certificate qr 2026-05-21 18:37:39 -04:00
root 239d35f8ff fix the event print and certificate qr 2026-05-21 17:00:38 -04:00
root 3333e71c94 add qr code to certificate 2026-05-17 17:24:07 -04:00
root af75475214 add certificate generation 2026-05-17 17:04:47 -04:00
root a8ef665239 fix event parent list 2026-05-16 16:03:46 -04:00
root 7c97a60795 add trophy prediction and treshold 2026-05-16 15:35:56 -04:00
root acca87c77b fix tracking attendance 2026-05-09 15:51:34 -04:00
root 9aacbe8972 fix draft exam upload 2026-05-08 00:33:40 -04:00
root 76866ffe1e update login scurity 2026-05-08 00:17:42 -04:00
root b01a4496e6 fixexam files 2026-05-06 18:45:13 -04:00
root 1f51be91e4 fix external kids for events 2026-05-05 22:37:32 -04:00
root 92016f90d0 fix issues on examdraft view and event print page 2026-05-05 01:38:20 -04:00
root 45d7895182 add waiver column to event table 2026-04-19 12:32:30 -04:00
root 596d368b1d fix event issues 2026-04-19 12:05:10 -04:00
root 35988e9ce1 fix logs issues 2026-04-18 11:44:02 -04:00
root 5fc4d8be30 fix double cote issue 2026-04-18 11:33:48 -04:00
root dcfd1f9542 fix users page 2026-04-18 11:29:18 -04:00
root b99f816261 update gitignore 2026-04-18 11:14:08 -04:00
root 931e30b6f1 update gitignore 2026-04-18 11:13:55 -04:00
root 189bb1a628 fix redirect page 2026-04-18 11:06:31 -04:00
root f04934039e add email sent for event 2026-04-18 10:51:22 -04:00
root c13dcb07d1 add event to calendar 2026-04-18 10:18:06 -04:00
root dd1d492c30 fix event charge and invoice update 2026-04-18 09:54:29 -04:00
root a448288878 update event charge as cash payment 2026-04-13 01:42:33 -04:00
root 821e9cdc81 update event charge at the invoice 2026-04-13 01:38:40 -04:00
2637 changed files with 19352 additions and 6619 deletions
-184
View File
@@ -1,184 +0,0 @@
#--------------------------------------------------------------------
# Example Environment Configuration file
#
# This file can be used as a starting point for your own
# custom .env files, and contains most of the possible settings
# available in a default install.
#
# By default, all of the settings are commented out. If you want
# to override the setting, you must un-comment it by removing the '#'
# at the beginning of the line.
#--------------------------------------------------------------------
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------
CI_ENVIRONMENT = development
# Which profile to use if none is supplied to sendEmail()
# Options: default, communication, payment, ...
MAIL_PROFILE_DEFAULT=default
# ===== DEFAULT (system) =====
# ---- Legacy fallbacks (kept for compatibility) ----
SMTP_HOST = smtp.gmail.com
SMTP_USER = alrahma.sunday.school@gmail.com
SMTP_PASS = "psnp emdq dykw ypul"
SMTP_PORT = 587
SMTP_ENCRYPTION = tls # was ssl; use tls for port 587
# Reply-To for all mail profiles
MAIL_DEFAULT_REPLY_TO=alrahma.isgl@gmail.com
MAIL_DEFAULT_REPLY_TO_NAME="Al Rahma Sunday School"
MAIL_COMMUNICATION_REPLY_TO=alrahma.isgl@gmail.com
MAIL_COMMUNICATION_REPLY_TO_NAME="School Communications"
MAIL_PAYMENT_REPLY_TO=alrahma.isgl@gmail.com
MAIL_PAYMENT_REPLY_TO_NAME="School Payments"
# Optional sender directory you already use elsewhere
MAIL_SENDERS="{\"general\":{\"email\":\"alrahma.isgl@gmail.com\",\"name\":\"Al Rahma No-Reply\"},\
\"registration\":{\"email\":\"alrahma.isgl@gmail.com\",\"name\":\"Al Rahma Register Office\"},\
\"notifications\":{\"email\":\"alrahma.isgl@gmail.com\",\"name\":\"Al Rahma Notifications\"},\
\"finance\":{\"email\":\"alrahma.isgl@gmail.com\",\"name\":\"Al Rahma Finance Office\"}}"
# Principal notification recipient for TimeOff requests (comma-separated allowed)
PRINCIPAL_EMAIL="melabidi@alrahmaisgl.org"
MAIL_PARENT_REPORT_TO="alrahma.isgl@gmail.com"
MAIL_FROM_ADDRESS = "alrahma.sunday.school@gmail.com"
session.expiration = 43200
#--------------------------------------------------------------------
# APP
#--------------------------------------------------------------------
# If you have trouble with `.`, you could also use `_`.
app_baseURL = 'http://localhost:8080/'
# app.forceGlobalSecureRequests = true
# app.CSPEnabled = false
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = 127.0.0.1
database.default.database = school
database.default.username = root
database.default.password = rootpassword
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
#--------------------------------------------------------------------
# CONTENT SECURITY POLICY
#--------------------------------------------------------------------
# contentsecuritypolicy.reportOnly = false
# contentsecuritypolicy.defaultSrc = 'none'
# contentsecuritypolicy.scriptSrc = 'self'
# contentsecuritypolicy.styleSrc = 'self'
# contentsecuritypolicy.imageSrc = 'self'
# contentsecuritypolicy.baseURI = null
# contentsecuritypolicy.childSrc = null
# contentsecuritypolicy.connectSrc = 'self'
# contentsecuritypolicy.fontSrc = null
# contentsecuritypolicy.formAction = null
# contentsecuritypolicy.frameAncestors = null
# contentsecuritypolicy.frameSrc = null
# contentsecuritypolicy.mediaSrc = null
# contentsecuritypolicy.objectSrc = null
# contentsecuritypolicy.pluginTypes = null
# contentsecuritypolicy.reportURI = null
# contentsecuritypolicy.sandbox = false
# contentsecuritypolicy.upgradeInsecureRequests = false
# contentsecuritypolicy.styleNonceTag = '{csp-style-nonce}'
# contentsecuritypolicy.scriptNonceTag = '{csp-script-nonce}'
# contentsecuritypolicy.autoNonce = true
#--------------------------------------------------------------------
# COOKIE
#--------------------------------------------------------------------
# cookie.prefix = ''
# cookie.expires = 0
# cookie.path = '/'
# cookie.domain = ''
# cookie.secure = false
# cookie.httponly = false
# cookie.samesite = 'Lax'
# cookie.raw = false
#--------------------------------------------------------------------
# ENCRYPTION
#--------------------------------------------------------------------
# encryption.key =
# encryption.driver = OpenSSL
# encryption.blockSize = 16
# encryption.digest = SHA512
#--------------------------------------------------------------------
# HONEYPOT
#--------------------------------------------------------------------
# honeypot.hidden = 'true'
# honeypot.label = 'Fill This Field'
# honeypot.name = 'honeypot'
# honeypot.template = '<label>{label}</label><input type="text" name="{name}" value=""/>'
# honeypot.container = '<div style="display:none">{template}</div>'
#--------------------------------------------------------------------
# SECURITY
#--------------------------------------------------------------------
# security.csrfProtection = 'cookie'
# security.tokenRandomize = false
# security.tokenName = 'csrf_token_name'
# security.headerName = 'X-CSRF-TOKEN'
# security.cookieName = 'csrf_cookie_name'
# security.expires = 7200
# security.regenerate = true
# security.redirect = false
# security.samesite = 'Lax'
#--------------------------------------------------------------------
# SESSION
#--------------------------------------------------------------------
# session.driver = 'CodeIgniter\Session\Handlers\FileHandler'
# session.cookieName = 'ci_session'
# session.expiration = 7200
# session.savePath = null
# session.matchIP = false
# session.timeToUpdate = 300
# session.regenerateDestroy = false
#--------------------------------------------------------------------
# LOGGER
#--------------------------------------------------------------------
logger.threshold = 4
MAIL_DEBUG = true
MAIL_TIMEOUT = 15
#--------------------------------------------------------------------
# CURLRequest
#--------------------------------------------------------------------
# curlrequest.shareOptions = false
mail.protocol = smtp
mail.SMTPHost = ${SMTP_HOST}
mail.SMTPUser = ${SMTP_USER}
mail.SMTPPass = ${SMTP_PASS}
mail.SMTPPort = ${SMTP_PORT}
mail.SMTPCrypto = tls
mail.fromEmail = ${SMTP_USER}
mail.fromName = "Al Rahma Sunday School"
mail.mailType = text
mail.charset = UTF-8
+15
View File
@@ -23,17 +23,32 @@
/public/build/ /public/build/
/public/hot/ /public/hot/
/public/uploads/**
!/public/uploads/**/index.html
!/public/uploads/.gitkeep
/uploads/**
!/uploads/**/index.html
!/uploads/.gitkeep
docker-compose.override.yml docker-compose.override.yml
docker-compose.local.yml docker-compose.local.yml
*.log *.log
.swp
.swo
*~
.tmp
.DS_Store .DS_Store
Thumbs.db Thumbs.db
.idea/ .idea/
.vscode/ .vscode/
.codex/
/coverage/ /coverage/
/build/ /build/
/builds
/phpunit.xml.cache /phpunit.xml.cache
/.phpunit.result.cache /.phpunit.result.cache
/writable/reports/*
/writable/test.txt
View File
+171
View File
@@ -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;
}
}
-232
View File
@@ -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();
$this->semester = $this->configModel->getConfig('semester');
$this->schoolYear = $this->configModel->getConfig('school_year');
}
public function run(array $params)
{
$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();
}
}
}
+1 -1
View File
@@ -16,11 +16,11 @@ class Commands extends BaseService
\App\Commands\CleanupPasswordResets::class, \App\Commands\CleanupPasswordResets::class,
\App\Commands\ConfigUpdate::class, \App\Commands\ConfigUpdate::class,
\App\Commands\DeleteInactiveUsers::class, \App\Commands\DeleteInactiveUsers::class,
\App\Commands\RecalculateInvoices::class,
\App\Commands\SendAbsenteesSummary::class, \App\Commands\SendAbsenteesSummary::class,
\App\Commands\SendLatesSummary::class, \App\Commands\SendLatesSummary::class,
\App\Commands\SendMonthlyPaymentNotifications::class, \App\Commands\SendMonthlyPaymentNotifications::class,
\App\Commands\SendTestPaymentNotification::class, \App\Commands\SendTestPaymentNotification::class,
\App\Commands\SyncPaypalPayments::class,
\App\Commands\RecalculateAttendance::class, \App\Commands\RecalculateAttendance::class,
]; ];
+2
View File
@@ -9,6 +9,7 @@ use App\Listeners\SchoolEventListener;
use App\Listeners\AttendanceConsequenceListener; use App\Listeners\AttendanceConsequenceListener;
use App\Listeners\WhatsappInviteListener; use App\Listeners\WhatsappInviteListener;
use App\Listeners\BelowSixtyEmailListener; use App\Listeners\BelowSixtyEmailListener;
use App\Listeners\DecisionEmailListener;
// Create an instance so we can use $this->emailService like your other handlers // Create an instance so we can use $this->emailService like your other handlers
$waListener = new WhatsappInviteListener(service('emailService')); $waListener = new WhatsappInviteListener(service('emailService'));
@@ -118,6 +119,7 @@ Events::on('attendance.follow_up', [AttendanceConsequenceListener::class, 'fol
Events::on('attendance.final_warning', [AttendanceConsequenceListener::class, 'finalWarning']); Events::on('attendance.final_warning', [AttendanceConsequenceListener::class, 'finalWarning']);
Events::on('attendance.dismissal', [AttendanceConsequenceListener::class, 'dismissal']); Events::on('attendance.dismissal', [AttendanceConsequenceListener::class, 'dismissal']);
Events::on('below60.email', [BelowSixtyEmailListener::class, 'handle']); Events::on('below60.email', [BelowSixtyEmailListener::class, 'handle']);
Events::on('below60.decision_email', [DecisionEmailListener::class, 'handle']);
//Whatsapp Event listener //Whatsapp Event listener
Events::on('whatsapp_invites.send', [$waListener, 'handle']); Events::on('whatsapp_invites.send', [$waListener, 'handle']);
+6 -5
View File
@@ -24,6 +24,8 @@ class Filters extends BaseConfig
'honeypot' => Honeypot::class, 'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class, 'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class, 'secureheaders' => SecureHeaders::class,
'sanitizeinput' => \App\Filters\SanitizeInputFilter::class,
'apiratelimit' => \App\Filters\ApiRateLimitFilter::class,
'auth' => \App\Filters\AuthFilter::class, // Define the alias for your auth filter 'auth' => \App\Filters\AuthFilter::class, // Define the alias for your auth filter
'apiAuth' => \App\Filters\ApiAuthFilter::class, // JWT-based API authentication 'apiAuth' => \App\Filters\ApiAuthFilter::class, // JWT-based API authentication
'cleanupScheduler' => \App\Filters\CleanupScheduler::class, 'cleanupScheduler' => \App\Filters\CleanupScheduler::class,
@@ -42,11 +44,9 @@ class Filters extends BaseConfig
public array $globals = [ public array $globals = [
'before' => [ 'before' => [
'timezone', 'timezone',
'sanitizeinput',
'invalidchars',
'csrf' => ['except' => [ 'csrf' => ['except' => [
// Webhooks / integrations
'api/paypal-webhook',
'index.php/api/paypal-webhook',
// WhatsApp membership management (legacy allowances retained) // WhatsApp membership management (legacy allowances retained)
'whatsapp/update-membership', 'whatsapp/update-membership',
'index.php/whatsapp/update-membership', 'index.php/whatsapp/update-membership',
@@ -80,6 +80,7 @@ class Filters extends BaseConfig
]], ]],
], ],
'after' => [ 'after' => [
'secureheaders',
'toolbar', 'toolbar',
'cleanupScheduler' => ['except' => ['cleanup/*']], 'cleanupScheduler' => ['except' => ['cleanup/*']],
], ],
@@ -112,7 +113,7 @@ class Filters extends BaseConfig
* @var array<string, array<string, list<string>>> * @var array<string, array<string, list<string>>>
*/ */
public array $filters = [ public array $filters = [
'apiratelimit' => ['before' => ['api/*', 'index.php/api/*']],
]; ];
} }
+1
View File
@@ -9,6 +9,7 @@ use CodeIgniter\Format\XMLFormatter;
class Format extends BaseConfig class Format extends BaseConfig
{ {
public int $jsonEncodeDepth = 512;
/** /**
* -------------------------------------------------------------------------- * --------------------------------------------------------------------------
* Available Response Formats * Available Response Formats
-13
View File
@@ -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
}
+99 -75
View File
@@ -174,6 +174,18 @@ $routes->group('administrator/subject-curriculum', ['filter' => 'auth:update_cur
$routes->post('delete/(:num)', 'View\SubjectCurriculumController::delete/$1'); $routes->post('delete/(:num)', 'View\SubjectCurriculumController::delete/$1');
}); });
$routes->get('administrator/trophy', 'View\TrophyController::index', ['filter' => 'auth:admin']);
$routes->get('administrator/trophy/winners', 'View\TrophyController::winners', ['filter' => 'auth:admin']);
$routes->get('administrator/trophy/final', 'View\TrophyController::final', ['filter' => 'auth:admin']);
// Certificates
$routes->get('administrator/certificates', 'View\CertificateController::index', ['filter' => 'auth:admin']);
$routes->get('administrator/certificates/csrf-token', 'View\CertificateController::csrfToken', ['filter' => 'auth:admin']);
$routes->post('administrator/certificates/generate', 'View\CertificateController::generate', ['filter' => 'auth:admin']);
$routes->get('administrator/certificates/log', 'View\CertificateController::auditLog', ['filter' => 'auth:admin']);
$routes->get('administrator/certificates/reprint/(:any)', 'View\CertificateController::reprint/$1', ['filter' => 'auth:read']);
$routes->get('verify/(:segment)', 'View\CertificateController::verify/$1');
/* /*
@@ -245,15 +257,17 @@ $routes->post('administrator/sections/auto-distribute', 'View\StudentController:
$routes->get('administrator/sections/promotion-totals', 'View\StudentController::promotionTotalsApi'); $routes->get('administrator/sections/promotion-totals', 'View\StudentController::promotionTotalsApi');
$routes->get('refunds/list', 'View\RefundController::listRefunds'); $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'); $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'); $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'); $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'); $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'); $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'); $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'); $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'); $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']);
@@ -393,8 +407,8 @@ $routes->get('print-requests/file/(:segment)', 'PrintRequests::serveFile/$1', ['
$routes->get('print-requests/file/(:segment)/(:alpha)', 'PrintRequests::serveFile/$1/$2', ['filter' => 'auth:teacher,teacher_assistant,admin']); $routes->get('print-requests/file/(:segment)/(:alpha)', 'PrintRequests::serveFile/$1/$2', ['filter' => 'auth:teacher,teacher_assistant,admin']);
$routes->get('uploads/print_requests/(:segment)', 'PrintRequests::serveFile/$1', ['filter' => 'auth:teacher,teacher_assistant,admin']); $routes->get('uploads/print_requests/(:segment)', 'PrintRequests::serveFile/$1', ['filter' => 'auth:teacher,teacher_assistant,admin']);
$routes->get('exam-drafts/files/teacher/(:segment)', 'View\FilesController::examDraftTeacher/$1', ['filter' => 'auth:teacher,teacher_assistant,admin']); $routes->get('exam-drafts/files/teacher/(:segment)', 'View\FilesController::examDraftTeacher/$1', ['filter' => 'auth:teacher,teacher_assistant,admin,administrator,principal']);
$routes->get('exam-drafts/files/final/(:segment)', 'View\FilesController::examDraftFinal/$1', ['filter' => 'auth:teacher,teacher_assistant,admin']); $routes->get('exam-drafts/files/final/(:segment)', 'View\FilesController::examDraftFinal/$1', ['filter' => 'auth:teacher,teacher_assistant,admin,administrator,principal']);
@@ -511,13 +525,31 @@ $routes->post('grading/below-60/email', 'View\GradingController::sendBelowSixtyE
$routes->post('grading/below-60/status', 'View\GradingController::updateBelowSixtyStatus', ['filter' => 'auth:read']); $routes->post('grading/below-60/status', 'View\GradingController::updateBelowSixtyStatus', ['filter' => 'auth:read']);
$routes->get('grading/below-60/schedule', 'View\GradingController::scheduleBelowSixty', ['filter' => 'auth:read']); $routes->get('grading/below-60/schedule', 'View\GradingController::scheduleBelowSixty', ['filter' => 'auth:read']);
$routes->post('grading/below-60/schedule', 'View\GradingController::saveBelowSixtyMeeting', ['filter' => 'auth:read']); $routes->post('grading/below-60/schedule', 'View\GradingController::saveBelowSixtyMeeting', ['filter' => 'auth:read']);
$routes->get('grading/decisions', 'View\GradingController::allDecisions', ['filter' => 'auth:read']);
$routes->post('grading/decisions/generate', 'View\GradingController::generateAllDecisions', ['filter' => 'auth:read']);
$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::previewBelowSixtyDecisionEmail',
['filter' => 'auth:read']
);
$routes->post(
'grading/below-60/decisions/email',
'View\GradingController::sendBelowSixtyDecisionEmail',
['filter' => 'auth:read']
);
// Final part // Final part
$routes->get('grading/(:segment)/(:num)/(:num)', 'View\GradingController::show/$1/$2/$3'); $routes->get('grading/(:segment)/(:num)/(:num)', 'View\GradingController::show/$1/$2/$3');
$routes->post('grading/update', 'View\GradingController::update'); $routes->post('grading/update', 'View\GradingController::update');
$routes->get('grading', 'View\GradingController::grading'); $routes->get('grading', 'View\GradingController::grading');
$routes->post('grading/toggle-score-lock', 'View\GradingController::toggleScoreLock', ['filter' => 'auth:read']); $routes->post('grading/toggle-score-lock', 'View\GradingController::toggleScoreLock', ['filter' => 'auth:read']);
$routes->get('grading/toggle-score-lock', static function () {
return 'GET route hit. Something is calling this route incorrectly.';
});
$routes->post('grading/lock-all-scores', 'View\GradingController::lockAllScores', ['filter' => 'auth:read']); $routes->post('grading/lock-all-scores', 'View\GradingController::lockAllScores', ['filter' => 'auth:read']);
$routes->post('grading/release-scores', 'View\GradingController::toggleParentScoresRelease', ['filter' => 'auth:read']); $routes->post('grading/release-scores', 'View\GradingController::toggleParentScoresRelease', ['filter' => 'auth:read']);
$routes->post('grading/refresh-semester-scores', 'View\GradingController::refreshSemesterScores', ['filter' => 'auth:read']); $routes->post('grading/refresh-semester-scores', 'View\GradingController::refreshSemesterScores', ['filter' => 'auth:read']);
@@ -535,9 +567,13 @@ $routes->post('payment/event_charges', 'View\EventController::eventUpdate');
// Parent event participation // Parent event participation
$routes->get('administrator/event-charges', 'View\EventController::eventShow'); $routes->get('administrator/event-charges', 'View\EventController::eventShow');
$routes->get('administrator/event-charges/pdf', 'View\EventController::eventChargesPdf');
$routes->post('administrator/event-charges/remove/(:num)', 'View\EventController::removeCharge/$1');
$routes->post('administrator/event-charges/payment/(:num)', 'View\EventController::toggleEventPayment/$1');
$routes->post('administrator/event-charges/waiver/(:num)', 'View\EventController::toggleWaiverStatus/$1');
$routes->get('administrator/get-students-with-charges', 'View\EventController::getStudentsWithCharges'); $routes->get('administrator/get-students-with-charges', 'View\EventController::getStudentsWithCharges');
$routes->get('parent/events', 'View\ParentController::parentEventPage'); $routes->get('parent/events', 'View\ParentController::parentEventPage', ['filter' => 'auth:parent']);
// parent event participation page // parent event participation page
$routes->post('parent/updateParticipation', 'View\ParentController::updateParticipation'); // handle parent participation updates $routes->post('parent/updateParticipation', 'View\ParentController::updateParticipation'); // handle parent participation updates
@@ -552,19 +588,19 @@ $routes->post('invoices/updateStatus/(:num)', 'View\InvoiceController::updateSta
// app/Config/Routes.php // app/Config/Routes.php
$routes->group('payment', ['filter' => 'auth'], static function ($routes) { $routes->group('payment', ['filter' => 'auth'], static function ($routes) {
// Read // Read
$routes->get('manual_pay', 'View\PaymentController::manualPaySearch', ['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:read']); $routes->get('manual_pay_suggest', 'View\PaymentController::manualPaySuggest', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
// Create // 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 // Update
$routes->post('manual_pay_edit', 'View\PaymentController::manualPayEdit', ['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: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) // Read (serve files)
$routes->get('serveCheckFile/(:any)/(:any)', 'View\PaymentController::serveCheckFile/$1/$2', ['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('serveCheckFile/(:any)', 'View\PaymentController::serveCheckFile/$1', ['filter' => 'auth:read']); $routes->get('file/(:num)', 'View\PaymentController::servePaymentFile/$1', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
}); });
@@ -607,9 +643,14 @@ $routes->group('admin', ['filter' => 'auth'], static function ($routes) {
$routes->post('admin/broadcast-email/upload-image', 'View\BroadcastEmailController::uploadImage'); $routes->post('admin/broadcast-email/upload-image', 'View\BroadcastEmailController::uploadImage');
$routes->get('payment/financial_report', 'View\FinancialController::financialReport'); $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'); $routes->get('financial-report/financialReportSummary', 'View\FinancialController::financialReportSummary', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
$routes->get('payment/download_csv', 'View\FinancialController::downloadCsv'); $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'); $routes->get('reports/downloadFinancialReport', 'View\FinancialController::downloadFinancialReport');
// Financial APIs (JSON) // Financial APIs (JSON)
$routes->get('api/financial/report', 'View\FinancialController::financialReportData', ['filter' => 'auth']); $routes->get('api/financial/report', 'View\FinancialController::financialReportData', ['filter' => 'auth']);
@@ -620,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('api/financial/unpaid-parents', 'View\FinancialController::unpaidParents', ['filter' => 'auth:view_invoice']);
$routes->get('expenses/index', 'View\ExpenseController::index'); $routes->get('expenses/index', 'View\ExpenseController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
$routes->get('expenses/create', 'View\ExpenseController::create'); $routes->get('expenses/create', 'View\ExpenseController::create', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
$routes->post('expenses/store', 'View\ExpenseController::store'); $routes->post('expenses/store', 'View\ExpenseController::store', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,create']);
$routes->post('expenses/updateStatus', 'View\ExpenseController::updateStatus'); $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/index', 'View\ReimbursementController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
$routes->get('reimbursements/create', 'View\ReimbursementController::create'); $routes->get('reimbursements/create', 'View\ReimbursementController::create', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
$routes->post('reimbursements/store', 'View\ReimbursementController::store'); $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'); $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'); $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'); $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'); $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'); $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'); $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'); $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'); $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'); $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'); $routes->get('reimbursements/batch/export', 'View\ReimbursementController::exportBatch', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
$routes->post('reimbursements/process', 'View\ReimbursementController::process'); $routes->post('reimbursements/process', 'View\ReimbursementController::process', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
$routes->get('reimbursements/export', 'View\ReimbursementController::export'); $routes->get('reimbursements/export', 'View\ReimbursementController::export', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
$routes->get('reimbursements', 'View\ReimbursementController::index'); $routes->get('reimbursements', 'View\ReimbursementController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
// Health check (upload dirs + DB timezone columns) // Health check (upload dirs + DB timezone columns)
$routes->get('admin/health', 'View\HealthController::index'); $routes->get('admin/health', 'View\HealthController::index');
@@ -707,14 +748,9 @@ $routes->get('payment_transactions/getByPayment/(:num)', 'View\PaymentTransactio
$routes->get('payment_transactions/create', 'View\PaymentTransactionController::create'); $routes->get('payment_transactions/create', 'View\PaymentTransactionController::create');
$routes->post('payment_transactions/updateStatus/(:num)', 'View\PaymentTransactionController::updateStatus/$1'); $routes->post('payment_transactions/updateStatus/(:num)', 'View\PaymentTransactionController::updateStatus/$1');
// Routes for PayPal integration // Routes for payment pages
$routes->get('payments/createPaypalPayment/(:num)', 'View\PaymentController::createPaypalPayment/$1');
$routes->get('payments/executePaypalPayment', 'View\PaymentController::executePaypalPayment');
$routes->get('payments/cancelPaypalPayment', 'View\PaymentController::cancelPaypalPayment');
$routes->get('payments/view/(:num)', 'View\PaymentController::viewPayment/$1'); $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', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
$routes->get('payment/get_enrolled_students/(:num)', 'View\PaymentController::getEnrolledStudents/$1');
// Payment Notification Management // Payment Notification Management
$routes->get('payment/notification_management', 'View\PaymentNotificationController::index', ['filter' => 'auth:view_invoice']); $routes->get('payment/notification_management', 'View\PaymentNotificationController::index', ['filter' => 'auth:view_invoice']);
@@ -742,6 +778,9 @@ $routes->post('/administrator/teacher-submissions/notify', 'View\AdministratorCo
$routes->get('/administrator/exam-drafts', 'View\ExamDraftController::adminIndex', ['filter' => 'auth:admin']); $routes->get('/administrator/exam-drafts', 'View\ExamDraftController::adminIndex', ['filter' => 'auth:admin']);
$routes->post('/administrator/exam-drafts/review', 'View\ExamDraftController::adminReview', ['filter' => 'auth:admin']); $routes->post('/administrator/exam-drafts/review', 'View\ExamDraftController::adminReview', ['filter' => 'auth:admin']);
$routes->post('/administrator/exam-drafts/upload-legacy', 'View\ExamDraftController::adminUploadLegacy', ['filter' => 'auth:admin']); $routes->post('/administrator/exam-drafts/upload-legacy', 'View\ExamDraftController::adminUploadLegacy', ['filter' => 'auth:admin']);
$routes->get('/principal/exam-drafts', 'View\ExamDraftController::principalIndex', ['filter' => 'auth:admin']);
$routes->post('/principal/exam-drafts/review', 'View\ExamDraftController::principalReview', ['filter' => 'auth:admin']);
$routes->post('/principal/exam-drafts/upload-legacy', 'View\ExamDraftController::principalUploadLegacy', ['filter' => 'auth:admin']);
/* /*
* -------------------------------------------------------------------- * --------------------------------------------------------------------
@@ -931,15 +970,6 @@ $routes->group('inventory', ['filter' => 'csrf'], static function ($routes) {
$routes->get('admin/enrollment/new-students', 'View\AdministratorController::showNewStudents', ['filter' => 'auth:view_new_students']); $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 //Emergency Contact
$routes->get('administrator/emergency_contact', 'View\EmergencyContactController::index'); $routes->get('administrator/emergency_contact', 'View\EmergencyContactController::index');
$routes->get('administrator/emergency_contact/edit/(:num)', 'View\EmergencyContactController::edit/$1'); $routes->get('administrator/emergency_contact/edit/(:num)', 'View\EmergencyContactController::edit/$1');
@@ -1018,16 +1048,16 @@ $routes->get('family', 'View\FamilyAdminController::index');
////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////
//upload files //upload files
$routes->get('receipts/(:any)', 'View\FilesController::receipt/$1'); $routes->get('receipts/(:any)', 'View\FilesController::receipt/$1', ['filter' => 'auth']);
$routes->get('reimbreceipts/(:any)', 'View\FilesController::reimb/$1'); // serves from writable/uploads/reimbursements $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'); $routes->get('early-dismissal-signatures/(:any)', 'View\FilesController::earlyDismissalSignature/$1');
// Expenses // Expenses
$routes->get('expenses/edit/(:num)', 'View\ExpenseController::edit/$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'); $routes->post('expenses/update/(:num)', 'View\ExpenseController::update/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
// Reimbursements // Reimbursements
$routes->get('reimbursements/edit/(:num)', 'View\ReimbursementController::edit/$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'); $routes->post('reimbursements/update/(:num)', 'View\ReimbursementController::update/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
@@ -1172,16 +1202,15 @@ $routes->get('/terms_of_service', 'View\PageController::termsOfService');
$routes->get('/help_center', 'View\PageController::helpCenter'); $routes->get('/help_center', 'View\PageController::helpCenter');
//payment //payment
$routes->get('/payment', 'View\PaymentController::redirectPage'); $routes->get('/payment', 'View\PaymentController::redirectPage', ['filter' => 'auth:parent']);
$routes->get('/payment/paypal', 'View\PaymentController::paypal');
$routes->get('/payment/manual', 'View\PaymentController::manual'); $routes->get('/payment/manual', 'View\PaymentController::manual');
$routes->post('/payment/manual', 'View\PaymentController::manual'); $routes->post('/payment/manual', 'View\PaymentController::manual');
// Voucher management // Voucher management
$routes->get('discounts/list', 'View\DiscountController::listVouchers'); $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'); $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'); $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'); $routes->match(['get', 'post'], 'discount/apply', 'View\DiscountController::applyVoucher', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
@@ -1525,11 +1554,6 @@ $routes->group('api/v1', ['filter' => 'apiAuth', 'namespace' => 'App\Controllers
$routes->get('class-preparation/(:num)', 'View\SupportController::show/$1'); $routes->get('class-preparation/(:num)', 'View\SupportController::show/$1');
$routes->post('class-preparation/(:num)/mark-printed', 'View\SupportController::markPrinted/$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 // Stats
$routes->get('stats', 'View\UserController::index'); $routes->get('stats', 'View\UserController::index');
+1 -1
View File
@@ -36,7 +36,7 @@ class Services extends BaseService
/** /**
* Override CI Email service to enforce a global Reply-To. * Override CI Email service to enforce a global Reply-To.
*/ */
public static function email(array $config = null, bool $getShared = true) public static function email(?array $config = null, bool $getShared = true)
{ {
if ($getShared) { if ($getShared) {
return static::getSharedInstance('email', $config); return static::getSharedInstance('email', $config);
+123 -34
View File
@@ -5,7 +5,6 @@ namespace App\Controllers;
use App\Models\LoginActivityModel; use App\Models\LoginActivityModel;
use App\Models\UserModel; use App\Models\UserModel;
use App\Models\UserRoleModel; use App\Models\UserRoleModel;
use CodeIgniter\Controller;
use CodeIgniter\Events\Events; use CodeIgniter\Events\Events;
use App\Models\IpAttemptModel; use App\Models\IpAttemptModel;
use App\Models\PasswordResetModel; use App\Models\PasswordResetModel;
@@ -19,7 +18,7 @@ require_once APPPATH . 'Helpers/pbkdf2_helper.php';
require_once APPPATH . 'Helpers/jwt_helper.php'; require_once APPPATH . 'Helpers/jwt_helper.php';
class AuthController extends Controller class AuthController extends BaseController
{ {
protected $configModel; protected $configModel;
protected $userModel; protected $userModel;
@@ -56,17 +55,50 @@ class AuthController extends Controller
public function loginMask() public function loginMask()
{ {
// Serve the login view directly here $redirectTo = $this->sanitizeRedirectTarget((string) ($this->request->getGet('redirect_to') ?? ''));
return view('user/login'); // Adjust the view path as needed
if (session()->get('is_logged_in')) {
if ($redirectTo !== null) {
return redirect()->to($redirectTo);
}
$roles = session()->get('roles') ?? [];
if (empty($roles) && session()->get('role')) {
$roles = [session()->get('role')];
}
if (!empty($roles)) {
return $this->redirectToDashboard($roles);
}
}
return view('user/login', [
'redirect_to' => $redirectTo ?? '',
]);
} }
public function login() public function login()
{ {
log_message('info', 'Processing login form submission.'); log_message('info', 'Processing login form submission.');
$redirectTo = $this->sanitizeRedirectTarget((string) ($this->request->getPost('redirect_to') ?? $this->request->getGet('redirect_to') ?? ''));
$validator = \Config\Services::validation();
$requestData = sanitize_request_value($this->request->getPost(['email', 'password']));
$validator->setRules([
'email' => 'required|valid_email|max_length[254]',
'password' => 'required|max_length[255]',
]);
if (! $validator->run($requestData)) {
return redirect()
->back()
->with('error', 'Please enter a valid email and password.')
->withInput();
}
// Step 1: Get email, password, and IP from the request // Step 1: Get email, password, and IP from the request
$email = $this->request->getPost('email'); $email = strtolower((string) $requestData['email']);
$password = $this->request->getPost('password'); $password = (string) $requestData['password'];
$ip = $this->request->getIPAddress(); $ip = $this->request->getIPAddress();
log_message('info', 'Login attempt from IP: ' . $ip . ' for email: ' . $email); log_message('info', 'Login attempt from IP: ' . $ip . ' for email: ' . $email);
@@ -98,7 +130,7 @@ class AuthController extends Controller
$this->logLoginAttempt($user['id'], $user['email'], $ip, $this->request->getUserAgent()); $this->logLoginAttempt($user['id'], $user['email'], $ip, $this->request->getUserAgent());
// ✅ Step 7: Call loginUser() to set session and redirect // ✅ Step 7: Call loginUser() to set session and redirect
return $this->loginUser($user); return $this->loginUser($user, $redirectTo);
} else { } else {
// Step 8: Password mismatch — log failed attempt // Step 8: Password mismatch — log failed attempt
$this->handleFailedLogin($user['id'], $user['email'], $ip); $this->handleFailedLogin($user['id'], $user['email'], $ip);
@@ -120,26 +152,29 @@ class AuthController extends Controller
// JSON API: POST /api/login // JSON API: POST /api/login
public function apiLogin() public function apiLogin()
{ {
$requestData = $this->request->getJSON(true); $requestData = sanitize_request_value($this->request->getJSON(true) ?: [
if (!$requestData) { 'email' => $this->request->getPost('email'),
// fallback to form vars 'password' => $this->request->getPost('password'),
$requestData = [ ]);
'email' => $this->request->getPost('email'),
'password' => $this->request->getPost('password'),
];
}
$email = $requestData['email'] ?? ''; $validation = \Config\Services::validation();
$password = $requestData['password'] ?? ''; $validation->setRules([
$ip = $this->request->getIPAddress(); 'email' => 'required|valid_email|max_length[254]',
'password' => 'required|max_length[255]',
]);
if (!$email || !$password) { if (! $validation->run($requestData)) {
return $this->response->setStatusCode(400)->setJSON([ return $this->response->setStatusCode(422)->setJSON([
'status' => false, 'status' => false,
'message' => 'Email and password are required.' 'message' => 'Validation failed.',
'errors' => $validation->getErrors(),
]); ]);
} }
$email = strtolower((string) ($requestData['email'] ?? ''));
$password = (string) ($requestData['password'] ?? '');
$ip = $this->request->getIPAddress();
if ($this->isIpBlocked($ip)) { if ($this->isIpBlocked($ip)) {
return $this->response->setStatusCode(429)->setJSON([ return $this->response->setStatusCode(429)->setJSON([
'status' => false, 'status' => false,
@@ -201,7 +236,15 @@ class AuthController extends Controller
'exp' => $exp, 'exp' => $exp,
]; ];
$secret = env('JWT_SECRET', 'change-me-in-env'); try {
$secret = require_env('JWT_SECRET');
} catch (\RuntimeException $e) {
return $this->response->setStatusCode(500)->setJSON([
'status' => false,
'message' => 'JWT configuration is missing.',
]);
}
$token = jwt_encode($payload, $secret, 'HS256'); $token = jwt_encode($payload, $secret, 'HS256');
return $this->response->setJSON([ return $this->response->setJSON([
@@ -221,18 +264,14 @@ class AuthController extends Controller
*/ */
public function apiRegister() public function apiRegister()
{ {
$requestData = $this->request->getJSON(true); $requestData = sanitize_request_value($this->request->getJSON(true) ?: $this->request->getPost());
if (!$requestData) {
// fallback to form vars
$requestData = $this->request->getPost();
}
// Basic validation // Basic validation
$rules = [ $rules = [
'firstname' => 'required|min_length[2]|max_length[30]', 'firstname' => "required|regex_match[/^[\\p{L}\\s'\\-]+$/u]|min_length[2]|max_length[30]",
'lastname' => 'required|min_length[2]|max_length[30]', 'lastname' => "required|regex_match[/^[\\p{L}\\s'\\-]+$/u]|min_length[2]|max_length[30]",
'email' => 'required|valid_email|is_unique[users.email]', 'email' => 'required|valid_email|max_length[254]|is_unique[users.email]',
'password' => 'required|min_length[8]', 'password' => 'required|min_length[8]|max_length[255]',
'cellphone' => 'required|min_length[10]|max_length[20]', 'cellphone' => 'required|min_length[10]|max_length[20]',
]; ];
@@ -313,7 +352,7 @@ class AuthController extends Controller
'exp' => $exp, 'exp' => $exp,
]; ];
$secret = env('JWT_SECRET', 'change-me-in-env'); $secret = require_env('JWT_SECRET');
$token = jwt_encode($payload, $secret, 'HS256'); $token = jwt_encode($payload, $secret, 'HS256');
return $this->response->setStatusCode(201)->setJSON([ return $this->response->setStatusCode(201)->setJSON([
@@ -491,7 +530,7 @@ class AuthController extends Controller
return true; return true;
} }
private function loginUser($user) private function loginUser($user, ?string $redirectTo = null)
{ {
$userRoleModel = new UserRoleModel(); $userRoleModel = new UserRoleModel();
$roles = $userRoleModel->select('roles.name') $roles = $userRoleModel->select('roles.name')
@@ -525,9 +564,17 @@ class AuthController extends Controller
if (count($roleNames) === 1) { if (count($roleNames) === 1) {
// One role → set and redirect directly // One role → set and redirect directly
session()->set('role', $roleNames[0]); session()->set('role', $roleNames[0]);
if ($redirectTo !== null) {
return redirect()->to($redirectTo);
}
return $this->redirectToDashboard([$roleNames[0]]); return $this->redirectToDashboard([$roleNames[0]]);
} else { } else {
// Multiple roles → redirect to role selection view // Multiple roles → redirect to role selection view
if ($redirectTo !== null) {
session()->set('post_login_redirect', $redirectTo);
} else {
session()->remove('post_login_redirect');
}
return redirect()->to('/select-role'); return redirect()->to('/select-role');
} }
@@ -592,12 +639,17 @@ private function redirectToDashboard(array $roles)
{ {
$selectedRole = $this->request->getPost('selected_role'); $selectedRole = $this->request->getPost('selected_role');
$availableRoles = session()->get('roles'); $availableRoles = session()->get('roles');
$redirectTo = $this->sanitizeRedirectTarget((string) ($this->request->getPost('redirect_to') ?? session()->get('post_login_redirect') ?? ''));
if (!$selectedRole || !in_array($selectedRole, $availableRoles)) { if (!$selectedRole || !in_array($selectedRole, $availableRoles)) {
return redirect()->to('/select-role')->with('error', 'Invalid role selected.'); return redirect()->to('/select-role')->with('error', 'Invalid role selected.');
} }
session()->set('role', $selectedRole); session()->set('role', $selectedRole);
session()->remove('post_login_redirect');
if ($redirectTo !== null) {
return redirect()->to($redirectTo);
}
return $this->redirectToDashboard([$selectedRole]); return $this->redirectToDashboard([$selectedRole]);
} }
@@ -609,7 +661,44 @@ private function redirectToDashboard(array $roles)
return redirect()->to('/login')->with('error', 'No roles available.'); return redirect()->to('/login')->with('error', 'No roles available.');
} }
return view('auth/select_role', ['roles' => $roles]); return view('auth/select_role', [
'roles' => $roles,
'redirect_to' => (string) (session()->get('post_login_redirect') ?? ''),
]);
}
private function sanitizeRedirectTarget(string $redirectTo): ?string
{
$redirectTo = trim($redirectTo);
if ($redirectTo === '') {
return null;
}
if (preg_match('#^https?://#i', $redirectTo)) {
$appHost = (string) parse_url(base_url('/'), PHP_URL_HOST);
$targetHost = (string) parse_url($redirectTo, PHP_URL_HOST);
$targetPath = (string) parse_url($redirectTo, PHP_URL_PATH);
$targetQuery = (string) parse_url($redirectTo, PHP_URL_QUERY);
if ($appHost === '' || $targetHost === '' || strcasecmp($appHost, $targetHost) !== 0) {
return null;
}
$redirectTo = $targetPath !== '' ? $targetPath : '/';
if ($targetQuery !== '') {
$redirectTo .= '?' . $targetQuery;
}
}
if (!str_starts_with($redirectTo, '/')) {
$redirectTo = '/' . ltrim($redirectTo, '/');
}
if (str_starts_with($redirectTo, '//')) {
return null;
}
return $redirectTo;
} }
} }
+16 -1
View File
@@ -36,7 +36,7 @@ abstract class BaseController extends Controller
* *
* @var list<string> * @var list<string>
*/ */
protected $helpers = []; protected $helpers = ['security'];
/** @var ApiClient */ /** @var ApiClient */
protected ApiClient $api; protected ApiClient $api;
@@ -73,6 +73,21 @@ abstract class BaseController extends Controller
// Assuming the user role is stored in the session // Assuming the user role is stored in the session
return session()->get('role'); return session()->get('role');
} }
protected function validated(array $rules, ?array $data = null): array
{
$validation = service('validation');
$payload = $data ?? ($this->request->getJSON(true) ?: $this->request->getPost());
$payload = sanitize_request_value($payload);
$validation->setRules($rules);
if (! $validation->run($payload)) {
throw new \InvalidArgumentException(json_encode($validation->getErrors(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: 'Validation failed');
}
return $payload;
}
} }
?> ?>
+35 -8
View File
@@ -10,8 +10,13 @@ class ProofreadController extends ResourceController
{ {
// Basic per-IP throttling: 10 requests per minute // Basic per-IP throttling: 10 requests per minute
$throttler = service('throttler'); $throttler = service('throttler');
$key = 'proofread-' . $this->request->getIPAddress();
if (!$throttler->check($key, 10, MINUTE)) { // Cache/throttler keys cannot contain reserved characters.
// Raw IPv6 addresses contain ":", so hash the IP first.
$ip = $this->request->getIPAddress();
$key = 'proofread-' . hash('sha256', $ip);
if (! $throttler->check($key, 10, MINUTE)) {
return $this->respond([ return $this->respond([
'ok' => false, 'ok' => false,
'error' => 'Too many requests. Try again in a minute.', 'error' => 'Too many requests. Try again in a minute.',
@@ -20,29 +25,51 @@ class ProofreadController extends ResourceController
} }
// Accept form-urlencoded payload to play nicely with CSRF protection // Accept form-urlencoded payload to play nicely with CSRF protection
$text = (string) ($this->request->getPost('text') ?? ''); $payload = sanitize_request_value($this->request->getPost(['text']));
if ($text === '' || mb_strlen($text) > 20000) {
$validation = service('validation');
$validation->setRules([
'text' => 'required|min_length[1]|max_length[20000]',
]);
if (! $validation->run($payload)) {
return $this->respond([ return $this->respond([
'ok' => false, 'ok' => false,
'error' => 'Invalid text (empty or too long).', 'error' => 'Invalid text payload.',
'csrfHash' => csrf_hash(), 'csrfHash' => csrf_hash(),
], 422); ], 422);
} }
$client = \Config\Services::curlrequest(['timeout' => 10]); $text = (string) $payload['text'];
$client = \Config\Services::curlrequest([
'timeout' => 10,
]);
try { try {
$resp = $client->post('https://api.languagetool.org/v2/check', [ $resp = $client->post('https://api.languagetool.org/v2/check', [
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], 'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'form_params' => [ 'form_params' => [
'text' => $text, 'text' => $text,
'language' => 'en-US', 'language' => 'en-US',
], ],
]); ]);
$result = json_decode($resp->getBody(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
return $this->respond([
'ok' => false,
'error' => 'Invalid response from proofread service.',
'csrfHash' => csrf_hash(),
], 502);
}
return $this->respond([ return $this->respond([
'ok' => true, 'ok' => true,
'result' => json_decode($resp->getBody(), true), 'result' => $result,
'csrfHash' => csrf_hash(), 'csrfHash' => csrf_hash(),
]); ]);
} catch (\Throwable $e) { } catch (\Throwable $e) {
@@ -2003,6 +2003,58 @@ class AttendanceTrackingController extends BaseController
return [$subject, $body]; return [$subject, $body];
} }
private function buildFallbackTemplate(string $code, string $variant, array $context): array
{
$studentName = (string) ($context['{{student_name}}'] ?? 'the student');
$incident = (string) ($context['{{incident_date}}'] ?? date('Y-m-d'));
$parentName = (string) ($context['{{parent_name}}'] ?? 'Parent/Guardian');
$phone = (string) ($context['{{school_phone}}'] ?? 'the school office');
$voicemail = (string) ($context['{{voicemail_phone}}'] ?? 'your voicemail');
$subject = match (true) {
str_starts_with($code, 'ABS_1') => 'Attendance Notice: Unreported Absence',
str_starts_with($code, 'ABS_2') => 'Attendance Follow-Up: Two Consecutive Absences',
str_starts_with($code, 'ABS_3') => 'Attendance Follow-Up: Three Absences',
str_starts_with($code, 'LATE_2') => 'Attendance Notice: Repeated Lateness',
str_starts_with($code, 'LATE_3'),
str_starts_with($code, 'LATE_4'),
str_starts_with($code, 'MIX') => 'Attendance Follow-Up: Repeated Lateness and Absence',
default => 'Attendance Notice',
};
$intro = "<p>Insha Allah this email finds you well";
if ($variant === 'answered') {
$intro .= ", <strong>{$parentName}</strong>. Jazakum Allahu khayran for taking the time to speak with us today.</p>";
} elseif ($variant === 'no_answer') {
$intro .= ".</p><p>We tried to reach you but could not connect and left a voice message at <strong>{$voicemail}</strong>.</p>";
} else {
$intro .= ".</p>";
}
$details = match (true) {
str_starts_with($code, 'ABS_1')
=> "<p>This is to let you know that <strong>{$studentName}</strong> was absent on <strong>{$incident}</strong> without prior notice.</p>",
str_starts_with($code, 'ABS_2')
=> "<p>This is a reminder that <strong>{$studentName}</strong> has had repeated absences, most recently on <strong>{$incident}</strong>, without prior notice.</p>",
str_starts_with($code, 'ABS_3')
=> "<p>This is a reminder that <strong>{$studentName}</strong> has been absent three times, most recently on <strong>{$incident}</strong>, without prior notice.</p>",
str_starts_with($code, 'LATE_2')
=> "<p>This is a reminder that <strong>{$studentName}</strong> has been late multiple times, most recently on <strong>{$incident}</strong>.</p>",
str_starts_with($code, 'LATE_3'),
str_starts_with($code, 'LATE_4')
=> "<p>This is a follow-up that <strong>{$studentName}</strong> has had repeated lateness concerns, most recently on <strong>{$incident}</strong>.</p>",
str_starts_with($code, 'MIX')
=> "<p>This is a follow-up that <strong>{$studentName}</strong> has had a mix of repeated lateness and absence concerns, most recently on <strong>{$incident}</strong>.</p>",
default
=> "<p>We'd like to inform you about <strong>{$studentName}</strong>'s recent attendance concern dated <strong>{$incident}</strong>.</p>",
};
$closing = "<p>If your child will be absent or late due to illness or family commitments, please let us know ahead of time.</p>"
. "<p>You can email/call/text us at <strong>{$phone}</strong>.</p>";
return [$subject, $intro . $details . $closing];
}
public function compose() public function compose()
{ {
@@ -2033,8 +2085,8 @@ class AttendanceTrackingController extends BaseController
$rendered = $this->renderTemplate($code, $variant, $ctx); $rendered = $this->renderTemplate($code, $variant, $ctx);
if (!$rendered) { if (!$rendered) {
return redirect()->to(site_url('attendance/violations')) log_message('warning', 'Attendance email template missing; using fallback compose body. code=' . $code . ' variant=' . $variant);
->with('error', 'Template not found for ' . $code . ' (' . $variant . ').'); $rendered = $this->buildFallbackTemplate($code, $variant, $ctx);
} }
[$subject, $body] = $rendered; [$subject, $body] = $rendered;
@@ -0,0 +1,664 @@
<?php
namespace App\Controllers\View;
use App\Controllers\BaseController;
use App\Models\ClassSectionModel;
use App\Models\ConfigurationModel;
use App\Models\CertificateRecordModel;
class CertificateController extends BaseController
{
protected $classSectionModel;
protected $configModel;
protected $certRecordModel;
protected $schoolYear;
public function __construct()
{
$this->classSectionModel = new ClassSectionModel();
$this->configModel = new ConfigurationModel();
$this->certRecordModel = new CertificateRecordModel();
$this->schoolYear = $this->configModel->getConfig('school_year');
}
// ─── Admin UI ──────────────────────────────────────────────────────────────
public function index()
{
$db = \Config\Database::connect();
$selectedCsid = $this->request->getGet('class_section_id');
$schoolYear = $this->request->getGet('school_year') ?? $this->schoolYear;
// ── All enrolled students across every class section ───────────────────
$allEnrolled = $db->table('student_class sc')
->select('s.id AS student_id, s.firstname, s.lastname, sc.class_section_id, cs.class_section_name')
->join('students s', 's.id = sc.student_id')
->join('classSection cs', 'cs.class_section_id = sc.class_section_id')
->where('s.is_active', 1)
->where('sc.school_year', $schoolYear)
->orderBy('s.firstname', 'ASC')
->orderBy('s.lastname', 'ASC')
->get()
->getResultArray();
$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 = [];
if (!empty($allIds)) {
$decisionRows = $db->table('student_decisions')
->whereIn('student_id', $allIds)
->where('school_year', $schoolYear)
->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,
];
}
}
// ── 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) {
$sid = (int)$c['student_id'];
if (!isset($certsByStudent[$sid])) {
$certsByStudent[$sid] = $c['certificate_number'];
}
}
}
// ── Build per-class buckets and stats ──────────────────────────────────
$studentsByClass = [];
$statsPerClass = [];
foreach ($allEnrolled as $row) {
$sid = (int)$row['student_id'];
$csid = (int)$row['class_section_id'];
if (!isset($statsPerClass[$csid])) {
$statsPerClass[$csid] = [
'name' => $row['class_section_name'],
'total' => 0,
'pass' => 0,
'cert' => 0,
];
}
$statsPerClass[$csid]['total']++;
// 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']++;
}
$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;
}
return view('admin/certificates/index', [
'studentsByClass' => $studentsByClass,
'selectedClassId' => $selectedCsid,
'schoolYear' => $schoolYear,
'certDate' => date('m/d/Y'),
'decisionsByStudent' => $decisionsByStudent,
'certsByStudent' => $certsByStudent,
'statsPerClass' => $statsPerClass,
]);
}
public function auditLog()
{
$schoolYear = $this->request->getGet('school_year') ?? $this->schoolYear;
$records = $this->certRecordModel->getAuditLog($schoolYear);
$yearSummary = $this->certRecordModel->yearSummary();
return view('admin/certificates/audit_log', [
'records' => $records,
'schoolYear' => $schoolYear,
'yearSummary' => $yearSummary,
]);
}
public function csrfToken()
{
return $this->response
->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->setHeader('Pragma', 'no-cache')
->setJSON([
'csrf_token' => csrf_token(),
'csrf_hash' => csrf_hash(),
]);
}
// ─── Public verification page ──────────────────────────────────────────────
public function verify(string $certNumber)
{
$record = \Config\Database::connect()
->table('certificate_records cr')
->select('cr.*, u.firstname AS admin_firstname, u.lastname AS admin_lastname')
->join('users u', 'u.id = cr.issued_by', 'left')
->groupStart()
->where('cr.verification_token', $certNumber)
->orWhere('cr.certificate_number', strtoupper($certNumber))
->groupEnd()
->get()
->getRowArray();
return view('certificates/verify', [
'record' => $record ?: null,
]);
}
// ─── Reprint an existing certificate ──────────────────────────────────────
public function reprint(string $certNumber)
{
$record = \Config\Database::connect()
->table('certificate_records')
->where('certificate_number', strtoupper($certNumber))
->get()
->getRowArray();
if (!$record) {
return redirect()->to('administrator/certificates/log')
->with('error', 'Certificate not found: ' . $certNumber);
}
$certDateFormatted = '';
if (!empty($record['cert_date'])) {
$ts = strtotime((string)$record['cert_date']);
if ($ts) {
$certDateFormatted = date('m/d/Y', $ts);
}
}
$student = [
'firstname' => (string)($record['student_name'] ?? ''),
'lastname' => '',
'grade' => (string)($record['grade'] ?? ''),
'cert_number' => (string)($record['certificate_number'] ?? ''),
'verify_token' => $this->ensureVerificationTokenForRecord($record),
];
// 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];
}
$pdfData = $this->buildPdf([$student], $certDateFormatted ?: date('m/d/Y'));
$filename = 'Certificate_' . strtoupper($certNumber) . '.pdf';
return $this->response
->setHeader('Content-Type', 'application/pdf')
->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"')
->setBody($pdfData);
}
// ─── PDF generation ────────────────────────────────────────────────────────
public function generate()
{
$studentIds = $this->request->getPost('student_ids') ?? [];
$certDate = trim($this->request->getPost('cert_date') ?? date('m/d/Y'));
$classSectionId = $this->request->getPost('class_section_id');
$schoolYear = $this->request->getPost('school_year') ?? $this->schoolYear;
if (empty($studentIds)) {
if ($this->request->isAJAX()) {
return $this->response
->setStatusCode(422)
->setJSON([
'ok' => false,
'error' => 'Please select at least one student.',
'csrf_token' => csrf_token(),
'csrf_hash' => csrf_hash(),
]);
}
return redirect()->to('administrator/certificates')
->with('error', 'Please select at least one student.');
}
$studentIds = array_filter(array_map('intval', $studentIds));
$certDate = preg_replace('/[^0-9\/\-]/', '', $certDate);
if (empty($studentIds)) {
if ($this->request->isAJAX()) {
return $this->response
->setStatusCode(422)
->setJSON([
'ok' => false,
'error' => 'Invalid student selection.',
'csrf_token' => csrf_token(),
'csrf_hash' => csrf_hash(),
]);
}
return redirect()->to('administrator/certificates')
->with('error', 'Invalid student selection.');
}
$db = \Config\Database::connect();
$students = [];
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.school_year', $schoolYear)
->where('s.id', $id)
->get()
->getRowArray();
}
if (!$row) {
$s = $db->table('students')
->select('id, firstname, lastname, registration_grade AS grade')
->where('id', $id)
->get()
->getRowArray();
$row = $s ?: null;
}
if ($row) {
$students[] = $row;
}
}
if (empty($students)) {
if ($this->request->isAJAX()) {
return $this->response
->setStatusCode(422)
->setJSON([
'ok' => false,
'error' => 'No valid students found.',
'csrf_token' => csrf_token(),
'csrf_hash' => csrf_hash(),
]);
}
return redirect()->to('administrator/certificates')
->with('error', 'No valid students found.');
}
$issuedAt = date('Y-m-d H:i:s');
// 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();
$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.
$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'] ?? ''),
'school_year' => $schoolYear,
'class_section_id' => $classSectionId ?: null,
'issued_at' => $issuedAt,
]);
$student['cert_number'] = $certNumber;
$student['verify_token'] = $verifyToken;
}
}
unset($student);
$pdfData = $this->buildPdf($students, $certDate);
$filename = 'Certificates_' . date('Ymd_His') . '.pdf';
return $this->response
->setHeader('Content-Type', 'application/pdf')
->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"')
->setHeader('X-CSRF-TOKEN-NAME', csrf_token())
->setHeader('X-CSRF-TOKEN', csrf_hash())
->setBody($pdfData);
}
// ─── Helpers ───────────────────────────────────────────────────────────────
private function parseCertDate(string $certDate): ?string
{
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;
}
private function formatGrade(string $raw): string
{
$clean = trim($raw);
$lower = strtolower($clean);
// 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: "1", "1-A", "2-B" → keep number only.
if (preg_match('/^(\d+)([- ][A-Za-z0-9]+)?$/', $clean, $m)) {
return 'Grade ' . (int)$m[1];
}
return $clean;
}
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,
]);
return $token;
}
// ─── PDF rendering ─────────────────────────────────────────────────────────
private function buildPdf(array $students, string $certDate): string
{
$fontDir = FCPATH . 'assets' . DIRECTORY_SEPARATOR . 'certificates' . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR;
$imgDir = FCPATH . 'assets' . DIRECTORY_SEPARATOR . 'certificates' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR;
$edwardianFont = \TCPDF_FONTS::addTTFfont($fontDir . 'Edwardian Script ITC Regular.ttf', 'TrueTypeUnicode', '', 32);
$garamondBold = \TCPDF_FONTS::addTTFfont($fontDir . 'Garamond Bold.ttf', 'TrueTypeUnicode', '', 32);
$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);
$pdf->SetAutoPageBreak(false, 0);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetHeaderMargin(0);
$pdf->SetFooterMargin(0);
$W = $pdf->getPageWidth();
$H = $pdf->getPageHeight();
foreach ($students as $student) {
$pdf->AddPage();
$name = trim((string)($student['firstname'] ?? '') . ' ' . (string)($student['lastname'] ?? ''));
$grade = $this->formatGrade($student['grade'] ?? '');
$certNumber = $student['cert_number'] ?? '';
$verifyToken = $student['verify_token'] ?? '';
$verifyUrl = $verifyToken !== ''
? site_url('verify/' . rawurlencode($verifyToken))
: null;
$this->drawCertificate(
$pdf,
$W,
$H,
$name,
$grade,
$certDate,
$certNumber,
$verifyUrl,
$imgDir,
$edwardianFont,
$garamondBold,
$ebGaramond
);
}
return $pdf->Output('', 'S');
}
/**
* Coordinate mapping: iTextSharp origin bottom-left → TCPDF origin top-left.
* y_tcpdf ≈ H y_iTextSharp
*/
private function drawCertificate(
\TCPDF $pdf,
float $W,
float $H,
string $name,
string $grade,
string $certDate,
string $certNumber,
?string $verifyUrl,
string $imgDir,
string $edwardianFont,
string $garamondBold,
string $ebGaramond
): void {
// ── Images
$pdf->Image($imgDir . 'title.png', 126, 0, 600);
$pdf->Image($imgDir . 'background.png', 280, 176, 291, 340);
$pdf->Image($imgDir . 'signature.png', 140, 410, 90, 80);
// ── "Presented to:"
$pdf->SetFont('times', 'B', 24);
$pdf->SetTextColor(0, 0, 0);
$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;
if (!empty($verifyUrl)) {
$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.
$pdf->SetFont($edwardianFont, '', 38);
$nameX = ($W - $pdf->GetStringWidth($name)) / 2;
$this->drawGradientText($pdf, $edwardianFont, 38, $name, $nameX, 221.5);
// ── Line under name
$pdf->SetFont('times', '', 20);
$pdf->SetXY(0, 236);
$pdf->Cell(600, 20, '___________________________________', 0, 0, 'R');
// ── Description
$pdf->SetFont($ebGaramond, '', 20);
$pdf->SetXY(0, 273);
$pdf->Cell($W, 20, 'for successfully completing the requirements of', 0, 0, 'C');
// ── Grade
$pdf->SetFont($garamondBold, '', 20);
$pdf->SetXY(0, 310);
$pdf->Cell($W, 20, $grade, 0, 0, 'C');
// ── "at"
$pdf->SetFont('times', '', 20);
$pdf->SetXY(0, 343);
$pdf->Cell($W, 20, 'at', 0, 0, 'C');
// ── School name
$pdf->SetFont($garamondBold, '', 20);
$pdf->SetXY(0, 375);
$pdf->Cell($W, 20, 'Al Rahma Sunday School', 0, 0, 'C');
// ── Date
$this->drawGradientText($pdf, $edwardianFont, 26, $certDate, 586, 456);
// ── Date underline + label
$pdf->SetFont('times', '', 20);
$pdf->SetXY(0, 463);
$pdf->Cell(742, 20, '_________________', 0, 0, 'R');
$pdf->SetXY(650, 492);
$pdf->Cell(80, 20, 'Date', 0, 0, 'C');
// ── Signature underline + label
$pdf->SetXY(106, 463);
$pdf->Cell(200, 20, '_________________', 0, 0, 'L');
$pdf->SetXY(106, 492);
$pdf->Cell(168, 20, 'Signature', 0, 0, 'C');
// ── Certificate number — 1.4 cm from bottom, 2.5 cm from left.
if ($certNumber !== '') {
$pdf->SetFont('helvetica', '', 8);
$pdf->SetTextColor(150, 150, 150);
$pdf->SetXY(70.86, $H - 39.68);
$pdf->Cell(200, 12, 'Certificate No. ' . $certNumber, 0, 0, 'L');
$pdf->SetTextColor(0, 0, 0);
}
}
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++) {
$pdf->setAlpha(($i + 1) * 25 / 255);
$pdf->SetTextColor(0, 0, 0);
$pdf->Text($x + $i / 4, $y + $i / 4, $text);
}
$pdf->setAlpha(1);
$pdf->SetTextColor(0, 0, 0);
$pdf->Text($x, $y, $text);
}
}
+8 -8
View File
@@ -24,10 +24,10 @@ class ContactController extends BaseController
// Define validation rules // Define validation rules
$validation->setRules([ $validation->setRules([
'name' => 'required|min_length[3]', 'name' => "required|regex_match[/^[\\p{L}\\s'\\-]+$/u]|min_length[3]|max_length[100]",
'email' => 'required|valid_email', 'email' => 'required|valid_email|max_length[254]',
'subject' => 'required|min_length[3]', 'subject' => 'required|min_length[3]|max_length[150]',
'message' => 'required|min_length[10]' 'message' => 'required|min_length[10]|max_length[5000]'
]); ]);
if (!$validation->withRequest($this->request)->run()) { if (!$validation->withRequest($this->request)->run()) {
@@ -37,10 +37,10 @@ class ContactController extends BaseController
} }
// Process form data // Process form data
$name = $this->request->getPost('name'); $name = esc((string) $this->request->getPost('name'));
$email = strtolower($this->request->getPost('email')); $email = esc(strtolower((string) $this->request->getPost('email')));
$subject = $this->request->getPost('subject'); $subject = esc((string) $this->request->getPost('subject'));
$message = $this->request->getPost('message'); $message = nl2br(esc((string) $this->request->getPost('message')));
// Initialize the EmailController // Initialize the EmailController
$emailController = new \App\Controllers\View\EmailController(); $emailController = new \App\Controllers\View\EmailController();
+13 -222
View File
@@ -2,6 +2,7 @@
namespace App\Controllers\View; namespace App\Controllers\View;
use App\Controllers\BaseController; use App\Controllers\BaseController;
use App\Libraries\InvoiceLedgerService;
use App\Models\DiscountVoucherModel; use App\Models\DiscountVoucherModel;
use App\Models\DiscountUsageModel; use App\Models\DiscountUsageModel;
use App\Models\InvoiceModel; use App\Models\InvoiceModel;
@@ -28,6 +29,7 @@ class DiscountController extends BaseController
protected $eventChargesModel; protected $eventChargesModel;
protected $additionalChargeModel; protected $additionalChargeModel;
protected $classSectionModel; protected $classSectionModel;
protected $invoiceLedgerService;
public function __construct() public function __construct()
{ {
@@ -41,6 +43,7 @@ class DiscountController extends BaseController
$this->eventChargesModel = new EventChargesModel(); $this->eventChargesModel = new EventChargesModel();
$this->additionalChargeModel = new AdditionalChargeModel(); $this->additionalChargeModel = new AdditionalChargeModel();
$this->classSectionModel = new ClassSectionModel(); $this->classSectionModel = new ClassSectionModel();
$this->invoiceLedgerService = new InvoiceLedgerService();
$this->schoolYear = $this->configModel->getConfig('school_year'); $this->schoolYear = $this->configModel->getConfig('school_year');
$this->semester = $this->configModel->getConfig('semester'); $this->semester = $this->configModel->getConfig('semester');
@@ -121,6 +124,8 @@ class DiscountController extends BaseController
foreach ($invoices as $invoice) { foreach ($invoices as $invoice) {
if ($remainingUses <= 0) break 2; // out of parentIds loop too 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 // Snapshot current balance BEFORE applying
$initialPreBalance = (float) $this->getCurrentInvoiceBalance($invoice['id'], $this->schoolYear); $initialPreBalance = (float) $this->getCurrentInvoiceBalance($invoice['id'], $this->schoolYear);
if ($initialPreBalance <= 0) { if ($initialPreBalance <= 0) {
@@ -201,22 +206,9 @@ class DiscountController extends BaseController
'updated_at' => $now, 'updated_at' => $now,
]); ]);
// Update invoice balance based on pre-discount snapshot (supports multiple discounts) $ledger = $this->invoiceLedgerService->recalculateInvoice((int) $invoice['id']);
$newBalance = max(0.0, round($initialPreBalance - $discount, 2)); $postBalance = (float) ($ledger['balance'] ?? 0.0);
$this->db->table('invoices') $currentBalance = $postBalance;
->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);
// Increment voucher usage // Increment voucher usage
$this->db->table('discount_vouchers') $this->db->table('discount_vouchers')
@@ -596,53 +588,11 @@ class DiscountController extends BaseController
*/ */
private function getCurrentInvoiceBalance($invoiceId, $schoolYear) private function getCurrentInvoiceBalance($invoiceId, $schoolYear)
{ {
$invoice = $this->invoiceModel->find($invoiceId); try {
if (!$invoice) return 0.0; return (float) ($this->invoiceLedgerService->calculateInvoice((int) $invoiceId)['balance'] ?? 0.0);
} catch (\Throwable $e) {
// Payments (exclude void/refund/failed, honor year) return 0.0;
$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();
} }
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,166 +600,7 @@ class DiscountController extends BaseController
*/ */
private function recalculateInvoice($invoiceId, $schoolYear): void private function recalculateInvoice($invoiceId, $schoolYear): void
{ {
$invoice = $this->invoiceModel->find($invoiceId); $this->invoiceLedgerService->recalculateInvoice((int) $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) {}
$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');
$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);
} }
/** /**
+157
View File
@@ -170,6 +170,163 @@ class EmailController extends Controller
} }
} }
/**
* Send one email with a single To recipient and many CC recipients.
*
* @param string $recipient
* @param string[] $ccRecipients
* @param string $subject
* @param string $htmlMessage
* @param string|null $profile
* @param string|null $replyToEmail
* @param string|null $replyToName
* @param array $attachments
*/
public function sendEmailWithCc(
string $recipient,
array $ccRecipients,
string $subject,
string $htmlMessage,
?string $profile = null,
?string $replyToEmail = null,
?string $replyToName = null,
array $attachments = []
): bool {
$ccRecipients = array_values(array_unique(array_filter(array_map(static function ($email) {
$email = trim((string) $email);
return filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : null;
}, $ccRecipients))));
if ($ccRecipients === []) {
return $this->sendEmail($recipient, $subject, $htmlMessage, $profile, $replyToEmail, $replyToName, $attachments);
}
$autoload = APPPATH . '../vendor/autoload.php';
if (is_file($autoload)) {
require_once $autoload;
}
$profile = $this->resolveProfile($profile);
$cfg = $this->getProfileConfig($profile);
if (empty($cfg['host']) || empty($cfg['user']) || $cfg['pass'] === '') {
log_message('error', "[mail:$profile] Missing SMTP config (host/user/pass). Check .env MAIL_{$this->envKeyFromProfile($profile)}_* or MAIL_DEFAULT_*.");
return false;
}
$debugEnabled = (bool) env('MAIL_DEBUG', false);
$timeout = (int) env('MAIL_TIMEOUT', 15);
$keepAlive = (bool) env('MAIL_KEEPALIVE', false);
$verifyPeer = filter_var(env('MAIL_VERIFY_PEER', 'true'), FILTER_VALIDATE_BOOLEAN);
$targetHost = $cfg['host'];
$targetPort = (int) $cfg['port'];
$resolved = @gethostbyname($targetHost);
if (!$resolved || $resolved === $targetHost) {
log_message('debug', "[mail:$profile] DNS resolve note: host=$targetHost, resolved=$resolved");
}
$sockOk = @fsockopen($targetHost, $targetPort, $errno, $errstr, 5);
if (!$sockOk) {
log_message('error', "[mail:$profile] Socket preflight failed to {$targetHost}:{$targetPort} (errno=$errno, err=$errstr). Likely firewall/port/encryption mismatch or wrong host.");
} else {
fclose($sockOk);
}
$mail = new PHPMailer(true);
try {
if ($debugEnabled) {
ob_start();
}
$mail->isSMTP();
$mail->Host = $cfg['host'];
$mail->Port = $cfg['port'];
$mail->SMTPAuth = true;
$mail->Username = $cfg['user'];
$mail->Password = $cfg['pass'];
$mail->CharSet = 'UTF-8';
$mail->Timeout = $timeout;
$mail->SMTPKeepAlive = $keepAlive;
$mail->SMTPAutoTLS = true;
if ($cfg['encryption'] === 'ssl') {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
} else {
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
}
$mail->SMTPOptions = [
'ssl' => [
'verify_peer' => $verifyPeer,
'verify_peer_name' => $verifyPeer,
'allow_self_signed' => !$verifyPeer,
],
];
$mail->SMTPDebug = $debugEnabled ? 3 : 0;
$mail->Debugoutput = 'error_log';
$mail->setFrom($cfg['fromEmail'], $cfg['fromName']);
if (!empty($cfg['returnPath'])) {
$mail->Sender = $cfg['returnPath'];
}
$mail->clearReplyTos();
$rtEmail = env('MAIL_DEFAULT_REPLY_TO');
$rtName = env('MAIL_DEFAULT_REPLY_TO_NAME');
if (!$rtEmail || !filter_var($rtEmail, FILTER_VALIDATE_EMAIL)) {
$rtEmail = $replyToEmail ?: ($cfg['replyTo'] ?: $cfg['fromEmail']);
}
if (!$rtName) {
$rtName = $replyToName ?: ($cfg['replyToName'] ?: $cfg['fromName']);
}
$rtName = $this->sanitizeReplyToName($rtName, $cfg['fromName']);
if ($rtEmail) {
$mail->addReplyTo($rtEmail, $rtName);
}
if (!empty($cfg['dkim']['domain']) && !empty($cfg['dkim']['private']) && !empty($cfg['dkim']['selector'])) {
$mail->DKIM_domain = $cfg['dkim']['domain'];
$mail->DKIM_private = $cfg['dkim']['private'];
$mail->DKIM_selector = $cfg['dkim']['selector'];
$mail->DKIM_identity = $cfg['fromEmail'];
}
$mail->addAddress($recipient);
foreach ($ccRecipients as $ccRecipient) {
$mail->addCC($ccRecipient);
}
foreach ($attachments as $att) {
if (!empty($att['path']) && is_file($att['path'])) {
$mail->addAttachment($att['path'], $att['name'] ?? '');
}
}
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $htmlMessage;
$ok = $mail->send();
$dbg = $debugEnabled ? (ob_get_clean() ?: '') : '';
if ($ok) {
log_message('info', "[mail:$profile] Sent to {$recipient} with " . count($ccRecipients) . " CC recipient(s), subj='{$subject}' via {$cfg['host']}:{$cfg['port']}/{$cfg['encryption']}");
return true;
}
log_message('error', "[mail:$profile] Failed: {$mail->ErrorInfo}. Debug: {$dbg}");
return false;
} catch (Exception $e) {
$dbg = $debugEnabled ? (ob_get_clean() ?: '') : '';
log_message('error', "[mail:$profile] Exception: {$e->getMessage()} | PHPMailer: {$mail->ErrorInfo} | Debug: {$dbg}");
return false;
}
}
/** Resolve null/alias profile names to a canonical env prefix. */ /** Resolve null/alias profile names to a canonical env prefix. */
private function resolveProfile(?string $profile): string private function resolveProfile(?string $profile): string
{ {
File diff suppressed because it is too large Load Diff
+169 -43
View File
@@ -102,11 +102,9 @@ class ExamDraftController extends BaseController
session()->set('class_section_id', $selectedClass); session()->set('class_section_id', $selectedClass);
} }
$allDrafts = $this->examDraftModel $classSectionIds = array_map(static fn($a) => (int) $a['class_section_id'], $assignments);
->select($this->draftSelectColumns())
->select('cs.class_section_name') $allDrafts = $this->visibleTeacherDraftsQuery($teacherId, $classSectionIds)
->join('classSection cs', 'cs.class_section_id = exam_drafts.class_section_id', 'left')
->where($this->authorIdColumn, $teacherId)
->orderBy('created_at', 'DESC') ->orderBy('created_at', 'DESC')
->findAll(); ->findAll();
@@ -117,10 +115,10 @@ class ExamDraftController extends BaseController
$row['final_pdf_file'] = $pdf; $row['final_pdf_file'] = $pdf;
} }
} }
$row = $this->attachTeacherDraftContext($row, $teacherId);
} }
unset($row); unset($row);
$classSectionIds = array_map(static fn($a) => (int) $a['class_section_id'], $assignments);
$legacyExams = []; $legacyExams = [];
// Guard against missing schema column in older databases // Guard against missing schema column in older databases
if ($this->hasIsLegacyColumn) { if ($this->hasIsLegacyColumn) {
@@ -129,8 +127,9 @@ class ExamDraftController extends BaseController
$legacyQuery = $this->examDraftModel $legacyQuery = $this->examDraftModel
->select($this->draftSelectColumns()) ->select($this->draftSelectColumns())
->select('cs.class_section_name') ->select('cs.class_section_name, u.firstname AS teacher_first, u.lastname AS teacher_last')
->join('classSection cs', 'cs.class_section_id = exam_drafts.class_section_id', 'left') ->join('classSection cs', 'cs.class_section_id = exam_drafts.class_section_id', 'left')
->join('users u', 'u.id = exam_drafts.' . $this->authorIdColumn, 'left')
->where('exam_drafts.is_legacy', 1) ->where('exam_drafts.is_legacy', 1)
->where('exam_drafts.status', 'legacy') ->where('exam_drafts.status', 'legacy')
->where('exam_drafts.final_file IS NOT NULL', null, false); ->where('exam_drafts.final_file IS NOT NULL', null, false);
@@ -143,6 +142,11 @@ class ExamDraftController extends BaseController
->orderBy('cs.class_section_name', 'ASC') ->orderBy('cs.class_section_name', 'ASC')
->orderBy('exam_drafts.created_at', 'DESC') ->orderBy('exam_drafts.created_at', 'DESC')
->findAll(); ->findAll();
foreach ($legacyExams as &$row) {
$row = $this->attachTeacherDraftContext($row, $teacherId);
}
unset($row);
} else { } else {
// Legacy column absent, show all drafts and skip legacy tab query // Legacy column absent, show all drafts and skip legacy tab query
$drafts = $allDrafts; $drafts = $allDrafts;
@@ -182,7 +186,7 @@ class ExamDraftController extends BaseController
} }
$classSectionId = (int) ($this->request->getPost('class_section_id') ?? session()->get('class_section_id') ?? 0); $classSectionId = (int) ($this->request->getPost('class_section_id') ?? session()->get('class_section_id') ?? 0);
$examType = trim((string) $this->request->getPost('exam_type')); $examType = $this->normalizeExamType($this->request->getPost('exam_type'));
$authorComment = trim((string) $this->request->getPost('author_comment')); $authorComment = trim((string) $this->request->getPost('author_comment'));
if ($classSectionId <= 0) { if ($classSectionId <= 0) {
@@ -226,7 +230,11 @@ class ExamDraftController extends BaseController
->orderBy('version', 'DESC') ->orderBy('version', 'DESC')
->first(); ->first();
$title = $examType ?: 'Exam Draft'; if ($examType === '') {
return redirect()->back()->withInput()->with('error', 'Select an exam type before submitting.');
}
$title = $examType;
if ($saveAsDraft) { if ($saveAsDraft) {
if ($teacherFile === null && (empty($existingDraft) || empty($this->draftTeacherFile($existingDraft)))) { if ($teacherFile === null && (empty($existingDraft) || empty($this->draftTeacherFile($existingDraft)))) {
@@ -235,7 +243,7 @@ class ExamDraftController extends BaseController
if (!empty($existingDraft) && strtolower((string) ($existingDraft['status'] ?? '')) === 'draft') { if (!empty($existingDraft) && strtolower((string) ($existingDraft['status'] ?? '')) === 'draft') {
$draftRowId = (int) ($existingDraft['id'] ?? 0); $draftRowId = (int) ($existingDraft['id'] ?? 0);
$updateDraft = [ $updateDraft = [
'exam_type' => $examType ?: null, 'exam_type' => $examType,
'draft_title' => $title, 'draft_title' => $title,
'author_comment' => $authorComment === '' ? null : $authorComment, 'author_comment' => $authorComment === '' ? null : $authorComment,
'status' => 'draft', 'status' => 'draft',
@@ -263,7 +271,7 @@ class ExamDraftController extends BaseController
'class_section_id' => $classSectionId, 'class_section_id' => $classSectionId,
'semester' => $this->semester, 'semester' => $this->semester,
'school_year' => $this->schoolYear, 'school_year' => $this->schoolYear,
'exam_type' => $examType ?: null, 'exam_type' => $examType,
'draft_title' => $title, 'draft_title' => $title,
'author_comment' => $authorComment === '' ? null : $authorComment, 'author_comment' => $authorComment === '' ? null : $authorComment,
'status' => 'draft', 'status' => 'draft',
@@ -280,9 +288,6 @@ class ExamDraftController extends BaseController
} }
$existingStatus = strtolower((string) ($existingDraft['status'] ?? '')); $existingStatus = strtolower((string) ($existingDraft['status'] ?? ''));
if ($examType === '') {
return redirect()->back()->withInput()->with('error', 'Select an exam type before submitting.');
}
if ($teacherFile === null) { if ($teacherFile === null) {
return redirect()->back()->withInput()->with('error', 'Upload a DOC/DOCX file to submit the exam draft.'); return redirect()->back()->withInput()->with('error', 'Upload a DOC/DOCX file to submit the exam draft.');
} }
@@ -291,7 +296,7 @@ class ExamDraftController extends BaseController
if (!empty($existingDraft) && $existingStatus === 'submitted') { if (!empty($existingDraft) && $existingStatus === 'submitted') {
$draftRowId = (int) ($existingDraft['id'] ?? 0); $draftRowId = (int) ($existingDraft['id'] ?? 0);
$updateSubmit = [ $updateSubmit = [
'exam_type' => $examType ?: null, 'exam_type' => $examType,
'draft_title' => $title, 'draft_title' => $title,
'author_comment' => $authorComment === '' ? null : $authorComment, 'author_comment' => $authorComment === '' ? null : $authorComment,
'status' => 'submitted', 'status' => 'submitted',
@@ -322,7 +327,7 @@ class ExamDraftController extends BaseController
'class_section_id' => $classSectionId, 'class_section_id' => $classSectionId,
'semester' => $this->semester, 'semester' => $this->semester,
'school_year' => $this->schoolYear, 'school_year' => $this->schoolYear,
'exam_type' => $examType ?: null, 'exam_type' => $examType,
'draft_title' => $title, 'draft_title' => $title,
'author_comment' => $authorComment === '' ? null : $authorComment, 'author_comment' => $authorComment === '' ? null : $authorComment,
'status' => 'submitted', 'status' => 'submitted',
@@ -343,6 +348,16 @@ class ExamDraftController extends BaseController
} }
public function adminIndex() public function adminIndex()
{
return $this->reviewIndex();
}
public function principalIndex()
{
return $this->reviewIndex();
}
public function reviewIndex()
{ {
if ($this->reviewerIdColumn !== '') { if ($this->reviewerIdColumn !== '') {
$allDrafts = $this->examDraftModel $allDrafts = $this->examDraftModel
@@ -482,10 +497,23 @@ class ExamDraftController extends BaseController
'visibleClasses' => $visibleClasses, 'visibleClasses' => $visibleClasses,
'classDraftGroups' => $classDraftGroups, 'classDraftGroups' => $classDraftGroups,
'newSubmissionClasses' => $newSubmissionClasses, 'newSubmissionClasses' => $newSubmissionClasses,
'reviewActionUrl' => base_url($this->reviewRoutePrefix() . '/exam-drafts/review'),
'legacyUploadUrl' => base_url($this->reviewRoutePrefix() . '/exam-drafts/upload-legacy'),
'reviewPortalLabel' => $this->reviewPortalLabel(),
]); ]);
} }
public function adminUploadLegacy() public function adminUploadLegacy()
{
return $this->reviewUploadLegacy();
}
public function principalUploadLegacy()
{
return $this->reviewUploadLegacy();
}
public function reviewUploadLegacy()
{ {
$adminId = (int) (session()->get('user_id') ?? 0); $adminId = (int) (session()->get('user_id') ?? 0);
if ($adminId <= 0) { if ($adminId <= 0) {
@@ -499,7 +527,7 @@ class ExamDraftController extends BaseController
$classSectionIds = array_values(array_filter(array_map('intval', $classSectionIds))); $classSectionIds = array_values(array_filter(array_map('intval', $classSectionIds)));
$schoolYear = trim((string) ($this->request->getPost('school_year') ?? $this->schoolYear)); $schoolYear = trim((string) ($this->request->getPost('school_year') ?? $this->schoolYear));
$semester = trim((string) ($this->request->getPost('semester') ?? $this->semester)); $semester = trim((string) ($this->request->getPost('semester') ?? $this->semester));
$examType = trim((string) $this->request->getPost('exam_type')); $examType = $this->normalizeExamType($this->request->getPost('exam_type'));
if (empty($classSectionIds)) { if (empty($classSectionIds)) {
return redirect()->back()->withInput()->with('error', 'Select at least one class section.'); return redirect()->back()->withInput()->with('error', 'Select at least one class section.');
@@ -510,6 +538,9 @@ class ExamDraftController extends BaseController
if ($semester === '') { if ($semester === '') {
return redirect()->back()->withInput()->with('error', 'Semester is required.'); return redirect()->back()->withInput()->with('error', 'Semester is required.');
} }
if ($examType === '') {
return redirect()->back()->withInput()->with('error', 'Exam type is required.');
}
$file = $this->request->getFile('old_exam_file'); $file = $this->request->getFile('old_exam_file');
if (!$file || !$file->isValid()) { if (!$file || !$file->isValid()) {
@@ -534,8 +565,8 @@ class ExamDraftController extends BaseController
$this->authorIdColumn => $adminId, // store under admin user since legacy uploads are admin-only $this->authorIdColumn => $adminId, // store under admin user since legacy uploads are admin-only
'semester' => ucfirst(strtolower($semester)), 'semester' => ucfirst(strtolower($semester)),
'school_year' => $schoolYear, 'school_year' => $schoolYear,
'exam_type' => $examType === '' ? null : $examType, 'exam_type' => $examType,
'draft_title' => $examType === '' ? 'Legacy Exam' : $examType, 'draft_title' => $examType,
'author_comment' => null, 'author_comment' => null,
'final_file' => $stored, 'final_file' => $stored,
'final_filename' => $file->getClientName(), 'final_filename' => $file->getClientName(),
@@ -563,13 +594,23 @@ class ExamDraftController extends BaseController
} }
if ($saved > 0) { if ($saved > 0) {
return redirect()->to('/administrator/exam-drafts')->with('success', 'Old exam uploaded successfully.'); return redirect()->to($this->reviewDashboardPath())->with('success', 'Old exam uploaded successfully.');
} }
return redirect()->back()->withInput()->with('error', 'Unable to save the old exam.'); return redirect()->back()->withInput()->with('error', 'Unable to save the old exam.');
} }
public function adminReview() public function adminReview()
{
return $this->reviewSubmission();
}
public function principalReview()
{
return $this->reviewSubmission();
}
public function reviewSubmission()
{ {
$draftId = (int) ($this->request->getPost('draft_id') ?? 0); $draftId = (int) ($this->request->getPost('draft_id') ?? 0);
if ($draftId <= 0) { if ($draftId <= 0) {
@@ -646,13 +687,18 @@ class ExamDraftController extends BaseController
$baseVersion = 1; $baseVersion = 1;
} }
$reviewRevision = $this->nextReviewRevision($draft, $baseVersion); $reviewRevision = $this->nextReviewRevision($draft, $baseVersion);
$reviewExamType = $this->normalizeExamType($draft['exam_type'] ?? $draft['draft_title'] ?? '');
if ($reviewExamType === '') {
return redirect()->back()->with('error', 'This draft is missing an exam type. Update the exam type before reviewing.');
}
$newRow = [ $newRow = [
$this->authorIdColumn => $this->draftTeacherId($draft), $this->authorIdColumn => $this->draftTeacherId($draft),
'class_section_id' => (int) ($draft['class_section_id'] ?? 0), 'class_section_id' => (int) ($draft['class_section_id'] ?? 0),
'semester' => (string) ($draft['semester'] ?? ''), 'semester' => (string) ($draft['semester'] ?? ''),
'school_year' => (string) ($draft['school_year'] ?? ''), 'school_year' => (string) ($draft['school_year'] ?? ''),
'exam_type' => $draft['exam_type'] ?? null, 'exam_type' => $reviewExamType,
'draft_title' => $draft['draft_title'] ?? $draft['exam_type'] ?? 'Exam Draft', 'draft_title' => $draft['draft_title'] ?? $reviewExamType,
'author_comment' => $draft['author_comment'] ?? null, 'author_comment' => $draft['author_comment'] ?? null,
'status' => $status, 'status' => $status,
'reviewed_at' => $update['reviewed_at'], 'reviewed_at' => $update['reviewed_at'],
@@ -677,11 +723,6 @@ class ExamDraftController extends BaseController
if ($this->hasAcceptanceTypeColumn) { if ($this->hasAcceptanceTypeColumn) {
$newRow['acceptance_type'] = $status === 'accepted' ? $acceptanceType : null; $newRow['acceptance_type'] = $status === 'accepted' ? $acceptanceType : null;
} }
$teacherFile = $this->draftTeacherFile($draft);
if (!empty($teacherFile)) {
$newRow[$this->authorFileColumn] = $teacherFile;
$newRow[$this->authorFilenameColumn] = $this->draftTeacherFilename($draft) ?? $teacherFile;
}
if ($this->hasIsLegacyColumn && !empty($draft['is_legacy'])) { if ($this->hasIsLegacyColumn && !empty($draft['is_legacy'])) {
$newRow['is_legacy'] = 1; $newRow['is_legacy'] = 1;
} }
@@ -698,16 +739,6 @@ class ExamDraftController extends BaseController
return redirect()->back()->with('success', 'Review saved successfully.'); return redirect()->back()->with('success', 'Review saved successfully.');
} }
return redirect()->back()->with('error', 'Unable to save the review.'); return redirect()->back()->with('error', 'Unable to save the review.');
} elseif (strtolower($status) === 'accepted' && !empty($this->draftTeacherFile($draft))) {
$copied = $this->copyDraftToFinal($this->draftTeacherFile($draft));
if ($copied !== null) {
$update['final_file'] = $copied;
$update['final_filename'] = $this->draftTeacherFilename($draft) ?? $this->draftTeacherFile($draft);
$pdfName = $this->ensurePdfExists($copied, pathinfo($copied, PATHINFO_EXTENSION));
if ($pdfName !== null && $this->hasFinalPdfColumn) {
$update['final_pdf_file'] = $pdfName;
}
}
} }
if ($status === 'legacy') { if ($status === 'legacy') {
$this->prepareLegacyPdfVersion($update, $draft); $this->prepareLegacyPdfVersion($update, $draft);
@@ -759,10 +790,11 @@ class ExamDraftController extends BaseController
return $this->response->setStatusCode(401); return $this->response->setStatusCode(401);
} }
$drafts = $this->examDraftModel $assignments = $this->teacherClassModel->getClassAssignmentsByUserId($teacherId, $this->schoolYear);
->select($this->draftSelectColumns()) $classSectionIds = array_map(static fn($a) => (int) $a['class_section_id'], $assignments);
->select('id, status, acceptance_type, updated_at, reviewed_at')
->where($this->authorIdColumn, $teacherId) $drafts = $this->visibleTeacherDraftsQuery($teacherId, $classSectionIds)
->select('exam_drafts.id, exam_drafts.status, exam_drafts.acceptance_type, exam_drafts.updated_at, exam_drafts.reviewed_at')
->orderBy('updated_at', 'DESC') ->orderBy('updated_at', 'DESC')
->findAll(); ->findAll();
@@ -808,6 +840,58 @@ class ExamDraftController extends BaseController
return $validIds[0] ?? 0; return $validIds[0] ?? 0;
} }
private function visibleTeacherDraftsQuery(int $teacherId, array $classSectionIds)
{
$query = $this->examDraftModel
->select($this->draftSelectColumns())
->select('cs.class_section_name, u.firstname AS teacher_first, u.lastname AS teacher_last')
->join('classSection cs', 'cs.class_section_id = exam_drafts.class_section_id', 'left')
->join('users u', 'u.id = exam_drafts.' . $this->authorIdColumn, 'left');
if (empty($classSectionIds)) {
return $query->where('exam_drafts.' . $this->authorIdColumn, $teacherId);
}
$query->groupStart()
->where('exam_drafts.' . $this->authorIdColumn, $teacherId)
->orGroupStart()
->whereIn('exam_drafts.class_section_id', $classSectionIds)
->where('exam_drafts.' . $this->authorIdColumn . ' !=', $teacherId)
->where('exam_drafts.status !=', 'draft');
if ($this->schoolYear !== '') {
$query->where('exam_drafts.school_year', $this->schoolYear);
}
if ($this->semester !== '') {
$query->where('exam_drafts.semester', $this->semester);
}
$query->groupEnd()
->groupEnd();
return $query;
}
private function attachTeacherDraftContext(array $row, int $viewerId): array
{
$isOwn = $this->draftTeacherId($row) === $viewerId;
$row['is_own_submission'] = $isOwn;
$row['teacher_display_name'] = $isOwn ? 'You' : $this->draftTeacherName($row);
return $row;
}
private function draftTeacherName(array $draft): string
{
$name = trim(((string) ($draft['teacher_first'] ?? '')) . ' ' . ((string) ($draft['teacher_last'] ?? '')));
if ($name !== '') {
return $name;
}
$teacherId = $this->draftTeacherId($draft);
return $teacherId > 0 ? 'Teacher #' . $teacherId : 'Teacher';
}
private function statusBadgeMap(): array private function statusBadgeMap(): array
{ {
return [ return [
@@ -944,7 +1028,7 @@ class ExamDraftController extends BaseController
. '<tr><td style="padding:4px 8px;"><strong>Status</strong></td><td style="padding:4px 8px;">' . esc((string) ($draft['status'] ?? 'submitted')) . '</td></tr>' . '<tr><td style="padding:4px 8px;"><strong>Status</strong></td><td style="padding:4px 8px;">' . esc((string) ($draft['status'] ?? 'submitted')) . '</td></tr>'
. '<tr><td style="padding:4px 8px;"><strong>Submitted at</strong></td><td style="padding:4px 8px;">' . esc((string) $submittedAt) . '</td></tr>' . '<tr><td style="padding:4px 8px;"><strong>Submitted at</strong></td><td style="padding:4px 8px;">' . esc((string) $submittedAt) . '</td></tr>'
. '</table>' . '</table>'
. '<p>Review drafts: <a href="' . esc(base_url('administrator/exam-drafts')) . '">Admin exam drafts</a></p>'; . '<p>Review drafts: <a href="' . esc(base_url($this->reviewRoutePrefix() . '/exam-drafts')) . '">' . esc($this->reviewPortalLabel()) . ' exam drafts</a></p>';
$mailer = \Config\Services::emailService(); $mailer = \Config\Services::emailService();
$mailer->send($principalEmail, $subject, $body, 'notifications'); $mailer->send($principalEmail, $subject, $body, 'notifications');
@@ -953,6 +1037,38 @@ class ExamDraftController extends BaseController
} }
} }
private function reviewDashboardPath(): string
{
return '/' . $this->reviewRoutePrefix() . '/exam-drafts';
}
private function reviewRoutePrefix(): string
{
return $this->isPrincipalReviewer() ? 'principal' : 'administrator';
}
private function reviewPortalLabel(): string
{
return $this->isPrincipalReviewer() ? 'Principal' : 'Administrator';
}
private function isPrincipalReviewer(): bool
{
$roles = session()->get('roles');
if (!is_array($roles)) {
$roles = $roles === null ? [] : [$roles];
}
foreach ($roles as $role) {
$normalized = strtolower(trim(str_replace([' ', '-'], '_', (string) $role)));
if ($normalized === 'principal') {
return true;
}
}
return false;
}
private function nextDraftVersion(array $draft): int private function nextDraftVersion(array $draft): int
{ {
$query = $this->examDraftModel $query = $this->examDraftModel
@@ -1307,9 +1423,14 @@ class ExamDraftController extends BaseController
$base = pathinfo($sourcePath, PATHINFO_FILENAME); $base = pathinfo($sourcePath, PATHINFO_FILENAME);
$targetPath = $targetDir . '/' . $base . '.pdf'; $targetPath = $targetDir . '/' . $base . '.pdf';
if (!function_exists('exec')) {
log_message('warning', 'ExamDraftController::convertDocToPdf skipped because exec() is unavailable.');
return is_file($targetPath) ? basename($targetPath) : null;
}
// Attempt conversion via LibreOffice if available // Attempt conversion via LibreOffice if available
$cmd = 'soffice --headless --convert-to pdf --outdir ' . escapeshellarg($targetDir) . ' ' . escapeshellarg($sourcePath) . ' 2>/dev/null'; $cmd = 'soffice --headless --convert-to pdf --outdir ' . escapeshellarg($targetDir) . ' ' . escapeshellarg($sourcePath) . ' 2>/dev/null';
@exec($cmd); @\exec($cmd);
return is_file($targetPath) ? basename($targetPath) : null; return is_file($targetPath) ? basename($targetPath) : null;
} }
@@ -1358,6 +1479,11 @@ class ExamDraftController extends BaseController
); );
} }
private function normalizeExamType($value): string
{
return trim((string) $value);
}
private function copyDraftToFinal(string $draftFilename): ?string private function copyDraftToFinal(string $draftFilename): ?string
{ {
$source = $this->fullUploadPath(self::TEACHER_UPLOAD_DIR, $draftFilename); $source = $this->fullUploadPath(self::TEACHER_UPLOAD_DIR, $draftFilename);
+20 -43
View File
@@ -3,6 +3,8 @@
namespace App\Controllers\View; namespace App\Controllers\View;
use App\Controllers\BaseController; use App\Controllers\BaseController;
use App\Libraries\FinancialStatus;
use App\Libraries\InvoiceLedgerService;
use App\Models\AdditionalChargeModel; use App\Models\AdditionalChargeModel;
use CodeIgniter\Controller; use CodeIgniter\Controller;
use App\Models\UserModel; use App\Models\UserModel;
@@ -28,6 +30,7 @@ class ExtraChargesController extends BaseController
protected $studentClassModel; protected $studentClassModel;
protected $enableAttendance; protected $enableAttendance;
protected $attendanceDayModel; protected $attendanceDayModel;
protected $invoiceLedgerService;
public function __construct() public function __construct()
{ {
@@ -39,6 +42,7 @@ class ExtraChargesController extends BaseController
$this->invoiceModel = new InvoiceModel(); $this->invoiceModel = new InvoiceModel();
$this->semester = $this->configModel->getConfig('semester'); $this->semester = $this->configModel->getConfig('semester');
$this->schoolYear = $this->configModel->getConfig('school_year'); $this->schoolYear = $this->configModel->getConfig('school_year');
$this->invoiceLedgerService = new InvoiceLedgerService();
} }
public function index() public function index()
@@ -247,13 +251,9 @@ class ExtraChargesController extends BaseController
// keep status as-is // keep status as-is
]); ]);
// If its already applied on an invoice and the amount changed, reflect the delta if (($row['status'] ?? '') === FinancialStatus::ADDITIONAL_CHARGE_APPLIED && !empty($row['invoice_id'])) {
if ($row['status'] === 'applied' && !empty($row['invoice_id']) && abs($delta) > 0.00001) { $db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $row['invoice_id']]);
if ($delta > 0) { $this->invoiceLedgerService->recalculateInvoice((int) $row['invoice_id']);
$this->invoiceModel->applyAdditionalCharge((int)$row['invoice_id'], $delta);
} else {
$this->invoiceModel->reverseAdditionalCharge((int)$row['invoice_id'], -$delta);
}
} }
$db->transComplete(); $db->transComplete();
@@ -343,7 +343,7 @@ class ExtraChargesController extends BaseController
'description' => trim($data['description'] ?? ''), 'description' => trim($data['description'] ?? ''),
'amount' => $signedAmount, 'amount' => $signedAmount,
'due_date' => !empty($data['due_date']) ? $data['due_date'] : null, '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_by' => (int)(session()->get('user_id') ?? 0),
'created_at' => \CodeIgniter\I18n\Time::now('UTC')->toDateTimeString(), // store UTC 'created_at' => \CodeIgniter\I18n\Time::now('UTC')->toDateTimeString(), // store UTC
]; ];
@@ -357,17 +357,9 @@ class ExtraChargesController extends BaseController
$this->additionalChargeModel->insert($payload); $this->additionalChargeModel->insert($payload);
$chargeId = (int)$this->additionalChargeModel->getInsertID(); $chargeId = (int)$this->additionalChargeModel->getInsertID();
// Apply to invoice if present
if ($invoiceId) { if ($invoiceId) {
try { $this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$invoiceId]);
if ($chargeType === 'add') { $this->invoiceLedgerService->recalculateInvoice($invoiceId);
$this->invoiceModel->applyAdditionalCharge($invoiceId, $amountAbs);
} else {
$this->invoiceModel->deductAdditionalCharge($invoiceId, $amountAbs);
}
} catch (\Throwable $e) {
log_message('error', 'apply/deductAdditionalCharge failed: ' . $e->getMessage());
}
} }
// AFTER // AFTER
@@ -470,23 +462,15 @@ class ExtraChargesController extends BaseController
$this->db->transStart(); $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, [ $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(); $this->db->transComplete();
if (!$this->db->transStatus()) { if (!$this->db->transStatus()) {
@@ -514,26 +498,19 @@ class ExtraChargesController extends BaseController
$chargeType = (string)($row['charge_type'] ?? 'add'); $chargeType = (string)($row['charge_type'] ?? 'add');
$status = (string)($row['status'] ?? 'pending'); $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']); if ($this->wantsJson()) return $this->response->setJSON(['ok' => false, 'error' => 'Nothing to reverse']);
return redirect()->back()->with('error', 'Nothing to reverse.'); return redirect()->back()->with('error', 'Nothing to reverse.');
} }
$this->db->transStart(); $this->db->transStart();
try { $this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$invoiceId]);
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->additionalChargeModel->update((int)$id, [ $this->additionalChargeModel->update((int)$id, [
'status' => 'pending', 'status' => FinancialStatus::ADDITIONAL_CHARGE_PENDING,
'invoice_id' => null, 'invoice_id' => null,
]); ]);
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
$this->db->transComplete(); $this->db->transComplete();
+183 -3
View File
@@ -4,7 +4,6 @@ namespace App\Controllers\View;
use CodeIgniter\Controller; use CodeIgniter\Controller;
use CodeIgniter\Exceptions\PageNotFoundException; use CodeIgniter\Exceptions\PageNotFoundException;
use Config\Database;
class FilesController extends Controller class FilesController extends Controller
{ {
@@ -22,7 +21,11 @@ class FilesController extends Controller
throw PageNotFoundException::forPageNotFound(); 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; $path = WRITEPATH . 'uploads/receipts/' . $name;
if (!is_file($path)) { if (!is_file($path)) {
throw PageNotFoundException::forPageNotFound(); throw PageNotFoundException::forPageNotFound();
@@ -79,7 +82,11 @@ class FilesController extends Controller
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound(); 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; $path = WRITEPATH . 'uploads/reimbursements/' . $name;
if (!is_file($path)) { if (!is_file($path)) {
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound(); throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
@@ -224,6 +231,10 @@ class FilesController extends Controller
throw PageNotFoundException::forPageNotFound(); throw PageNotFoundException::forPageNotFound();
} }
if (!$this->canAccessExamDraftFile($name, $subdir)) {
return $this->response->setStatusCode(403, 'You are not allowed to access this file.');
}
$mime = 'application/octet-stream'; $mime = 'application/octet-stream';
if (function_exists('finfo_open')) { if (function_exists('finfo_open')) {
$fi = finfo_open(FILEINFO_MIME_TYPE); $fi = finfo_open(FILEINFO_MIME_TYPE);
@@ -317,4 +328,173 @@ class FilesController extends Controller
} }
return 'teacher_file'; return 'teacher_file';
} }
private function resolveExamDraftAuthorIdColumn($db): string
{
try {
$fields = $db->getFieldNames('exam_drafts');
if (in_array('teacher_id', $fields, true)) {
return 'teacher_id';
}
if (in_array('author_id', $fields, true)) {
return 'author_id';
}
} catch (\Throwable $e) {
log_message('error', 'FilesController::resolveExamDraftAuthorIdColumn error: ' . $e->getMessage());
}
return 'teacher_id';
}
private function canAccessExamDraftFile(string $filename, string $subdir): bool
{
$userId = (int) (session()->get('user_id') ?? 0);
if ($userId <= 0) {
return false;
}
$role = strtolower((string) (session()->get('role') ?? ''));
if (in_array($role, ['admin', 'administrator', 'principal'], true)) {
return true;
}
$db = Database::connect();
$fileColumn = $subdir === 'finals' ? 'final_file' : $this->resolveExamDraftFileColumn($db);
$authorIdColumn = $this->resolveExamDraftAuthorIdColumn($db);
$draft = $db->table('exam_drafts ed')
->select('ed.class_section_id, ed.school_year, ed.semester, ed.status, ed.' . $authorIdColumn . ' AS draft_author_id')
->where('ed.' . $fileColumn, $filename)
->limit(1)
->get()
->getRowArray();
if (empty($draft)) {
return false;
}
$authorId = (int) ($draft['draft_author_id'] ?? 0);
if ($authorId > 0 && $authorId === $userId) {
return true;
}
$classSectionId = (int) ($draft['class_section_id'] ?? 0);
if ($classSectionId <= 0) {
return false;
}
$status = strtolower(trim((string) ($draft['status'] ?? '')));
if ($subdir === 'drafts' && $status === 'draft') {
return false;
}
$currentSchoolYear = trim((string) (session()->get('school_year') ?? ''));
$currentSemester = trim((string) (session()->get('semester') ?? ''));
$draftSchoolYear = trim((string) ($draft['school_year'] ?? ''));
$draftSemester = trim((string) ($draft['semester'] ?? ''));
$hasCurrentAssignment = $db->table('teacher_class')
->select('id')
->where('teacher_id', $userId)
->where('class_section_id', $classSectionId);
if ($currentSchoolYear !== '') {
$hasCurrentAssignment->where('school_year', $currentSchoolYear);
}
$hasCurrentAssignment = $hasCurrentAssignment->limit(1)->countAllResults() > 0;
if ($hasCurrentAssignment) {
if ($subdir === 'finals') {
return true;
}
return $draftSchoolYear === '' || $currentSchoolYear === '' || $draftSchoolYear === $currentSchoolYear;
}
$assignmentQuery = $db->table('teacher_class')
->select('id')
->where('teacher_id', $userId)
->where('class_section_id', $classSectionId);
if ($draftSchoolYear !== '') {
$assignmentQuery->where('school_year', $draftSchoolYear);
}
$hasDraftYearAssignment = $assignmentQuery->limit(1)->countAllResults() > 0;
if (!$hasDraftYearAssignment) {
return false;
}
if ($subdir === 'finals') {
return true;
}
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
+126 -30
View File
@@ -74,7 +74,7 @@ class InvoiceController extends ResourceController
$this->dueDate = $this->configModel->getConfig('due_date'); $this->dueDate = $this->configModel->getConfig('due_date');
$this->firstStudentFee = (float) ($this->configModel->getConfig('first_student_fee') ?? 350); $this->firstStudentFee = (float) ($this->configModel->getConfig('first_student_fee') ?? 350);
$this->secondStudentFee = (float) ($this->configModel->getConfig('second_student_fee') ?? 200); $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->refundDeadline = date('Y-m-d', strtotime($this->configModel->getConfig('refund_deadline')));
$this->db = \Config\Database::connect(); $this->db = \Config\Database::connect();
$this->request = \Config\Services::request(); $this->request = \Config\Services::request();
@@ -381,18 +381,24 @@ class InvoiceController extends ResourceController
return false; return false;
} }
public function generateInvoice(string $parentId = null) public function generateInvoice(
string $parentId = null,
?string $schoolYearOverride = null,
?string $semesterOverride = null,
bool $recalculateDiscounts = true
)
{ {
$isAjax = $this->request->isAJAX() || str_contains(strtolower($this->request->getHeaderLine('Accept')), 'application/json'); $isAjax = $this->request->isAJAX() || str_contains(strtolower($this->request->getHeaderLine('Accept')), 'application/json');
if ($parentId == null) { if ($parentId == null) {
$parentId = (int)$this->request->getPost('parent_id'); $parentId = (int)$this->request->getPost('parent_id');
} }
$schoolYear = (string) $this->schoolYear; $schoolYear = (string) ($schoolYearOverride ?: $this->schoolYear);
$semester = (string) ($semesterOverride ?: $this->semester);
// Fetch enrolled + withdrawn students // Fetch enrolled + withdrawn students
$enrollments = $this->enrollmentModel $enrollments = $this->enrollmentModel
->where('parent_id', $parentId) ->where('parent_id', $parentId)
->where('school_year', $this->schoolYear) ->where('school_year', $schoolYear)
->findAll(); ->findAll();
if (empty($enrollments)) { if (empty($enrollments)) {
@@ -444,21 +450,23 @@ class InvoiceController extends ResourceController
$tuitionFee = $fees['tuition_fee']; $tuitionFee = $fees['tuition_fee'];
// ✅ Fetch event charges // ✅ Fetch event charges
$eventsList = $this->chargesModel->getChargesWithEventInfo($parentId, $this->schoolYear); $eventsList = $this->chargesModel->getChargesWithEventInfo($parentId, $schoolYear);
$eventchargeTotal = array_sum(array_column($eventsList, 'charged')); $eventchargeTotal = array_sum(array_column($eventsList, 'charged'));
$totalDiscount = $this->recalculateAndUpdateDiscount( $totalDiscount = 0.0;
$parentId, if ($recalculateDiscounts) {
$this->schoolYear, $totalDiscount = $this->recalculateAndUpdateDiscount(
$tuitionFee, $parentId,
$enrollments $schoolYear,
); $tuitionFee,
$enrollments
);
}
$semester = $this->semester;
// ✅ Refunds PAID to the parent for this year (Partial/Paid) // ✅ Refunds PAID to the parent for this year (Partial/Paid)
$refundPaid = (float) $this->refundModel->getTotalApprovedRefundByParentIdAndSchoolYear($parentId, $this->schoolYear); $refundPaid = (float) $this->refundModel->getTotalApprovedRefundByParentIdAndSchoolYear($parentId, $schoolYear);
$totalPaid = $this->paymentModel->getTotalPaidByParentId($parentId, $this->schoolYear); $totalPaid = $this->paymentModel->getTotalPaidByParentId($parentId, $schoolYear);
$discountedTuition = max(0, $tuitionFee); $discountedTuition = max(0, $tuitionFee);
$totalAmount = $discountedTuition + $eventchargeTotal; $totalAmount = $discountedTuition + $eventchargeTotal;
@@ -469,17 +477,22 @@ class InvoiceController extends ResourceController
- $refundPaid // approved refunds paid to parent - $refundPaid // approved refunds paid to parent
- $totalPaid; // payments received - $totalPaid; // payments received
// Your invoice fetch // Business rule: single invoice per parent per school year.
$existingInvoices = $this->invoiceModel->getInvoicesByParentId($parentId, $this->schoolYear); // If legacy duplicates exist, prefer the invoice that already has a discount applied,
// otherwise use the latest invoice for the parent/year.
$invoice = $this->selectActiveInvoiceForParentYear((int)$parentId, $schoolYear);
$updated = false; $updated = false;
$updatedIds = []; $updatedIds = [];
if (!empty($existingInvoices)) { if (!empty($invoice) && isset($invoice['id'])) {
foreach ($existingInvoices as $invoice) { $paymentExclude = ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'];
if (!isset($invoice['id'])) { $paymentsHasStatus = false;
continue; $paymentsHasVoid = false;
} try {
$paymentsHasStatus = $this->db->fieldExists('status', 'payments');
$paymentsHasVoid = $this->db->fieldExists('is_void', 'payments');
} catch (\Throwable $e) {
}
// Preserve applied additional charges and recalc this invoice only // Preserve applied additional charges and recalc this invoice only
$extrasSum = 0.0; $extrasSum = 0.0;
@@ -487,7 +500,7 @@ class InvoiceController extends ResourceController
$rows = $this->db->table('additional_charges') $rows = $this->db->table('additional_charges')
->select('charge_type, amount') ->select('charge_type, amount')
->where('invoice_id', (int)$invoice['id']) ->where('invoice_id', (int)$invoice['id'])
->where('school_year', $this->schoolYear) ->where('school_year', $schoolYear)
->where('status', 'applied') ->where('status', 'applied')
->get()->getResultArray(); ->get()->getResultArray();
foreach ($rows as $r) { foreach ($rows as $r) {
@@ -520,7 +533,7 @@ class InvoiceController extends ResourceController
$r = $this->db->table('refunds') $r = $this->db->table('refunds')
->select('COALESCE(SUM(refund_paid_amount),0) AS tot') ->select('COALESCE(SUM(refund_paid_amount),0) AS tot')
->where('invoice_id', (int)$invoice['id']) ->where('invoice_id', (int)$invoice['id'])
->where('school_year', $this->schoolYear) ->where('school_year', $schoolYear)
->whereIn('status', ['Partial','Paid']) ->whereIn('status', ['Partial','Paid'])
->get()->getRowArray(); ->get()->getRowArray();
$invRefunds = (float)($r['tot'] ?? 0.0); $invRefunds = (float)($r['tot'] ?? 0.0);
@@ -528,8 +541,33 @@ class InvoiceController extends ResourceController
log_message('error', 'refund sum failed for invoice ' . (int)$invoice['id'] . ': ' . $e->getMessage()); log_message('error', 'refund sum failed for invoice ' . (int)$invoice['id'] . ': ' . $e->getMessage());
} }
// Payments recorded on this invoice (denormalized field kept in sync by PaymentController) // Payments recorded on this invoice (sum payments to avoid stale invoice.paid_amount)
$paidOnInv = (float)($invoice['paid_amount'] ?? 0.0); $paidOnInv = 0.0;
try {
$qb = $this->db->table('payments')
->select('COALESCE(SUM(paid_amount),0) AS tot')
->where('invoice_id', (int)$invoice['id'])
->where('paid_amount >', 0);
if ($paymentsHasStatus) {
$qb->groupStart()
->whereNotIn('status', $paymentExclude)
->orWhere('status IS NULL', null, false)
->groupEnd();
}
if ($paymentsHasVoid) {
$qb->groupStart()
->where('is_void', 0)
->orWhere('is_void IS NULL', null, false)
->groupEnd();
}
$row = $qb->get()->getRowArray();
$paidOnInv = (float)($row['tot'] ?? 0.0);
} catch (\Throwable $e) {
log_message('error', 'payment sum failed for invoice ' . (int)$invoice['id'] . ': ' . $e->getMessage());
$paidOnInv = (float)($invoice['paid_amount'] ?? 0.0);
}
$newBalance = $newTotal - $invDiscount - $invRefunds - $paidOnInv; $newBalance = $newTotal - $invDiscount - $invRefunds - $paidOnInv;
$newStatus = ($newBalance <= 0.00001) $newStatus = ($newBalance <= 0.00001)
@@ -547,7 +585,6 @@ class InvoiceController extends ResourceController
$updatedIds[] = (int)$invoice['id']; $updatedIds[] = (int)$invoice['id'];
log_message('info', "Updated invoice ID {$invoice['id']} for parent ID {$parentId}."); log_message('info', "Updated invoice ID {$invoice['id']} for parent ID {$parentId}.");
$updated = true; $updated = true;
}
} else { } else {
// Generate invoice number // Generate invoice number
$schoolId = $this->userModel->getSchoolIdByUserId($parentId); $schoolId = $this->userModel->getSchoolIdByUserId($parentId);
@@ -578,7 +615,7 @@ class InvoiceController extends ResourceController
// Initial balance equals the created total; discounts/refunds/payments will adjust later // Initial balance equals the created total; discounts/refunds/payments will adjust later
'balance' => $totalAmount, 'balance' => $totalAmount,
'status' => 'Unpaid', 'status' => 'Unpaid',
'school_year' => $this->schoolYear, 'school_year' => $schoolYear,
'semester' => $semester, 'semester' => $semester,
'issue_date' => $issueUtc, 'issue_date' => $issueUtc,
'due_date' => $dueUtc, 'due_date' => $dueUtc,
@@ -615,6 +652,47 @@ class InvoiceController extends ResourceController
->with('success', $updated ? 'Invoice updated.' : 'Invoice created.'); ->with('success', $updated ? 'Invoice updated.' : 'Invoice created.');
} }
private function selectActiveInvoiceForParentYear(int $parentId, string $schoolYear): ?array
{
if ($parentId <= 0 || $schoolYear === '') {
return null;
}
// Prefer invoices flagged as having discounts.
$invoice = $this->invoiceModel
->where('parent_id', $parentId)
->where('school_year', $schoolYear)
->where('has_discount', 1)
->orderBy('id', 'DESC')
->first();
if (!empty($invoice)) {
return $invoice;
}
// Fallback: prefer invoices with discount_usages rows.
try {
$row = $this->db->table('invoices i')
->select('i.*')
->join('discount_usages du', 'du.invoice_id = i.id', 'inner')
->where('i.parent_id', $parentId)
->where('i.school_year', $schoolYear)
->orderBy('i.id', 'DESC')
->get()
->getRowArray();
if (!empty($row)) {
return $row;
}
} catch (\Throwable $e) {
}
// Final fallback: latest invoice for parent/year.
return $this->invoiceModel
->where('parent_id', $parentId)
->where('school_year', $schoolYear)
->orderBy('id', 'DESC')
->first();
}
private function recalculateAndUpdateDiscount( private function recalculateAndUpdateDiscount(
int $parentId, int $parentId,
string $schoolYear, string $schoolYear,
@@ -678,7 +756,7 @@ class InvoiceController extends ResourceController
log_message('error', 'additional_charges sum failed for discount recalculation invoice ' . (int)$invoice['id'] . ': ' . $e->getMessage()); log_message('error', 'additional_charges sum failed for discount recalculation invoice ' . (int)$invoice['id'] . ': ' . $e->getMessage());
} }
$baseTotal = round($tuitionFee + $eventchargeTotal + $extrasSum, 2); $baseTotal = round($tuitionFee + $extrasSum, 2);
// Recalculate discount // Recalculate discount
if ($discountUsage['discount_type'] === 'percent') { if ($discountUsage['discount_type'] === 'percent') {
@@ -1266,6 +1344,12 @@ class InvoiceController extends ResourceController
} }
} }
} }
if ($studentName === 'N/A') {
$externalName = trim((string)($event['external_firstname'] ?? '') . ' ' . (string)($event['external_lastname'] ?? ''));
if ($externalName !== '') {
$studentName = $externalName . ' (external)';
}
}
$dt = $toLocal($event['created_at'] ?? null, false); $dt = $toLocal($event['created_at'] ?? null, false);
$amount = (float)($event['charged'] ?? 0.0); $amount = (float)($event['charged'] ?? 0.0);
@@ -1612,12 +1696,24 @@ private function getGradeLevel($grade): array
$invoice['last_payment_date'] = $lastPayments[$invoice['id']]['last_payment_date'] ?? null; $invoice['last_payment_date'] = $lastPayments[$invoice['id']]['last_payment_date'] ?? null;
} }
$invoiceEventCharges = [];
foreach ($invoices as $invoice) {
$year = $invoice['school_year'] ?? $this->schoolYear;
$sem = $invoice['semester'] ?? $this->semester;
$invoiceEventCharges[(int)$invoice['id']] = $this->chargesModel->getChargesWithEventInfo(
$invoice['parent_id'],
$year,
$sem
);
}
return view('/parent/invoice_payment', [ return view('/parent/invoice_payment', [
'invoices' => $invoices, 'invoices' => $invoices,
'schoolYears' => $schoolYears, 'schoolYears' => $schoolYears,
'selectedYear' => $selectedYear, 'selectedYear' => $selectedYear,
'currentSchoolYear' => $currentSchoolYear, 'currentSchoolYear' => $currentSchoolYear,
'dueDate' => $this->dueDate 'dueDate' => $this->dueDate,
'invoiceEventCharges' => $invoiceEventCharges,
]); ]);
} }
+25 -6
View File
@@ -1797,16 +1797,34 @@ $existing = $this->studentModel
$activeEventCount = is_array($activeEvents) ? count($activeEvents) : 0; $activeEventCount = is_array($activeEvents) ? count($activeEvents) : 0;
// Get charges (participation info) // Get charges (participation info)
$chargesList = $this->chargesModel->getChargesWithEventInfo($parentId, $schoolYear); $chargesList = $this->chargesModel->getChargesWithEventInfo($parentId, $schoolYear, $semester);
// Build a map: "studentId:eventId" => [ 'participation' => ..., 'date' => ... ] // Build a map: "studentId:eventId" => [ 'participation' => ..., 'date' => ... ]
$charges = []; $charges = [];
$externalParticipantsByEvent = [];
foreach ($chargesList as $charge) { foreach ($chargesList as $charge) {
$key = $charge['student_id'] . ':' . $charge['event_id']; $studentId = $charge['student_id'] ?? null;
$charges[$key] = [ $eventId = (int) ($charge['event_id'] ?? 0);
'participation' => $charge['participation'],
'date' => $charge['updated_at'] ?? $charge['created_at'] // Use updated_at if available if (!empty($studentId)) {
]; $key = $studentId . ':' . $eventId;
$charges[$key] = [
'participation' => $charge['participation'],
'date' => $charge['updated_at'] ?? $charge['created_at'], // Use updated_at if available
];
continue;
}
$externalName = trim((string) ($charge['external_firstname'] ?? '') . ' ' . (string) ($charge['external_lastname'] ?? ''));
if ($eventId > 0 && $externalName !== '') {
$externalParticipantsByEvent[$eventId][] = [
'name' => $externalName,
'note' => (string) ($charge['external_note'] ?? ''),
'participation' => (string) ($charge['participation'] ?? ''),
'event_paid' => !empty($charge['event_paid']),
'charged' => (float) ($charge['charged'] ?? ($charge['event_amount'] ?? 0)),
];
}
} }
// Get enrolled students // Get enrolled students
@@ -1815,6 +1833,7 @@ $existing = $this->studentModel
return view('parent/event_participation', [ return view('parent/event_participation', [
'activeEvents' => $activeEvents, 'activeEvents' => $activeEvents,
'charges' => $charges, 'charges' => $charges,
'externalParticipantsByEvent' => $externalParticipantsByEvent,
'yourStudents' => $students, 'yourStudents' => $students,
'activeEventCount' => $activeEventCount, 'activeEventCount' => $activeEventCount,
]); ]);
+153 -539
View File
@@ -2,6 +2,9 @@
namespace App\Controllers\View; namespace App\Controllers\View;
use App\Libraries\FinancialAttachmentService;
use App\Libraries\FinancialStatus;
use App\Libraries\InvoiceLedgerService;
use App\Models\PaymentModel; use App\Models\PaymentModel;
use App\Models\AdditionalChargeModel; use App\Models\AdditionalChargeModel;
use App\Models\ClassSectionModel; use App\Models\ClassSectionModel;
@@ -16,23 +19,14 @@ use App\Models\PaymentErrorModel;
use App\Models\InvoiceModel; use App\Models\InvoiceModel;
use App\Models\TeacherClassModel; use App\Models\TeacherClassModel;
use App\Models\DiscountUsageModel; 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\RESTful\ResourceController;
use CodeIgniter\Events\Events; use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\PageNotFoundException;
class PaymentController extends ResourceController class PaymentController extends ResourceController
{ {
protected $paymentModel; protected $paymentModel;
protected $paypalConfig;
protected $apiContext;
protected $request; protected $request;
protected $db; protected $db;
protected $invoiceModel; protected $invoiceModel;
@@ -51,6 +45,8 @@ class PaymentController extends ResourceController
protected $discountUsageModel; protected $discountUsageModel;
protected $additionalChargeModel; protected $additionalChargeModel;
protected $classSectionModel; protected $classSectionModel;
protected $invoiceLedgerService;
protected $financialAttachmentService;
public function __construct() public function __construct()
{ {
@@ -60,7 +56,6 @@ class PaymentController extends ResourceController
$this->eventChargesModel = new EventChargesModel(); $this->eventChargesModel = new EventChargesModel();
$this->manualPaymentModel = new ManualPaymentModel(); $this->manualPaymentModel = new ManualPaymentModel();
$this->paymentModel = new PaymentModel(); $this->paymentModel = new PaymentModel();
$this->paypalConfig = new PaypalConfig();
$this->request = \Config\Services::request(); $this->request = \Config\Services::request();
$this->db = \Config\Database::connect(); $this->db = \Config\Database::connect();
$this->invoiceModel = new InvoiceModel(); $this->invoiceModel = new InvoiceModel();
@@ -73,20 +68,9 @@ class PaymentController extends ResourceController
$this->installmentDate = $this->configModel->getConfig('installment_date'); $this->installmentDate = $this->configModel->getConfig('installment_date');
$this->discountUsageModel = new DiscountUsageModel(); $this->discountUsageModel = new DiscountUsageModel();
$this->additionalChargeModel = new AdditionalChargeModel(); $this->additionalChargeModel = new AdditionalChargeModel();
$this->classSectionModel = new ClassSectionModel(); $this->classSectionModel = new ClassSectionModel();
$this->invoiceLedgerService = new InvoiceLedgerService();
// Set up PayPal API context $this->financialAttachmentService = new FinancialAttachmentService();
$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']
]);
} }
// API: Create a new payment plan // API: Create a new payment plan
@@ -185,135 +169,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() public function redirectPage()
{ {
$modeCheck = $this->configModel->getConfig('paypal_mode'); return redirect()
->to(site_url('parent/invoice_payment'))
$parentId = session()->get('user_id'); // assuming this is the logged-in parent ->with('info', 'Online payment is currently unavailable. Please contact the school office to complete payment.');
// 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');
} }
public function manual() public function manual()
@@ -329,11 +189,7 @@ class PaymentController extends ResourceController
// Handle file upload if present // Handle file upload if present
$proof = $this->request->getFile('proof'); $proof = $this->request->getFile('proof');
if ($proof && $proof->isValid() && !$proof->hasMoved()) { $data['proof_path'] = $this->financialAttachmentService->saveUploadedFile($proof, 'payments');
$filename = $proof->getRandomName();
$proof->move(WRITEPATH . 'uploads/payments/', $filename);
$data['proof_path'] = $filename;
}
$this->manualPaymentModel->insert($data); $this->manualPaymentModel->insert($data);
@@ -1057,26 +913,13 @@ class PaymentController extends ResourceController
// Optional receipt upload // Optional receipt upload
$checkFile = null; $checkFile = null;
$paymentFile = $this->request->getFile('payment_file'); $paymentFile = $this->request->getFile('payment_file');
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) { try {
$okTypes = ['image/jpeg', 'image/png', 'application/pdf']; $checkFile = $this->financialAttachmentService->saveUploadedFile(
$okExts = ['jpg', 'jpeg', 'png', 'pdf']; $paymentFile,
$paymentMethod === 'check' ? 'checks' : ($paymentMethod === 'card' ? 'cards' : 'misc')
$mime = $paymentFile->getMimeType(); );
$ext = strtolower($paymentFile->getClientExtension()); } catch (\RuntimeException $e) {
return redirect()->back()->withInput()->with('error', $e->getMessage());
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;
} }
$this->db->transBegin(); $this->db->transBegin();
@@ -1096,10 +939,7 @@ class PaymentController extends ResourceController
$invYear = (string)($row['school_year'] ?? $this->schoolYear); $invYear = (string)($row['school_year'] ?? $this->schoolYear);
// Recompute invoice totals from tuition + events + additional charges // Recompute invoice totals from tuition + events + additional charges
$this->recalculateInvoice($invoiceId, $invYear); $currentBalance = (float) $this->invoiceLedgerService->recalculateInvoice($invoiceId)['balance'];
// Authoritative balance
$currentBalance = $this->getCurrentInvoiceBalance($invoiceId);
if ($amount > $currentBalance + 0.00001) { if ($amount > $currentBalance + 0.00001) {
$this->db->transRollback(); $this->db->transRollback();
@@ -1135,7 +975,9 @@ class PaymentController extends ResourceController
$this->schoolYear, $this->schoolYear,
$this->semester, $this->semester,
$checkNumber, $checkNumber,
$installmentSeq $installmentSeq,
(array) $this->invoiceModel->find($invoiceId),
$currentBalance
); );
if (!$ok) { if (!$ok) {
@@ -1144,11 +986,10 @@ class PaymentController extends ResourceController
} }
// Ensure invoice totals/balance reflect discounts and this payment // Ensure invoice totals/balance reflect discounts and this payment
$this->recalculateInvoice($invoiceId, $this->schoolYear); $ledger = $this->invoiceLedgerService->recalculateInvoice($invoiceId);
// Post-payment balance from snapshot // Post-payment balance from snapshot
$postBalance = (float)round($initialPreBalance - $amount, 2); $postBalance = (float) ($ledger['balance'] ?? max(0.0, round($initialPreBalance - $amount, 2)));
if ($postBalance < 0) $postBalance = 0.0;
// Optional enrollment update // Optional enrollment update
$enrollmentupdated = $this->updateEnrollmentStatusIfPaid($invoiceId); $enrollmentupdated = $this->updateEnrollmentStatusIfPaid($invoiceId);
@@ -1235,20 +1076,21 @@ class PaymentController extends ResourceController
$checkFile = $payment['check_file']; // default keep old file $checkFile = $payment['check_file']; // default keep old file
// Handle optional check or card payment receipt upload // Handle optional check or card payment receipt upload
if (strtolower($paymentMethod) === 'check') { try {
$paymentFile = $this->request->getFile('payment_file'); // ✅ Updated to payment_file $paymentFile = $this->request->getFile('payment_file');
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) { if (strtolower($paymentMethod) === 'check') {
$fileName = $paymentFile->getRandomName(); $uploaded = $this->financialAttachmentService->saveUploadedFile($paymentFile, 'checks');
$paymentFile->move(WRITEPATH . 'uploads/checks/', $fileName); if ($uploaded !== null) {
$checkFile = $fileName; $checkFile = $uploaded;
} }
} elseif (strtolower($paymentMethod) === 'card') { } elseif (strtolower($paymentMethod) === 'card') {
$paymentFile = $this->request->getFile('payment_file'); // ✅ Updated to payment_file $uploaded = $this->financialAttachmentService->saveUploadedFile($paymentFile, 'cards');
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) { if ($uploaded !== null) {
$fileName = $paymentFile->getRandomName(); $checkFile = $uploaded;
$paymentFile->move(WRITEPATH . 'uploads/cards/', $fileName); }
$checkFile = $fileName; // reuse for compatibility
} }
} catch (\RuntimeException $e) {
return redirect()->back()->withInput()->with('error', $e->getMessage());
} }
// ❌ Validate amount - negative or zero // ❌ Validate amount - negative or zero
@@ -1259,41 +1101,51 @@ class PaymentController extends ResourceController
); );
} }
// 🔄 Recalculate invoice first to ensure totals reflect tuition + events + additional $this->db->transBegin();
$this->recalculateInvoice($payment['invoice_id'], $this->schoolYear);
// 🔄 Get current balance based on actual payments (with school_year filter) try {
// We need to calculate what the balance would be WITHOUT the current payment being edited $invoiceId = (int) ($payment['invoice_id'] ?? 0);
$currentBalance = $this->getCurrentInvoiceBalanceExcludingPayment($payment['invoice_id'], $paymentId); $lockedInvoice = $this->db->query(
'SELECT id FROM invoices WHERE id = ? FOR UPDATE',
[$invoiceId]
)->getRowArray();
if ($paidAmount > $currentBalance) { if (!$lockedInvoice) {
return redirect()->back()->with( $this->db->transRollback();
'error', return redirect()->back()->with('error', 'Linked invoice not found.');
'Entered amount (' . number_format($paidAmount, 2) . ') exceeds remaining balance (' . number_format($currentBalance, 2) . ').' }
);
$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) . ').'
);
}
$updateData = [
'paid_amount' => $paidAmount,
'payment_method' => strtolower($paymentMethod),
'check_file' => $checkFile,
'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'),
];
$this->paymentModel->update($paymentId, $updateData);
$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.');
} }
// ✅ Update edited payment with check_number
$updateData = [
'paid_amount' => $paidAmount,
'payment_method' => strtolower($paymentMethod),
'check_file' => $checkFile,
'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);
return redirect()->back()->with('success', 'Payment updated successfully.');
} }
@@ -1302,164 +1154,7 @@ class PaymentController extends ResourceController
*/ */
private function recalculateInvoice($invoiceId, $schoolYear) private function recalculateInvoice($invoiceId, $schoolYear)
{ {
$invoice = $this->invoiceModel->find($invoiceId); $this->invoiceLedgerService->recalculateInvoice((int) $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,
]);
} }
/** /**
@@ -1521,106 +1216,28 @@ class PaymentController extends ResourceController
/** Get current invoice balance = total - payments - discounts - refundsPaid (no school_year filter). */ /** Get current invoice balance = total - payments - discounts - refundsPaid (no school_year filter). */
private function getCurrentInvoiceBalance(int $invoiceId): float private function getCurrentInvoiceBalance(int $invoiceId): float
{ {
$invoice = $this->invoiceModel->find($invoiceId); try {
if (!$invoice) return 0.0; return (float) ($this->invoiceLedgerService->calculateInvoice($invoiceId)['balance'] ?? 0.0);
} catch (\Throwable $e) {
$db = $this->db; return 0.0;
$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();
} }
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. */ /** Balance excluding a specific payment (for edit scenarios) and subtracting discounts/refunds. */
private function getCurrentInvoiceBalanceExcludingPayment(int $invoiceId, int $excludePaymentId): float private function getCurrentInvoiceBalanceExcludingPayment(int $invoiceId, int $excludePaymentId): float
{ {
$invoice = $this->invoiceModel->find($invoiceId); $payment = $this->paymentModel->find($excludePaymentId);
if (!$invoice) return 0.0; if (!$payment) {
return $this->getCurrentInvoiceBalance($invoiceId);
$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();
} }
if ($hasVoid) { $currentBalance = $this->getCurrentInvoiceBalance($invoiceId);
$qb->groupStart() $status = FinancialStatus::normalizePaymentStatus($payment['status'] ?? null);
->where('is_void', 0) if (in_array($status, FinancialStatus::EXCLUDED_PAYMENT_STATUSES, true)) {
->orWhere('is_void IS NULL', null, false) return $currentBalance;
->groupEnd();
} }
$row = $qb->first(); return max(0.0, round($currentBalance + (float) ($payment['paid_amount'] ?? 0), 2));
$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));
} }
@@ -1655,9 +1272,11 @@ class PaymentController extends ResourceController
$schoolYear = null, $schoolYear = null,
$semester = null, $semester = null,
$checkNumber = 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) { if (!$invoice) {
return false; return false;
} }
@@ -1678,49 +1297,26 @@ class PaymentController extends ResourceController
} }
// Compute new totals $preBalance = $currentBalance ?? $this->getCurrentInvoiceBalance((int) $invoiceId);
$newPaid = (float) $invoice['paid_amount'] + (float) $amount; $newBalance = max(0.0, round($preBalance - (float) $amount, 2));
$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
}
// 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 = [ $paymentData = [
'parent_id' => $invoice['parent_id'], 'parent_id' => $invoice['parent_id'],
'invoice_id' => $invoiceId, 'invoice_id' => $invoiceId,
'total_amount' => $invoice['total_amount'], 'total_amount' => $invoice['total_amount'],
'paid_amount' => $amount, 'paid_amount' => $amount,
'balance' => $newBalance, 'balance' => $newBalance,
'number_of_installments' => $installmentSeq, // <-- installment sequence (1,2,3,...) 'number_of_installments' => $installmentSeq, // <-- installment sequence (1,2,3,...)
'transaction_id' => $transactionId, 'installment_seq' => $installmentSeq,
'payment_method' => strtolower($paymentMethod), 'transaction_id' => $transactionId,
'payment_date' => $paymentDate, 'payment_method' => strtolower($paymentMethod),
'status' => $paymentStatus, 'payment_date' => $paymentDate,
'check_file' => $checkFile, 'status' => FinancialStatus::PAYMENT_RECORDED,
'check_number' => (strtolower($paymentMethod) === 'check') ? $checkNumber : null, 'check_file' => $checkFile,
'updated_by' => session()->get('user_id'), 'check_number' => (strtolower($paymentMethod) === 'check') ? $checkNumber : null,
'school_year' => $schoolYear ?? $this->schoolYear, 'updated_by' => session()->get('user_id'),
'semester' => $semester ?? $this->semester, 'school_year' => $schoolYear ?? $this->schoolYear,
// 'installment_index' => $installmentSeq, // use if you add a dedicated column later 'semester' => $semester ?? $this->semester,
]; ];
if (!$this->paymentModel->insert($paymentData)) { if (!$this->paymentModel->insert($paymentData)) {
@@ -1741,35 +1337,53 @@ class PaymentController extends ResourceController
->countAllResults(); ->countAllResults();
} }
public function serveCheckFile($filename, $mode = 'download') public function servePaymentFile(int $paymentId, string $mode = 'download')
{ {
$filename = basename($filename); $payment = $this->paymentModel->find($paymentId);
$roots = [ if (!$payment || empty($payment['check_file'])) {
WRITEPATH . 'uploads/checks/' . $filename, throw PageNotFoundException::forPageNotFound('Payment file not found.');
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;
}
} }
if (!$path) { if (!$this->canViewPayment($payment)) {
throw new \CodeIgniter\Exceptions\PageNotFoundException('Payment file not found: ' . esc($filename)); 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') { if ($mode === 'inline') {
return $this->response return $this->response
->setHeader('Content-Type', mime_content_type($path)) ->setHeader('Content-Type', $this->financialAttachmentService->detectMime($path))
->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"') ->setHeader('Content-Disposition', 'inline; filename="' . basename($path) . '"')
->setBody(file_get_contents($path)); ->setBody(file_get_contents($path));
} }
return $this->response->download($path, null); 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;
}
}
+176 -44
View File
@@ -3,12 +3,15 @@
namespace App\Controllers\View; namespace App\Controllers\View;
use App\Controllers\BaseController; use App\Controllers\BaseController;
use App\Libraries\FinancialAttachmentService;
use App\Libraries\InvoiceLedgerService;
use App\Models\RefundModel; use App\Models\RefundModel;
use App\Models\UserModel; use App\Models\UserModel;
use App\Models\PaymentModel; use App\Models\PaymentModel;
use App\Models\ConfigurationModel; use App\Models\ConfigurationModel;
use App\Models\InvoiceModel; use App\Models\InvoiceModel;
use App\Models\EnrollmentModel; use App\Models\EnrollmentModel;
use CodeIgniter\Exceptions\PageNotFoundException;
class RefundController extends BaseController class RefundController extends BaseController
{ {
@@ -18,6 +21,8 @@ class RefundController extends BaseController
protected ConfigurationModel $configModel; protected ConfigurationModel $configModel;
protected InvoiceModel $invoiceModel; protected InvoiceModel $invoiceModel;
protected EnrollmentModel $enrollmentModel; protected EnrollmentModel $enrollmentModel;
protected InvoiceLedgerService $invoiceLedgerService;
protected FinancialAttachmentService $financialAttachmentService;
protected $db; protected $db;
// Allowed request types (mapped to your `refunds.request` column) // Allowed request types (mapped to your `refunds.request` column)
@@ -33,6 +38,8 @@ class RefundController extends BaseController
$this->configModel = new ConfigurationModel(); $this->configModel = new ConfigurationModel();
$this->invoiceModel = new InvoiceModel(); $this->invoiceModel = new InvoiceModel();
$this->enrollmentModel = new EnrollmentModel(); $this->enrollmentModel = new EnrollmentModel();
$this->invoiceLedgerService = new InvoiceLedgerService();
$this->financialAttachmentService = new FinancialAttachmentService();
$this->db = \Config\Database::connect(); $this->db = \Config\Database::connect();
} }
@@ -445,6 +452,14 @@ class RefundController extends BaseController
return $this->response->setJSON(['error' => 'Failed to create refund request.']); 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 // Fire refundPending notification/event for newly created refunds
try { try {
$user = $this->userModel->select('id, email, firstname, lastname')->find($parentId) ?: []; $user = $this->userModel->select('id, email, firstname, lastname')->find($parentId) ?: [];
@@ -467,13 +482,36 @@ class RefundController extends BaseController
// Approve refund (no money movement) // Approve refund (no money movement)
public function approveRefund(int $refundId) public function approveRefund(int $refundId)
{ {
$ok = $this->refundModel->update($refundId, [ $refund = $this->refundModel->find($refundId);
'status' => 'Approved', if (!$refund) {
'approved_at' => utc_now(), return $this->response->setJSON(['error' => 'Refund not found']);
'approved_by' => session()->get('user_id'), }
'updated_at' => utc_now(),
'updated_by' => session()->get('user_id'), $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(),
'approved_by' => session()->get('user_id'),
'updated_at' => utc_now(),
'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']); return $this->response->setJSON($ok ? ['success' => 'Refund approved'] : ['error' => 'Approve failed']);
} }
@@ -481,13 +519,36 @@ class RefundController extends BaseController
// Reject refund // Reject refund
public function rejectRefund(int $refundId) public function rejectRefund(int $refundId)
{ {
$ok = $this->refundModel->update($refundId, [ $refund = $this->refundModel->find($refundId);
'status' => 'Rejected', if (!$refund) {
'approved_at' => utc_now(), return $this->response->setJSON(['error' => 'Refund not found']);
'approved_by' => session()->get('user_id'), }
'updated_at' => utc_now(),
'updated_by' => session()->get('user_id'), $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(),
'approved_by' => session()->get('user_id'),
'updated_at' => utc_now(),
'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']); return $this->response->setJSON($ok ? ['success' => 'Refund rejected'] : ['error' => 'Reject failed']);
} }
@@ -526,17 +587,21 @@ class RefundController extends BaseController
// Optional file upload for Check // Optional file upload for Check
$checkFileName = $refund['check_file'] ?? null; $checkFileName = $refund['check_file'] ?? null;
if ($refundMethod === 'Check') { if ($refundMethod === 'Check') {
$checkFile = $this->request->getFile('check_file'); try {
if ($checkFile && $checkFile->isValid() && !$checkFile->hasMoved()) { $checkFile = $this->request->getFile('check_file');
$checkFileName = $checkFile->getRandomName(); $uploaded = $this->financialAttachmentService->saveUploadedFile($checkFile, 'checks');
$checkFile->move(WRITEPATH . 'uploads/checks/', $checkFileName); if ($uploaded !== null) {
$checkFileName = $uploaded;
}
} catch (\RuntimeException $e) {
return $this->response->setJSON(['error' => $e->getMessage()]);
} }
} }
$newStatus = ($total < $target) ? 'Partial' : 'Paid'; $newStatus = ($total < $target) ? 'Partial' : 'Paid';
$db = db_connect(); $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 // 0) If this refund is not tied to an invoice yet, assign it to the most overpaid invoice
$assignInvoiceId = null; $assignInvoiceId = null;
@@ -595,26 +660,32 @@ class RefundController extends BaseController
} }
} }
// 1) Update refund row try {
$this->refundModel->update($refundId, [ $affectedInvoiceId = (int) ($assignInvoiceId ?? $refund['invoice_id'] ?? 0);
'refund_paid_amount' => $total, if ($affectedInvoiceId > 0) {
'status' => $newStatus, $db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$affectedInvoiceId]);
'refunded_at' => utc_now(), }
'updated_at' => utc_now(),
'updated_by' => session()->get('user_id'),
'refund_method' => $refundMethod,
'check_nbr' => $checkNbr,
'check_file' => $checkFileName,
// tie to invoice if determined
'invoice_id' => $assignInvoiceId ?? $refund['invoice_id'],
]);
// 2) Optional: If you want an accounting journal entry for payouts, write to a dedicated table. $this->refundModel->update($refundId, [
// We no longer insert a negative row into payments to avoid schema/validation conflicts. 'refund_paid_amount' => $total,
'status' => $newStatus,
'refunded_at' => utc_now(),
'updated_at' => utc_now(),
'updated_by' => session()->get('user_id'),
'refund_method' => $refundMethod,
'check_nbr' => $checkNbr,
'check_file' => $checkFileName,
'invoice_id' => $affectedInvoiceId ?: null,
]);
$db->transComplete(); if ($affectedInvoiceId > 0) {
$this->invoiceLedgerService->recalculateInvoice($affectedInvoiceId);
}
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.']); return $this->response->setJSON(['error' => 'Failed to update payment.']);
} }
@@ -770,16 +841,77 @@ class RefundController extends BaseController
return $this->response->setJSON(['error' => 'Refund not found.']); return $this->response->setJSON(['error' => 'Refund not found.']);
} }
$ok = $this->refundModel->update($refundId, [ $this->db->transBegin();
'status' => $status,
'reason' => $reason, try {
'approved_at' => utc_now(), if (!empty($refund['invoice_id'])) {
'approved_by' => session()->get('user_id'), $this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $refund['invoice_id']]);
'updated_at' => utc_now(), }
'updated_by' => session()->get('user_id'),
]); $ok = $this->refundModel->update($refundId, [
'status' => $status,
'reason' => $reason,
'approved_at' => utc_now(),
'approved_by' => session()->get('user_id'),
'updated_at' => utc_now(),
'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.'] return $this->response->setJSON($ok ? ['success' => 'Refund status updated successfully.']
: ['error' => 'Failed to update refund status.']); : ['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');
}
} }
+162 -96
View File
@@ -601,153 +601,219 @@ class ReimbursementController extends BaseController
]); ]);
} }
public function updateBatchAssignment() public function updateBatchAssignment()
{ {
if (strtolower($this->request->getMethod()) !== 'post') { if (strtolower($this->request->getMethod()) !== 'post') {
return $this->response->setStatusCode(405)->setJSON([ return $this->response->setStatusCode(405)->setJSON([
'success' => false, 'success' => false,
'error' => 'Method not allowed', 'error' => 'Method not allowed',
]); ]);
} }
$expenseId = (int) $this->request->getPost('expense_id'); $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) { $batchIdRaw = $this->request->getPost('batch_id');
return $this->response->setStatusCode(422)->setJSON([ $batchId = (int) $batchIdRaw;
'success' => false,
'error' => 'Invalid expense id.',
]);
}
$now = date('Y-m-d H:i:s'); $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) {
return $this->response->setStatusCode(422)->setJSON([
'success' => false,
'error' => 'Invalid expense id.',
]);
}
$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 $activeItem = $this->batchItemModel
->where('expense_id', $expenseId) ->where('expense_id', $expenseId)
->where('unassigned_at IS NULL', null, false) ->where('unassigned_at IS NULL', null, false)
->first(); ->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 ($batchId <= 0) {
if ($activeItem) { 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'])) { if (!$reimbursementId && !empty($activeItem['reimbursement_id'])) {
$reimbursementId = (int) $activeItem['reimbursement_id']; $reimbursementId = (int) $activeItem['reimbursement_id'];
} }
} }
$newHash = function_exists('csrf_hash') ? csrf_hash() : null; if (!$this->db->transStatus()) {
return $this->response throw new \RuntimeException('Transaction failed while unassigning batch item.');
->setHeader('X-CSRF-HASH', (string) $newHash) }
->setJSON([
'success' => true, $this->db->transCommit();
'batch_id' => 0,
'admin_id' => null, return $newHashResponse([
'reimbursement_id' => $reimbursementId, 'success' => true,
'csrf_hash' => $newHash, 'batch_id' => 0,
]); 'admin_id' => null,
'reimbursement_id' => $reimbursementId,
]);
} }
$batch = $this->batchModel->find($batchId); $batch = $this->batchModel->find($batchId);
if (!$batch || strtolower((string) ($batch['status'] ?? 'open')) !== 'open') { if (!$batch || strtolower((string) ($batch['status'] ?? 'open')) !== 'open') {
$this->db->transRollback();
return $this->response->setStatusCode(404)->setJSON([ return $this->response->setStatusCode(404)->setJSON([
'success' => false, 'success' => false,
'error' => 'Batch not found or already closed.', 'error' => 'Batch not found or already closed.',
]); ]);
} }
$currentAdmin = $activeItem ? (int) ($activeItem['admin_id'] ?? 0) : null; if (!$reimbursementId) {
$activeSameBatch = $activeItem && (int) ($activeItem['batch_id'] ?? 0) === $batchId; if ($activeItem && !empty($activeItem['reimbursement_id'])) {
if ($activeSameBatch && ($currentAdmin === ($adminId ?? 0))) { $reimbursementId = (int) $activeItem['reimbursement_id'];
$newHash = function_exists('csrf_hash') ? csrf_hash() : null; } else {
return $this->response $reimbursementId = $this->lookupReimbursementId($expenseId);
->setHeader('X-CSRF-HASH', (string) $newHash) }
->setJSON([
'success' => true,
'batch_id' => $batchId,
'admin_id' => $adminId,
'reimbursement_id' => $activeItem['reimbursement_id'] ?? null,
'csrf_hash' => $newHash,
]);
} }
if ($activeSameBatch) { $activeSameBatch = $activeItem && (int) ($activeItem['batch_id'] ?? 0) === $batchId;
if (!$reimbursementId) { $currentAdmin = $activeItem ? (int) ($activeItem['admin_id'] ?? 0) : null;
$reimbursementId = $activeItem['reimbursement_id'] ? (int) $activeItem['reimbursement_id'] : $this->lookupReimbursementId($expenseId); $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.');
} }
$updatePayload = [
$this->db->transCommit();
return $newHashResponse([
'success' => true,
'batch_id' => $batchId,
'admin_id' => $adminId,
'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) {
$this->batchItemModel->update((int) $activeItem['id'], [
'admin_id' => $adminId, 'admin_id' => $adminId,
'assigned_at' => $now, 'assigned_at' => $now,
'reimbursement_id' => $reimbursementId, 'reimbursement_id' => $reimbursementId,
'unassigned_at' => $adminId === null ? $now : null, 'unassigned_at' => 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([
'success' => true,
'batch_id' => $batchId,
'admin_id' => $adminId,
'reimbursement_id' => $reimbursementId,
'csrf_hash' => $newHash,
]);
}
if ($activeItem) { if (!$this->db->transStatus()) {
$this->batchItemModel->update((int) $activeItem['id'], ['unassigned_at' => $now]); throw new \RuntimeException('Transaction failed while updating existing assignment.');
if (!$reimbursementId && !empty($activeItem['reimbursement_id'])) {
$reimbursementId = (int) $activeItem['reimbursement_id'];
} }
$this->db->transCommit();
return $newHashResponse([
'success' => true,
'batch_id' => $batchId,
'admin_id' => $adminId,
'reimbursement_id' => $reimbursementId,
]);
} }
if (!$reimbursementId) { /**
$reimbursementId = $this->lookupReimbursementId($expenseId); * If the item is active in another batch, soft-unassign that row first.
*/
if ($activeItem) {
$this->batchItemModel->update((int) $activeItem['id'], [
'unassigned_at' => $now,
]);
} }
$insertData = [ /**
* 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();
$assignmentData = [
'batch_id' => $batchId, 'batch_id' => $batchId,
'expense_id' => $expenseId, 'expense_id' => $expenseId,
'reimbursement_id' => $reimbursementId, 'reimbursement_id' => $reimbursementId,
'admin_id' => $adminId, 'admin_id' => $adminId,
'assigned_at' => $now, 'assigned_at' => $now,
'unassigned_at' => null,
'school_year' => $this->schoolYear, 'school_year' => $this->schoolYear,
'semester' => $this->semester, 'semester' => $this->semester,
]; ];
try { if ($existingBatchItem) {
$this->batchItemModel->insert($insertData); $this->batchItemModel->update((int) $existingBatchItem['id'], $assignmentData);
} catch (\Throwable $e) { } else {
log_message('error', 'Failed to assign expense #{expense} to batch #{batch}: {msg}', [ $this->batchItemModel->insert($assignmentData);
'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; if (!$this->db->transStatus()) {
throw new \RuntimeException('Transaction failed while saving assignment.');
}
return $this->response $this->db->transCommit();
->setHeader('X-CSRF-HASH', (string) $newHash)
->setJSON([ return $newHashResponse([
'success' => true, 'success' => true,
'batch_id' => $batchId, 'batch_id' => $batchId,
'admin_id' => $adminId, 'admin_id' => $adminId,
'reimbursement_id' => $reimbursementId, 'reimbursement_id' => $reimbursementId,
'csrf_hash' => $newHash, ]);
]); } catch (\Throwable $e) {
$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.',
]);
} }
}
public function lockBatch() public function lockBatch()
{ {
+468 -95
View File
@@ -73,19 +73,6 @@ class ReportCardsController extends PrintablesBaseController
$semesters = array_values(array_filter(array_map(static fn($r) => (string)($r['semester'] ?? ''), $rs))); $semesters = array_values(array_filter(array_map(static fn($r) => (string)($r['semester'] ?? ''), $rs)));
} catch (\Throwable $e) { } catch (\Throwable $e) {
} }
try {
$rs2 = $this->db->table('student_class')
->select('DISTINCT semester', false)
->where('school_year', $year)
->where('semester IS NOT NULL', null, false)
->orderBy('semester', 'ASC')
->get()->getResultArray();
foreach ($rs2 as $r) {
$val = (string)($r['semester'] ?? '');
if ($val !== '' && !in_array($val, $semesters, true)) $semesters[] = $val;
}
} catch (\Throwable $e) {
}
// Ensure standard options are present even if data is missing (so Spring can be selected) // Ensure standard options are present even if data is missing (so Spring can be selected)
$defaults = array_values(array_filter([(string)($this->semester ?? ''), 'Fall', 'Spring'], static fn($v) => $v !== '')); $defaults = array_values(array_filter([(string)($this->semester ?? ''), 'Fall', 'Spring'], static fn($v) => $v !== ''));
foreach ($defaults as $d) { foreach ($defaults as $d) {
@@ -330,18 +317,27 @@ class ReportCardsController extends PrintablesBaseController
$examCommentTypes = $isSecond $examCommentTypes = $isSecond
? ['final'] ? ['final']
: ($isFirst ? ['midterm'] : ['midterm', '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'); $hasCommentReview = $this->db->fieldExists('comment_review', 'score_comments');
$commentSelect = $hasCommentReview $hasCommentSemester = $this->db->fieldExists('semester', 'score_comments');
? 'student_id, score_type, comment, comment_review' $hasCommentUpdatedAt = $this->db->fieldExists('updated_at', 'score_comments');
: 'student_id, score_type, comment'; $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 $commentBuilder = $this->scoreCommentModel
->select($commentSelect) ->select(implode(', ', $commentSelectParts))
->whereIn('student_id', $studentIds) ->whereIn('student_id', $studentIds)
->where('school_year', $year) ->where('school_year', $year);
->whereIn('score_type', $commentTypes); if ($hasCommentUpdatedAt) {
if ($sem !== '') { $commentBuilder->orderBy('updated_at', 'DESC');
$this->applySemesterFilter($commentBuilder, $sem, 'semester');
} }
$commentRows = []; $commentRows = [];
try { try {
@@ -349,25 +345,92 @@ class ReportCardsController extends PrintablesBaseController
} catch (\Throwable $e) { } 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 = []; $commentsByStudent = [];
$commentPriorityByStudent = [];
foreach ($commentRows as $row) { foreach ($commentRows as $row) {
$sid = (int)($row['student_id'] ?? 0); $sid = (int)($row['student_id'] ?? 0);
if ($sid <= 0) { if ($sid <= 0) {
continue; continue;
} }
$typeRaw = strtolower(trim((string)($row['score_type'] ?? '')));
if ($typeRaw === '') { $typeRaw = $normalizeCommentType($row['score_type'] ?? '');
if ($typeRaw === '' || !in_array($typeRaw, $wantedCommentTypes, true)) {
continue; 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 === '') { if ($commentVal === '') {
continue; continue;
} }
$commentsByStudent[$sid][$typeRaw] = $commentVal;
$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); $isNumeric = static fn($v) => $v !== null && $v !== '' && is_numeric($v);
@@ -480,6 +543,20 @@ class ReportCardsController extends PrintablesBaseController
if (trim((string)($commentSet['ptap'] ?? '')) === '') { if (trim((string)($commentSet['ptap'] ?? '')) === '') {
$missing[] = 'PTAP comment'; $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'] ?? '')) === '') { if (trim((string)($commentSet['attendance'] ?? '')) === '') {
$missing[] = 'Attendance comment'; $missing[] = 'Attendance comment';
} }
@@ -858,6 +935,7 @@ class ReportCardsController extends PrintablesBaseController
$studentName = trim(($data['student']['firstname'] ?? '') . ' ' . ($data['student']['lastname'] ?? '')); $studentName = trim(($data['student']['firstname'] ?? '') . ' ' . ($data['student']['lastname'] ?? ''));
$gradeLabel = (string)($data['grade'] ?? ($data['class_section_name'] ?? 'N/A')); $gradeLabel = (string)($data['grade'] ?? ($data['class_section_name'] ?? 'N/A'));
$today = (string)($data['report_date_display'] ?? date('m-d-Y')); $today = (string)($data['report_date_display'] ?? date('m-d-Y'));
$termRank = trim((string)($data['term_rank_display'] ?? ''));
$firstSemScore = $data['first_semester_score'] ?? null; $firstSemScore = $data['first_semester_score'] ?? null;
$secondSemScore = $data['second_semester_score'] ?? ($data['total_score'] ?? null); $secondSemScore = $data['second_semester_score'] ?? ($data['total_score'] ?? null);
$finalAverage = $data['final_average'] ?? null; $finalAverage = $data['final_average'] ?? null;
@@ -993,54 +1071,91 @@ class ReportCardsController extends PrintablesBaseController
$gradeY = $pdf->GetY(); $gradeY = $pdf->GetY();
$gradePad = max(0, 2 - (4 * 0.3528)); // reduce indentation by 4pt $gradePad = max(0, 2 - (4 * 0.3528)); // reduce indentation by 4pt
$drawGradeCell = static function (\FPDF $pdf, float $x, float $y, float $w, float $h, string $label, string $value, float $pad) { $drawGradeCell = static function (
$pdf->Rect($x, $y, $w, $h); \FPDF $pdf,
$pdf->SetXY($x + $pad, $y + 3); float $x,
$pdf->SetFont('Helvetica', 'B', 11); float $y,
$pdf->Write(5, $label . ' '); float $w,
$labelWidth = $pdf->GetStringWidth($label . ' '); float $h,
$pdf->SetFont('Helvetica', '', 12); string $label,
$pdf->SetXY($x + 2 + $labelWidth, $y + 3); string $value,
$pdf->Write(5, $value); float $pad
}; ) {
$pdf->Rect($x, $y, $w, $h);
$pdf->SetXY($x + $pad, $y + 3);
$pdf->SetFont('Helvetica', 'B', 11);
$pdf->Write(5, $label . ' ');
$labelWidth = $pdf->GetStringWidth($label . ' ');
$pdf->SetFont('Helvetica', '', 12);
$pdf->SetXY($x + 2 + $labelWidth, $y + 3);
$pdf->Write(5, $value);
};
$drawRankCell = static function (
\FPDF $pdf,
float $x,
float $y,
float $w,
float $h,
string $rankValue,
float $pad
) {
$rankValue = trim($rankValue) !== '' ? trim($rankValue) : 'N/A';
if ($semNum === 2) { $pdf->Rect($x, $y, $w, $h);
$firstLabel = ' 1st Semester Grade:'; $pdf->SetXY($x + $pad, $y + 3);
$firstValue = $numFmt($firstSemScore) . '/100'; $pdf->SetFont('Helvetica', 'B', 11);
$secondLabel = ' 2nd Semester Grade:'; $pdf->Write(5, ' Class Rank: ');
$secondValue = $numFmt($effectiveSecond) . '/100';
$drawGradeCell($pdf, $gradeX, $gradeY, $gradeCellWidth, $gradeCellHeight, $firstLabel, $firstValue, $gradePad);
$drawGradeCell($pdf, $gradeX + $gradeCellWidth, $gradeY, $gradeCellWidth, $gradeCellHeight, $secondLabel, $secondValue, $gradePad);
} else {
$gradeLabel = ' 1st Semester Grade:';
$gradeValue = $numFmt($effectiveSecond) . '/100';
$drawGradeCell($pdf, $gradeX, $gradeY, $gradeCellWidth, $gradeCellHeight, $gradeLabel, $gradeValue, $gradePad);
}
$pdf->SetY($gradeY + $gradeCellHeight);
$finalScoreRowHeight = 12; $labelWidth = $pdf->GetStringWidth(' Class Rank: ');
$finalScoreEndY = null; $pdf->SetFont('Helvetica', '', 12);
// Show Final Score only for second semester / Spring $pdf->SetXY($x + 2 + $labelWidth, $y + 3);
if ($semNum === 2) { $pdf->Write(5, $rankValue);
$finalLabel = 'Final Score****:'; };
$finalValue = (is_string($finalScoreVal) ? $finalScoreVal : $numFmt($finalScoreVal)) . '/100'; if ($semNum === 2) {
$finalCellWidth = 65; // match Total Semester Days column width $firstLabel = ' 1st Semester Grade:';
$finalCellHeight = $finalScoreRowHeight; $firstValue = $numFmt($firstSemScore) . '/100';
$finalX = $pdf->GetX();
$finalY = $pdf->GetY(); $secondLabel = ' 2nd Semester Grade:';
$pdf->Rect($finalX, $finalY, $finalCellWidth, $finalCellHeight); $secondValue = $numFmt($effectiveSecond) . '/100';
$finalPad = max(0, 2 - (4 * 0.3528)); // reduce indentation by 4pt
$pdf->SetXY($finalX + $finalPad, $finalY + 3); $drawGradeCell($pdf, $gradeX, $gradeY, $gradeCellWidth, $gradeCellHeight, $firstLabel, $firstValue, $gradePad);
$pdf->SetFont('Helvetica', 'B', 11); $drawGradeCell($pdf, $gradeX + $gradeCellWidth, $gradeY, $gradeCellWidth, $gradeCellHeight, $secondLabel, $secondValue, $gradePad);
$pdf->Write(5, ' ' . $finalLabel . ' '); } else {
$finalLabelWidth = $pdf->GetStringWidth(' ' . $finalLabel . ' '); $gradeLabel = ' 1st Semester Grade:';
$pdf->SetFont('Helvetica', '', 12); $gradeValue = $numFmt($effectiveSecond) . '/100';
$pdf->SetXY($finalX + 2 + $finalLabelWidth, $finalY + 3);
$pdf->Write(5, $finalValue); $drawGradeCell($pdf, $gradeX, $gradeY, $gradeCellWidth, $gradeCellHeight, $gradeLabel, $gradeValue, $gradePad);
$pdf->Ln($finalCellHeight);
$finalScoreEndY = $finalY + $finalCellHeight; // Fall: Ranking goes to the right of 1st Semester Grade.
} $drawRankCell($pdf, $gradeX + $gradeCellWidth, $gradeY, $gradeCellWidth, $gradeCellHeight, $termRank, $gradePad);
$scoresEndY = $pdf->GetY(); }
$pdf->SetY($gradeY + $gradeCellHeight);
$finalScoreRowHeight = 12;
$finalScoreEndY = null;
// Show Final Score only for second semester / Spring.
if ($semNum === 2) {
$finalLabel = 'Final Score****:';
$finalValue = (is_string($finalScoreVal) ? $finalScoreVal : $numFmt($finalScoreVal)) . '/100';
$finalCellWidth = 65;
$finalCellHeight = $finalScoreRowHeight;
$finalX = $pdf->GetX();
$finalY = $pdf->GetY();
$finalPad = max(0, 2 - (4 * 0.3528));
$drawGradeCell($pdf, $finalX, $finalY, $finalCellWidth, $finalCellHeight, ' ' . $finalLabel, $finalValue, $finalPad);
// Spring: Ranking goes to the right of Final Score.
$drawRankCell($pdf, $finalX + $finalCellWidth, $finalY, $finalCellWidth, $finalCellHeight, $termRank, $finalPad);
$pdf->SetY($finalY + $finalCellHeight);
$finalScoreEndY = $finalY + $finalCellHeight;
}
$scoresEndY = $pdf->GetY();
// Legend anchored near bottom with a 3mm buffer (dynamic placement) // Legend anchored near bottom with a 3mm buffer (dynamic placement)
$examLegendLabel = ($semNum === 1) ? 'Midterm Exam' : 'Final Exam'; $examLegendLabel = ($semNum === 1) ? 'Midterm Exam' : 'Final Exam';
@@ -1506,10 +1621,16 @@ class ReportCardsController extends PrintablesBaseController
if ($typeRaw === 'attendance_comment') { if ($typeRaw === 'attendance_comment') {
$typeRaw = 'attendance'; $typeRaw = 'attendance';
} }
$reviewVal = trim((string)($row['comment_review'] ?? '')); $rawComment = trim((string)($row['comment'] ?? ''));
$commentVal = $this->db->fieldExists('comment_review', 'score_comments') if ($typeRaw === 'attendance') {
? $reviewVal // Attendance comments must come from score_comments.comment.
: trim((string)($row['comment'] ?? '')); $commentVal = $rawComment;
} else {
$reviewVal = trim((string)($row['comment_review'] ?? ''));
$commentVal = $this->db->fieldExists('comment_review', 'score_comments') && $reviewVal !== ''
? $reviewVal
: $rawComment;
}
if ($commentVal === '') { if ($commentVal === '') {
continue; continue;
} }
@@ -1559,6 +1680,20 @@ class ReportCardsController extends PrintablesBaseController
$firstSemesterScore = $secondSemesterScore; $firstSemesterScore = $secondSemesterScore;
} }
$rankingScore = $secondSemesterScore;
if ($normSemester === 'spring' && is_numeric($firstSemesterScore) && is_numeric($secondSemesterScore)) {
$rankingScore = round(((float)$firstSemesterScore + (float)$secondSemesterScore) / 2, 1);
}
$termRanking = $this->calculateTermRanking(
$studentId,
$sectionCode,
$sectionId,
$refYear,
$refSemester !== '' ? $refSemester : (string)($score['semester'] ?? ''),
$rankingScore
);
// Total semester days from attendance records (max total_attendance within same term) // Total semester days from attendance records (max total_attendance within same term)
$totalSemesterDays = null; $totalSemesterDays = null;
@@ -1566,34 +1701,30 @@ class ReportCardsController extends PrintablesBaseController
$semRange = $this->semesterRangeService->getSemesterRange($refYear, ucfirst($normSemester)); $semRange = $this->semesterRangeService->getSemesterRange($refYear, ucfirst($normSemester));
if ($semRange) { if ($semRange) {
try { try {
$events = $this->calendarModel->getEventsBySchoolYearAndSemester($refYear, $normSemester); // Fetch all events for the year (no semester filter) so that
// no-school events stored with a different semester label or
// NULL semester are still picked up. Date-range filtering below.
$events = $this->calendarModel->getEventsBySchoolYearAndSemester($refYear, null);
$noSchoolDays = []; $noSchoolDays = [];
foreach ($events as $event) { foreach ($events as $event) {
if (empty($event['no_school'])) { if (empty($event['no_school'])) {
continue; continue;
} }
$dateStr = substr((string)($event['date'] ?? ''), 0, 10); $dateStr = substr((string)($event['date'] ?? ''), 0, 10);
if ($dateStr === '') { if ($dateStr === '' || $dateStr < $semRange[0] || $dateStr > $semRange[1]) {
continue;
}
try {
$eventDate = new \DateTime($dateStr);
} catch (\Throwable) {
continue;
}
if ($eventDate->format('N') !== '7') {
continue;
}
if ($dateStr < $semRange[0] || $dateStr > $semRange[1]) {
continue; continue;
} }
$noSchoolDays[$dateStr] = true; $noSchoolDays[$dateStr] = true;
} }
$sundays = $this->listSundays($semRange[0], $semRange[1]); $sundays = $this->listSundays($semRange[0], $semRange[1]);
$anchor = $this->resolveAnchorSunday();
$limit = $semRange[1]; $limit = $semRange[1];
if ($anchor !== '' && $anchor >= $semRange[0]) { // Only cap at "today" while the semester is still in progress.
$limit = min($anchor, $semRange[1]); // Once the semester end date has passed, count all its Sundays.
if ($semRange[1] > date('Y-m-d')) {
$anchor = $this->resolveAnchorSunday();
if ($anchor !== '' && $anchor >= $semRange[0]) {
$limit = min($anchor, $semRange[1]);
}
} }
$totalSemesterDays = 0; $totalSemesterDays = 0;
foreach ($sundays as $date) { foreach ($sundays as $date) {
@@ -1689,12 +1820,254 @@ class ReportCardsController extends PrintablesBaseController
'second_semester_score' => $secondSemesterScore, 'second_semester_score' => $secondSemesterScore,
'first_semester_score' => $firstSemesterScore, 'first_semester_score' => $firstSemesterScore,
'final_average' => $finalAverage, 'final_average' => $finalAverage,
'term_rank' => $termRanking,
'term_rank_display' => $termRanking['display'] ?? null,
'comments' => $commentMap, 'comments' => $commentMap,
'total_score' => $secondSemesterScore, 'total_score' => $secondSemesterScore,
'total_attendance_days' => $totalSemesterDays, 'total_attendance_days' => $totalSemesterDays,
]; ];
} }
private function calculateTermRanking(
int $studentId,
int $sectionCode,
?int $sectionId,
string $schoolYear,
?string $semester,
?float $studentScore
): ?array {
if ($studentId <= 0 || $schoolYear === '' || $studentScore === null) {
return null;
}
$sectionIds = array_values(array_unique(array_filter([
$sectionCode > 0 ? $sectionCode : null,
$sectionId && $sectionId > 0 ? $sectionId : null,
])));
if (empty($sectionIds)) {
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')
->where('ss.school_year', $schoolYear)
->whereIn('ss.student_id', $rosterStudentIds)
->orderBy('ss.updated_at', 'DESC')
->orderBy('ss.id', 'DESC');
if ($semesterForRank !== '') {
$this->applySemesterFilter($builder, $semesterForRank, 'ss.semester');
}
$rows = $builder->get()->getResultArray();
if (empty($rows)) {
return null;
}
$scoresByStudent = [];
foreach ($rows as $row) {
$sid = (int)($row['student_id'] ?? 0);
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' => $rawScore,
'rank_score' => round($rawScore, 1),
'firstname' => $rosterByStudent[$sid]['firstname'],
'lastname' => $rosterByStudent[$sid]['lastname'],
];
}
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, ss.semester_score, ss.updated_at, ss.id')
->where('ss.school_year', $schoolYear)
->whereIn('ss.student_id', $studentIds)
->orderBy('ss.updated_at', 'DESC')
->orderBy('ss.id', 'DESC');
if ($semesterForRank !== '') {
$this->applySemesterExclusion($firstRowsBuilder, $semesterForRank, 'ss.semester');
}
$firstRows = $firstRowsBuilder->get()->getResultArray();
$firstScoresByStudent = [];
foreach ($firstRows as $row) {
$sid = (int)($row['student_id'] ?? 0);
if ($sid <= 0 || !isset($rosterByStudent[$sid]) || isset($firstScoresByStudent[$sid])) {
continue;
}
$scoreVal = $row['semester_score'] ?? null;
if (!is_numeric($scoreVal)) {
continue;
}
$firstScoresByStudent[$sid] = (float)$scoreVal;
}
foreach ($scoresByStudent as $sid => &$rankRow) {
if (!isset($firstScoresByStudent[$sid])) {
unset($scoresByStudent[$sid]);
continue;
}
$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;
}
// 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 {
// 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;
}
return $a['student_id'] <=> $b['student_id'];
});
$position = null;
$previousScore = null;
foreach ($rankable as $index => $row) {
$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 = $currentScore;
}
if ((int)$row['student_id'] === $studentId) {
$total = count($rankable);
return [
'position' => $position,
'total' => $total,
'score' => $currentScore,
'display' => $this->formatOrdinal($position) . ' out of ' . $total,
];
}
}
return null;
}
private function formatOrdinal(?int $value): string
{
$n = (int)$value;
if ($n <= 0) {
return '';
}
$mod100 = $n % 100;
if ($mod100 >= 11 && $mod100 <= 13) {
return $n . 'th';
}
return match ($n % 10) {
1 => $n . 'st',
2 => $n . 'nd',
3 => $n . 'rd',
default => $n . 'th',
};
}
/** /**
* Resolve teacher & TA names for a class section (by PK or code), * Resolve teacher & TA names for a class section (by PK or code),
* relaxing semester/year if needed. Returns ['teacher_name' => string, 'ta_names' => string[]]. * relaxing semester/year if needed. Returns ['teacher_name' => string, 'ta_names' => string[]].
@@ -231,18 +231,36 @@ class ScoreCommentController extends BaseController
$rawCommentsBuilder->groupEnd(); $rawCommentsBuilder->groupEnd();
} }
if (!$isAllSections && $classSectionId > 0) {
// Prefer the exact class-section row over legacy NULL class-section rows.
// Without this, duplicate rows can overwrite each other unpredictably.
$rawCommentsBuilder
->orderBy("CASE WHEN class_section_id = {$classSectionId} THEN 0 ELSE 1 END", '', false)
->orderBy('id', 'DESC');
} else {
$rawCommentsBuilder->orderBy('id', 'DESC');
}
$rawComments = $rawCommentsBuilder->findAll(); $rawComments = $rawCommentsBuilder->findAll();
$existingAttendance = []; $existingAttendance = [];
foreach ($rawComments as $c) { foreach ($rawComments as $c) {
$sid = (int)$c['student_id']; $sid = (int) $c['student_id'];
$typ = (string)$c['score_type']; $typ = strtolower(trim((string) $c['score_type']));
// The query is ordered with the best row first. Do not let legacy/older
// duplicate rows overwrite the selected comment/review.
if (isset($comments[$sid][$typ])) {
continue;
}
$comments[$sid][$typ] = [ $comments[$sid][$typ] = [
'comment' => $c['comment'] ?? null, 'comment' => $c['comment'] ?? null,
'comment_review' => $c['comment_review'] ?? null, 'comment_review' => $c['comment_review'] ?? null,
'commented_by' => $c['commented_by'] ?? null, 'commented_by' => $c['commented_by'] ?? null,
'reviewed_by' => $c['reviewed_by'] ?? null, 'reviewed_by' => $c['reviewed_by'] ?? null,
]; ];
if ($typ === 'attendance') { if ($typ === 'attendance') {
$existingAttendance[$sid] = $c; $existingAttendance[$sid] = $c;
} }
@@ -435,6 +453,16 @@ class ScoreCommentController extends BaseController
$existingQuery->groupEnd(); $existingQuery->groupEnd();
} }
if (is_int($classSectionId) && $classSectionId > 0) {
// Prefer updating the real class-section row. If only a legacy NULL row
// exists, it will be picked next and migrated to the class section below.
$existingQuery
->orderBy("CASE WHEN class_section_id = {$classSectionId} THEN 0 ELSE 1 END", '', false)
->orderBy('id', 'DESC');
} else {
$existingQuery->orderBy('id', 'DESC');
}
$existing = $existingQuery->first(); $existing = $existingQuery->first();
$data = [ $data = [
+504
View File
@@ -0,0 +1,504 @@
<?php
namespace App\Controllers\View;
use App\Controllers\BaseController;
use App\Models\ConfigurationModel;
class TrophyController extends BaseController
{
private const PERCENTILE = 75.0;
protected ConfigurationModel $configModel;
public function __construct()
{
$this->configModel = new ConfigurationModel();
}
public function index()
{
$db = \Config\Database::connect();
$currentYear = $this->configModel->getConfig('school_year') ?? '';
$selectedYear = $this->request->getGet('school_year') ?? $currentYear;
$percentile = (float) ($this->request->getGet('percentile') ?? 75);
$percentile = max(1.0, min(99.0, $percentile));
// Available school years from class assignments so the current year can
// still appear even if fall scores are not fully entered yet.
$years = $db->table('student_class')
->select('school_year')
->distinct()
->orderBy('school_year', 'DESC')
->get()
->getResultArray();
$years = array_column($years, 'school_year');
// Build a fall-score-based projection. We start from class assignments so
// students without a recorded fall score still appear as "not yet
// projected" rather than disappearing from the page.
$rows = $db->table('student_class sc')
->select([
'sc.student_id',
'sc.class_section_id',
'MAX(ss.semester_score) AS fall_score',
'cs.class_section_name',
'CONCAT(s.firstname, " ", s.lastname) AS student_name',
's.school_id',
's.gender',
])
->join('classSection cs', 'cs.class_section_id = sc.class_section_id', 'left')
->join('students s', 's.id = sc.student_id', 'left')
->join(
'semester_scores ss',
'ss.student_id = sc.student_id'
. ' AND ss.class_section_id = sc.class_section_id'
. ' AND ss.school_year = ' . $db->escape($selectedYear)
. ' AND LOWER(ss.semester) = "fall"',
'left'
)
->where('sc.school_year', $selectedYear)
->orderBy('cs.class_section_name', 'ASC')
->orderBy('fall_score', 'DESC')
->orderBy('student_name', 'ASC')
->groupBy('sc.student_id, sc.class_section_id, cs.class_section_name, s.firstname, s.lastname, s.school_id')
->get()
->getResultArray();
// Group rows by class section
$sections = [];
foreach ($rows as $row) {
$sid = (int) ($row['class_section_id'] ?? 0);
$name = $row['class_section_name'] ?? 'Section ' . $sid;
if (!isset($sections[$sid])) {
$sections[$sid] = ['name' => $name, 'students' => []];
}
$sections[$sid]['students'][] = [
'student_id' => (int) $row['student_id'],
'name' => $row['student_name'],
'school_id' => $row['school_id'],
'gender' => $row['gender'] ?? '',
'fall_score' => is_numeric($row['fall_score']) ? (float) $row['fall_score'] : null,
];
}
// Calculate trophy thresholds from fall scores only, then project who is
// currently on track for a year-end trophy.
$classResults = [];
foreach ($sections as $sid => $section) {
usort($section['students'], static function (array $a, array $b): int {
$aScore = $a['fall_score'];
$bScore = $b['fall_score'];
if ($aScore === null && $bScore === null) {
return strcmp($a['name'], $b['name']);
}
if ($aScore === null) {
return 1;
}
if ($bScore === null) {
return -1;
}
return $bScore <=> $aScore ?: strcmp($a['name'], $b['name']);
});
$scores = array_column($section['students'], 'fall_score');
$calc = $this->calculateThreshold($scores, $percentile);
$threshold = $calc['threshold'];
$students = array_map(function (array $student) use ($threshold): array {
$student['projected_trophy'] = $threshold !== null
&& $student['fall_score'] !== null
&& $student['fall_score'] >= $threshold;
return $student;
}, $section['students']);
$scoredCount = count(array_filter(
array_column($students, 'fall_score'),
static fn ($score) => $score !== null
));
$boys = array_filter($students, static fn ($s) => strtolower($s['gender']) === 'male');
$girls = array_filter($students, static fn ($s) => strtolower($s['gender']) === 'female');
$trophyBoys = array_filter($boys, static fn ($s) => $s['projected_trophy']);
$trophyGirls = array_filter($girls, static fn ($s) => $s['projected_trophy']);
$nBoys = count($boys);
$nGirls = count($girls);
$nTrophyBoys = count($trophyBoys);
$nTrophyGirls = count($trophyGirls);
$total = count($students);
$classResults[] = [
'section_id' => $sid,
'section_name' => $section['name'],
'students' => $students,
'threshold' => $threshold,
'trophy_count' => $calc['winners'],
'student_count' => $total,
'scored_count' => $scoredCount,
'method' => $calc['method'],
'boys' => $nBoys,
'girls' => $nGirls,
'trophy_boys' => $nTrophyBoys,
'trophy_girls' => $nTrophyGirls,
'pct_boys' => $total > 0 ? round($nBoys / $total * 100) : 0,
'pct_girls' => $total > 0 ? round($nGirls / $total * 100) : 0,
'pct_trophy_boys' => $nBoys > 0 ? round($nTrophyBoys / $nBoys * 100) : 0,
'pct_trophy_girls' => $nGirls > 0 ? round($nTrophyGirls / $nGirls * 100) : 0,
'pct_trophy_total' => $total > 0 ? round($calc['winners'] / $total * 100): 0,
];
}
return view('administrator/trophy', [
'classResults' => $classResults,
'selectedYear' => $selectedYear,
'selectedPercentile'=> $percentile,
'years' => $years,
]);
}
public function winners()
{
$db = \Config\Database::connect();
$currentYear = $this->configModel->getConfig('school_year') ?? '';
$selectedYear = $this->request->getGet('school_year') ?? $currentYear;
$percentile = (float) ($this->request->getGet('percentile') ?? 75);
$percentile = max(1.0, min(99.0, $percentile));
$years = $db->table('student_class')
->select('school_year')->distinct()
->orderBy('school_year', 'DESC')
->get()->getResultArray();
$years = array_column($years, 'school_year');
$ey = $db->escape($selectedYear);
$rows = $db->table('student_class sc')
->select([
'sc.student_id',
'sc.class_section_id',
'cs.class_section_name',
'CONCAT(s.firstname, " ", s.lastname) AS student_name',
's.school_id',
's.gender',
'MAX(sf.semester_score) AS fall_score',
'MAX(sp.semester_score) AS spring_score',
])
->join('classSection cs', 'cs.class_section_id = sc.class_section_id', 'left')
->join('students s', 's.id = sc.student_id', 'left')
->join('semester_scores sf',
'sf.student_id = sc.student_id AND sf.class_section_id = sc.class_section_id'
. ' AND sf.school_year = ' . $ey . ' AND LOWER(sf.semester) = "fall"', 'left')
->join('semester_scores sp',
'sp.student_id = sc.student_id AND sp.class_section_id = sc.class_section_id'
. ' AND sp.school_year = ' . $ey . ' AND LOWER(sp.semester) = "spring"', 'left')
->where('sc.school_year', $selectedYear)
->orderBy('cs.class_section_name', 'ASC')
->orderBy('student_name', 'ASC')
->groupBy('sc.student_id, sc.class_section_id, cs.class_section_name, s.firstname, s.lastname, s.school_id, s.gender')
->get()->getResultArray();
$sections = [];
foreach ($rows as $row) {
$sid = (int) ($row['class_section_id'] ?? 0);
$name = $row['class_section_name'] ?? 'Section ' . $sid;
if (!isset($sections[$sid])) $sections[$sid] = ['name' => $name, 'students' => []];
$fall = is_numeric($row['fall_score']) ? (float) $row['fall_score'] : null;
$spring = is_numeric($row['spring_score']) ? (float) $row['spring_score'] : null;
$year = ($fall !== null && $spring !== null)
? round(($fall + $spring) / 2, 1)
: ($fall ?? $spring);
$sections[$sid]['students'][] = [
'name' => $row['student_name'],
'school_id' => $row['school_id'],
'gender' => $row['gender'] ?? '',
'fall_score' => $fall,
'spring_score' => $spring,
'year_score' => $year,
];
}
$classResults = [];
foreach ($sections as $section) {
usort($section['students'], static function ($a, $b) {
if ($a['fall_score'] === null && $b['fall_score'] === null) return strcmp($a['name'], $b['name']);
if ($a['fall_score'] === null) return 1;
if ($b['fall_score'] === null) return -1;
return $b['fall_score'] <=> $a['fall_score'] ?: strcmp($a['name'], $b['name']);
});
$scores = array_column($section['students'], 'fall_score');
$calc = $this->calculateThreshold($scores, $percentile);
$threshold = $calc['threshold'];
$allStudents = $section['students'];
$winners = array_values(array_filter($allStudents, function ($s) use ($threshold) {
return $threshold !== null && $s['fall_score'] !== null && $s['fall_score'] >= $threshold;
}));
if (empty($winners)) continue;
$boys = array_filter($allStudents, static fn($s) => strtolower($s['gender']) === 'male');
$girls = array_filter($allStudents, static fn($s) => strtolower($s['gender']) === 'female');
$trophyBoys = array_filter($winners, static fn($s) => strtolower($s['gender']) === 'male');
$trophyGirls = array_filter($winners, static fn($s) => strtolower($s['gender']) === 'female');
$n = count($allStudents);
$nBoys = count($boys);
$nGirls = count($girls);
$nTB = count($trophyBoys);
$nTG = count($trophyGirls);
$classResults[] = [
'section_name' => $section['name'],
'threshold' => $threshold,
'winners' => $winners,
'student_count' => $n,
'boys' => $nBoys,
'girls' => $nGirls,
'trophy_boys' => $nTB,
'trophy_girls' => $nTG,
'pct_boys' => $n > 0 ? round($nBoys / $n * 100) : 0,
'pct_girls' => $n > 0 ? round($nGirls / $n * 100) : 0,
'pct_trophy_boys' => $nBoys > 0 ? round($nTB / $nBoys * 100) : 0,
'pct_trophy_girls' => $nGirls > 0 ? round($nTG / $nGirls * 100) : 0,
'pct_trophy_total' => $n > 0 ? round(count($winners) / $n * 100) : 0,
];
}
return view('administrator/trophy_winners', [
'classResults' => $classResults,
'selectedYear' => $selectedYear,
'selectedPercentile' => $percentile,
'years' => $years,
]);
}
public function final()
{
$db = \Config\Database::connect();
$currentYear = $this->configModel->getConfig('school_year') ?? '';
$selectedYear = $this->request->getGet('school_year') ?? $currentYear;
$percentile = (float) ($this->request->getGet('percentile') ?? 75);
$percentile = max(1.0, min(99.0, $percentile));
$years = $db->table('student_class')
->select('school_year')->distinct()
->orderBy('school_year', 'DESC')
->get()->getResultArray();
$years = array_column($years, 'school_year');
$ey = $db->escape($selectedYear);
$rows = $db->table('student_class sc')
->select([
'sc.student_id',
'sc.class_section_id',
'cs.class_section_name',
'CONCAT(s.firstname, " ", s.lastname) AS student_name',
's.school_id',
's.gender',
'MAX(sf.semester_score) AS fall_score',
'MAX(sp.semester_score) AS spring_score',
])
->join('classSection cs', 'cs.class_section_id = sc.class_section_id', 'left')
->join('students s', 's.id = sc.student_id', 'left')
->join('semester_scores sf',
'sf.student_id = sc.student_id AND sf.class_section_id = sc.class_section_id'
. ' AND sf.school_year = ' . $ey . ' AND LOWER(sf.semester) = "fall"', 'left')
->join('semester_scores sp',
'sp.student_id = sc.student_id AND sp.class_section_id = sc.class_section_id'
. ' AND sp.school_year = ' . $ey . ' AND LOWER(sp.semester) = "spring"', 'left')
->where('sc.school_year', $selectedYear)
->orderBy('cs.class_section_name', 'ASC')
->orderBy('student_name', 'ASC')
->groupBy('sc.student_id, sc.class_section_id, cs.class_section_name, s.firstname, s.lastname, s.school_id, s.gender')
->get()->getResultArray();
$sections = [];
foreach ($rows as $row) {
$sid = (int) ($row['class_section_id'] ?? 0);
$name = $row['class_section_name'] ?? 'Section ' . $sid;
if (!isset($sections[$sid])) $sections[$sid] = ['name' => $name, 'students' => []];
$fall = is_numeric($row['fall_score']) ? (float) $row['fall_score'] : null;
$spring = is_numeric($row['spring_score']) ? (float) $row['spring_score'] : null;
$year = ($fall !== null && $spring !== null)
? round(($fall + $spring) / 2, 1)
: ($fall ?? $spring);
$sections[$sid]['students'][] = [
'name' => $row['student_name'],
'school_id' => $row['school_id'],
'gender' => $row['gender'] ?? '',
'fall_score' => $fall,
'spring_score' => $spring,
'year_score' => $year,
];
}
$classResults = [];
foreach ($sections as $section) {
$students = $section['students'];
$fallCalc = $this->calculateThreshold(array_column($students, 'fall_score'), $percentile);
$yearCalc = $this->calculateThreshold(array_column($students, 'year_score'), $percentile);
$fallThreshold = $fallCalc['threshold'];
$yearThreshold = $yearCalc['threshold'];
$annotated = array_map(static function (array $s) use ($fallThreshold, $yearThreshold): array {
$predicted = $fallThreshold !== null && $s['fall_score'] !== null && $s['fall_score'] >= $fallThreshold;
$actual = $yearThreshold !== null && $s['year_score'] !== null && $s['year_score'] >= $yearThreshold;
$status = match (true) {
$predicted && $actual => 'confirmed',
!$predicted && $actual => 'surprise',
$predicted && !$actual => 'missed',
default => 'none',
};
return $s + compact('predicted', 'actual', 'status');
}, $students);
usort($annotated, static function (array $a, array $b): int {
if ($a['year_score'] === null && $b['year_score'] === null) return strcmp($a['name'], $b['name']);
if ($a['year_score'] === null) return 1;
if ($b['year_score'] === null) return -1;
return $b['year_score'] <=> $a['year_score'] ?: strcmp($a['name'], $b['name']);
});
$nConfirmed = count(array_filter($annotated, static fn ($s) => $s['status'] === 'confirmed'));
$nSurprise = count(array_filter($annotated, static fn ($s) => $s['status'] === 'surprise'));
$nMissed = count(array_filter($annotated, static fn ($s) => $s['status'] === 'missed'));
$nPredicted = count(array_filter($annotated, static fn ($s) => $s['predicted']));
$nActual = count(array_filter($annotated, static fn ($s) => $s['actual']));
$n = count($annotated);
$classResults[] = [
'section_name' => $section['name'],
'students' => $annotated,
'student_count' => $n,
'fall_threshold' => $fallThreshold,
'year_threshold' => $yearThreshold,
'predicted_count' => $nPredicted,
'actual_count' => $nActual,
'confirmed' => $nConfirmed,
'surprises' => $nSurprise,
'missed' => $nMissed,
'accuracy' => $nPredicted > 0 ? round($nConfirmed / $nPredicted * 100) : ($nActual === 0 ? 100 : 0),
];
}
return view('administrator/trophy_final', [
'classResults' => $classResults,
'selectedYear' => $selectedYear,
'selectedPercentile' => $percentile,
'years' => $years,
]);
}
private function calculateThreshold(array $scores, float $percentile = 75.0): array
{
$scores = array_values(array_filter(
$scores,
static fn ($v) => is_numeric($v) && $v !== null
));
$scores = array_map('floatval', $scores);
sort($scores); // ascending
$n = count($scores);
if ($n === 0) {
return ['threshold' => null, 'winners' => 0, 'method' => 'empty'];
}
$minWinners = 3; // never fewer than 3, regardless of class size or score count
// Hard maximum: top (100 - percentile)% of class, but never below the minimum.
$maxWinners = max($minWinners, (int) floor($n * (1 - $percentile / 100)));
$threshold = $this->empiricalPercentile($scores, $percentile);
$winners = $this->countAtOrAbove($scores, $threshold);
if ($winners < $minWinners) {
// Too few qualify — REDUCE the threshold down to the score of the
// 3rd-ranked student so the minimum of 3 is always met.
// If fewer than 3 students have scores, award all of them.
$target = min($minWinners, $n);
$desc = array_reverse($scores); // descending
$threshold = $desc[$target - 1]; // score at rank $target
$winners = $this->countAtOrAbove($scores, $threshold); // ties included
return ['threshold' => $threshold, 'winners' => $winners, 'method' => 'min3_reduced'];
}
if ($winners <= $maxWinners) {
return ['threshold' => $threshold, 'winners' => $winners, 'method' => 'empirical_percentile'];
}
// Too many winners — raise threshold to respect the cap.
$result = $this->capByRank($scores, $maxWinners);
// capByRank may overshoot and drop below the minimum (e.g. bimodal scores
// where only 2 students are in the top cluster). Enforce min=3 here too.
if ($result['winners'] < $minWinners) {
$target = min($minWinners, $n);
$desc = array_reverse($scores);
$threshold = $desc[$target - 1];
$winners = $this->countAtOrAbove($scores, $threshold);
return ['threshold' => $threshold, 'winners' => $winners, 'method' => 'min3_after_cap'];
}
return $result;
}
/**
* Raise the threshold until at most $max students qualify.
* Returns the result without checking the minimum — caller must do that.
*/
private function capByRank(array $sortedScores, int $max): array
{
$desc = array_reverse($sortedScores);
$threshold = $desc[$max - 1];
$winners = $this->countAtOrAbove($sortedScores, $threshold);
if ($winners <= $max) {
return ['threshold' => $threshold, 'winners' => $winners, 'method' => 'capped_25pct'];
}
// Ties push it over — walk up through distinct scores.
$unique = array_values(array_unique(array_filter(
$sortedScores,
static fn ($s) => $s > $threshold
)));
sort($unique);
foreach ($unique as $candidate) {
$w = $this->countAtOrAbove($sortedScores, $candidate);
if ($w <= $max) {
return ['threshold' => $candidate, 'winners' => $w, 'method' => 'capped_25pct'];
}
}
// All scores are equal.
return ['threshold' => $sortedScores[0], 'winners' => count($sortedScores), 'method' => 'all_equal'];
}
private function empiricalPercentile(array $sortedScores, float $p): float
{
$n = count($sortedScores);
if ($n === 0) return 0.0;
$index = ($p / 100.0) * ($n - 1);
$lower = (int) floor($index);
$upper = (int) ceil($index);
if ($lower === $upper) return $sortedScores[$lower];
return $sortedScores[$lower] + ($index - $lower) * ($sortedScores[$upper] - $sortedScores[$lower]);
}
private function countAtOrAbove(array $scores, float $threshold): int
{
return count(array_filter($scores, static fn ($s) => $s >= $threshold));
}
}
@@ -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') ?? '',
];
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddEventPaidFlagToCharges extends Migration
{
public function up()
{
$fields = [
'event_paid' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 0,
'after' => 'charged',
],
];
$this->forge->addColumn('event_charges', $fields);
}
public function down()
{
$this->forge->dropColumn('event_charges', 'event_paid');
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddClassSectionToEventCharges extends Migration
{
public function up()
{
$fields = [
'class_section_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
'after' => 'event_paid',
],
];
if (! $this->db->fieldExists('class_section_id', 'event_charges')) {
$this->forge->addColumn('event_charges', $fields);
}
}
public function down()
{
if ($this->db->fieldExists('class_section_id', 'event_charges')) {
$this->forge->dropColumn('event_charges', 'class_section_id');
}
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddEventPaymentRefToEventCharges extends Migration
{
public function up()
{
$fields = [
'event_payment_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
'after' => 'class_section_id',
],
];
if (! $this->db->fieldExists('event_payment_id', 'event_charges')) {
$this->forge->addColumn('event_charges', $fields);
}
}
public function down()
{
if ($this->db->fieldExists('event_payment_id', 'event_charges')) {
$this->forge->dropColumn('event_charges', 'event_payment_id');
}
}
}
@@ -0,0 +1,43 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddExternalParticipantFieldsToEventCharges extends Migration
{
public function up()
{
$fields = [
'external_firstname' => [
'type' => 'VARCHAR',
'constraint' => 150,
'null' => true,
'after' => 'event_payment_id',
],
'external_lastname' => [
'type' => 'VARCHAR',
'constraint' => 150,
'null' => true,
],
'external_note' => [
'type' => 'VARCHAR',
'constraint' => 254,
'null' => true,
],
];
if (! $this->db->fieldExists('external_firstname', 'event_charges')) {
$this->forge->addColumn('event_charges', $fields);
}
}
public function down()
{
foreach (['external_firstname', 'external_lastname', 'external_note'] as $field) {
if ($this->db->fieldExists($field, 'event_charges')) {
$this->forge->dropColumn('event_charges', $field);
}
}
}
}
@@ -0,0 +1,43 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddExternalParentInfoToEventCharges extends Migration
{
public function up()
{
$fields = [
'external_parent_firstname' => [
'type' => 'VARCHAR',
'constraint' => 150,
'null' => true,
'after' => 'external_note',
],
'external_parent_lastname' => [
'type' => 'VARCHAR',
'constraint' => 150,
'null' => true,
],
'external_parent_phone' => [
'type' => 'VARCHAR',
'constraint' => 50,
'null' => true,
],
];
if (! $this->db->fieldExists('external_parent_firstname', 'event_charges')) {
$this->forge->addColumn('event_charges', $fields);
}
}
public function down()
{
foreach (['external_parent_firstname', 'external_parent_lastname', 'external_parent_phone'] as $field) {
if ($this->db->fieldExists($field, 'event_charges')) {
$this->forge->dropColumn('event_charges', $field);
}
}
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddExternalParentEmailToEventCharges extends Migration
{
public function up()
{
$fields = [
'external_parent_email' => [
'type' => 'VARCHAR',
'constraint' => 254,
'null' => true,
'after' => 'external_parent_phone',
],
];
if (! $this->db->fieldExists('external_parent_email', 'event_charges')) {
$this->forge->addColumn('event_charges', $fields);
}
}
public function down()
{
if ($this->db->fieldExists('external_parent_email', 'event_charges')) {
$this->forge->dropColumn('event_charges', 'external_parent_email');
}
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddWaiverSignedToEventCharges extends Migration
{
public function up()
{
$fields = [
'waiver_signed' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 0,
'after' => 'charged',
],
];
if (! $this->db->fieldExists('waiver_signed', 'event_charges')) {
$this->forge->addColumn('event_charges', $fields);
}
}
public function down()
{
if ($this->db->fieldExists('waiver_signed', 'event_charges')) {
$this->forge->dropColumn('event_charges', 'waiver_signed');
}
}
}
@@ -0,0 +1,85 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateCertificateRecords extends Migration
{
public function up()
{
if ($this->db->tableExists('certificate_records')) {
return;
}
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'certificate_number' => [
'type' => 'VARCHAR',
'constraint' => 30,
],
'student_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'student_name' => [
'type' => 'VARCHAR',
'constraint' => 200,
],
'grade' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'cert_date' => [
'type' => 'DATE',
'null' => true,
],
'school_year' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => true,
],
'class_section_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
'issued_by' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
'issued_at' => [
'type' => 'DATETIME',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey('certificate_number');
$this->forge->addKey(['school_year', 'student_id']);
$this->forge->createTable('certificate_records');
}
public function down()
{
$this->forge->dropTable('certificate_records', true);
}
}
@@ -0,0 +1,70 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateBelowSixtyDecisions extends Migration
{
public function up()
{
if ($this->db->tableExists('below_sixty_decisions')) {
return;
}
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'student_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'semester' => [
'type' => 'VARCHAR',
'constraint' => 20,
],
'school_year' => [
'type' => 'VARCHAR',
'constraint' => 20,
],
'decision' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'notes' => [
'type' => 'TEXT',
'null' => true,
],
'decided_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->addUniqueKey(['student_id', 'semester', 'school_year']);
$this->forge->addKey(['school_year', 'semester']);
$this->forge->createTable('below_sixty_decisions');
}
public function down()
{
$this->forge->dropTable('below_sixty_decisions', true);
}
}
@@ -0,0 +1,85 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateStudentDecisions extends Migration
{
public function up()
{
if ($this->db->tableExists('student_decisions')) {
return;
}
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'student_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'semester' => [
'type' => 'VARCHAR',
'constraint' => 20,
],
'school_year' => [
'type' => 'VARCHAR',
'constraint' => 20,
],
'class_section_name' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'semester_score' => [
'type' => 'DECIMAL',
'constraint' => '8,2',
'null' => true,
],
'decision' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'source' => [
'type' => 'ENUM',
'constraint' => ['auto', 'manual', 'pending'],
'default' => 'auto',
],
'notes' => [
'type' => 'TEXT',
'null' => true,
],
'generated_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->addUniqueKey(['student_id', 'semester', 'school_year']);
$this->forge->addKey(['school_year', 'semester']);
$this->forge->createTable('student_decisions');
}
public function down()
{
$this->forge->dropTable('student_decisions', true);
}
}
@@ -0,0 +1,73 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddVerificationTokenToCertificateRecords extends Migration
{
private const INDEX_NAME = 'uniq_certificate_verification_token';
public function up()
{
if (!$this->db->tableExists('certificate_records')) {
return;
}
if (!$this->db->fieldExists('verification_token', 'certificate_records')) {
$this->forge->addColumn('certificate_records', [
'verification_token' => [
'type' => 'VARCHAR',
'constraint' => 64,
'null' => true,
'after' => 'certificate_number',
],
]);
}
$rows = $this->db->table('certificate_records')
->select('id, verification_token')
->get()
->getResultArray();
foreach ($rows as $row) {
if (trim((string)($row['verification_token'] ?? '')) !== '') {
continue;
}
$this->db->table('certificate_records')
->where('id', (int)$row['id'])
->update(['verification_token' => $this->generateToken()]);
}
$this->forge->addUniqueKey('verification_token', self::INDEX_NAME);
$this->forge->processIndexes('certificate_records');
}
public function down()
{
if (!$this->db->tableExists('certificate_records')) {
return;
}
if ($this->db->fieldExists('verification_token', 'certificate_records')) {
$this->forge->dropKey('certificate_records', self::INDEX_NAME);
$this->forge->dropColumn('certificate_records', 'verification_token');
}
}
private function generateToken(): string
{
do {
$token = bin2hex(random_bytes(16));
$exists = $this->db->table('certificate_records')
->select('id')
->where('verification_token', $token)
->limit(1)
->get()
->getRowArray();
} while ($exists);
return $token;
}
}
@@ -0,0 +1,294 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class FinancialSystemLedgerCleanup extends Migration
{
public function up()
{
$this->addInstallmentSequenceColumn();
$this->ensureIndexes();
$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_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 ensureIndexes(): void
{
$this->addIndexIfMissing('payments', 'idx_payments_invoice_id', ['invoice_id']);
$this->addIndexIfMissing('payments', 'idx_payments_parent_year_semester', ['parent_id', 'school_year', 'semester']);
$this->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 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]);
}
}
+3 -3
View File
@@ -86,9 +86,9 @@ class NavSeeder extends Seeder
['parent'=>'Financial','label'=>'Discount Management','url'=>'discounts/list','sort_order'=>1], ['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'=>'Expenses Management','url'=>'expenses/index','sort_order'=>2],
['parent'=>'Financial','label'=>'Financial Report','url'=>'payment/financial_report','sort_order'=>3], ['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'=>'Tuition Forecast','url'=>'administrator/tuition-forecast','sort_order'=>4],
['parent'=>'Financial','label'=>'Manual Payment','url'=>'payment/manual_pay','sort_order'=>5], ['parent'=>'Financial','label'=>'Invoices Management','url'=>'invoice_payment/invoice_management','sort_order'=>5],
['parent'=>'Financial','label'=>'PaypalTransactions','url'=>'administrator/paypal_transactions','sort_order'=>6], ['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'=>'Refund Management','url'=>'refunds/list','sort_order'=>7],
['parent'=>'Financial','label'=>'Reimbursement Management','url'=>'reimbursements/index','sort_order'=>8], ['parent'=>'Financial','label'=>'Reimbursement Management','url'=>'reimbursements/index','sort_order'=>8],
+8 -1
View File
@@ -11,6 +11,8 @@ class ApiAuthFilter implements FilterInterface
{ {
public function before(RequestInterface $request, $arguments = null) public function before(RequestInterface $request, $arguments = null)
{ {
helper('security');
$authorization = $request->getHeaderLine('Authorization'); $authorization = $request->getHeaderLine('Authorization');
if (!$authorization || stripos($authorization, 'Bearer ') !== 0) { if (!$authorization || stripos($authorization, 'Bearer ') !== 0) {
return $this->unauthorized('Missing or invalid Authorization header'); return $this->unauthorized('Missing or invalid Authorization header');
@@ -21,7 +23,12 @@ class ApiAuthFilter implements FilterInterface
return $this->unauthorized('Bearer token is required'); return $this->unauthorized('Bearer token is required');
} }
$secret = env('JWT_SECRET', 'change-me-in-env'); try {
$secret = require_env('JWT_SECRET');
} catch (\RuntimeException $e) {
return $this->unauthorized('JWT configuration is missing');
}
$payload = jwt_decode($token, $secret); $payload = jwt_decode($token, $secret);
if (!$payload || empty($payload['sub'])) { if (!$payload || empty($payload['sub'])) {
+3 -1
View File
@@ -13,13 +13,15 @@ class ApiDocsAuthFilter implements FilterInterface
{ {
public function before(RequestInterface $request, $arguments = null) public function before(RequestInterface $request, $arguments = null)
{ {
helper('security');
$authHeader = $request->getHeaderLine('Authorization'); $authHeader = $request->getHeaderLine('Authorization');
if ($authHeader && str_starts_with($authHeader, 'Bearer ')) { if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
$token = trim(substr($authHeader, 7)); $token = trim(substr($authHeader, 7));
try { try {
$key = getenv('JWT_SECRET') ?: 'your_default_secret'; $key = require_env('JWT_SECRET');
$decoded = JWT::decode($token, new Key($key, 'HS256')); $decoded = JWT::decode($token, new Key($key, 'HS256'));
if (!isset($decoded->roles) || empty($decoded->roles->admin)) { if (!isset($decoded->roles) || empty($decoded->roles->admin)) {
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
class ApiRateLimitFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
$throttler = service('throttler');
$response = Services::response();
$maxRequests = isset($arguments[0]) ? max(1, (int) $arguments[0]) : 60;
$windowSeconds = isset($arguments[1]) ? max(1, (int) $arguments[1]) : MINUTE;
$userId = session()->get('user_id');
$identifier = $userId ? 'user:' . $userId : 'ip:' . $request->getIPAddress();
$route = trim($request->getUri()->getPath(), '/');
$key = 'api-rate-' . sha1($request->getMethod() . '|' . $route . '|' . $identifier);
if (! $throttler->check($key, $maxRequests, $windowSeconds)) {
return $response
->setStatusCode(429)
->setHeader('Retry-After', (string) $windowSeconds)
->setJSON([
'status' => false,
'message' => 'Too many requests. Please try again later.',
]);
}
return null;
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
return $response;
}
}
+94 -28
View File
@@ -35,13 +35,19 @@ class AuthFilter implements FilterInterface
public function before(RequestInterface $request, $arguments = null) public function before(RequestInterface $request, $arguments = null)
{ {
$session = session(); $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'); $userId = $session->get('user_id');
$loginTime = (int) $session->get('login_time'); $loginTime = (int) $session->get('login_time');
// Must be logged in // Must be logged in
if (empty($userRoles) || empty($userId)) { if (empty($userRoles) || empty($userId)) {
return redirect()->to('/login'); $target = ltrim($request->getUri()->getPath(), '/');
$query = $request->getUri()->getQuery();
if ($query !== '') {
$target .= '?' . $query;
}
return redirect()->to('/login?redirect_to=' . rawurlencode('/' . ltrim($target, '/')));
} }
// Enforce 12-hour session lifetime // Enforce 12-hour session lifetime
@@ -60,35 +66,16 @@ class AuthFilter implements FilterInterface
return $this->deny($request, "You don't have permission to use this feature."); return $this->deny($request, "You don't have permission to use this feature.");
} }
// Route arguments: ['filter' => 'auth:permission_name|alt_permission,update'] [$requirements, $crudAction] = $this->parseRequirements($arguments);
// 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';
if (!empty($arguments)) { if (!empty($requirements)) {
$arg0 = strtolower((string) $arguments[0]); if ($this->matchesAnyRequirement($requirements, $crudAction, $roleIds, (array) $userRoles)) {
return;
// 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';
}
} }
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)) { if ($this->isAllowedByMenu($request, $roleIds)) {
return; // ✅ allowed return; // ✅ allowed
} }
@@ -110,7 +97,86 @@ class AuthFilter implements FilterInterface
]); ]);
} }
return redirect()->to('/login')->with('error', 'Your session has expired. Please log in again.'); $target = ltrim($request->getUri()->getPath(), '/');
$query = $request->getUri()->getQuery();
if ($query !== '') {
$target .= '?' . $query;
}
return redirect()->to('/login?redirect_to=' . rawurlencode('/' . ltrim($target, '/')))
->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) public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
class SanitizeInputFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
helper('security');
$sanitizedGet = sanitize_request_value($request->getGet() ?? []);
$sanitizedPost = sanitize_request_value($request->getPost() ?? []);
$request->setGlobal('get', $sanitizedGet);
$request->setGlobal('post', $sanitizedPost);
$request->setGlobal('request', array_merge(is_array($sanitizedGet) ? $sanitizedGet : [], is_array($sanitizedPost) ? $sanitizedPost : []));
$request->setGlobal('cookie', sanitize_request_value($request->getCookie() ?? []));
$contentType = strtolower($request->getHeaderLine('Content-Type'));
$body = $request->getBody();
if (str_contains($contentType, 'application/json') && trim($body) !== '') {
$decoded = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE || ! is_array($decoded)) {
return Services::response()
->setStatusCode(400)
->setJSON([
'status' => false,
'message' => 'Malformed JSON payload.',
]);
}
$request->setBody((string) json_encode(sanitize_request_value($decoded), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
return null;
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
return $response;
}
}
+35 -1
View File
@@ -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) { foreach ($templates as $template) {
$min = isset($template['min_score']) ? (float) $template['min_score'] : 0.0; $min = isset($template['min_score']) ? (float) $template['min_score'] : 0.0;
$max = isset($template['max_score']) ? (float) $template['max_score'] : 100.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;
} }
} }
+3
View File
@@ -0,0 +1,3 @@
<?php
require_once __DIR__ . '/AuthHelper.php';
+41
View File
@@ -0,0 +1,41 @@
<?php
if (! function_exists('sanitize_request_value')) {
/**
* Recursively normalize request values without applying output encoding.
*/
function sanitize_request_value($value)
{
if (is_array($value)) {
foreach ($value as $key => $item) {
$value[$key] = sanitize_request_value($item);
}
return $value;
}
if (! is_string($value)) {
return $value;
}
$value = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $value) ?? $value;
return trim($value);
}
}
if (! function_exists('require_env')) {
/**
* Fetch an environment variable and fail closed when it is missing.
*/
function require_env(string $key): string
{
$value = env($key);
if ($value === null || $value === '') {
throw new RuntimeException(sprintf('Missing required environment variable: %s', $key));
}
return (string) $value;
}
}
@@ -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';
}
}
+98
View File
@@ -0,0 +1,98 @@
<?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 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 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,
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;
}
}
+343
View File
@@ -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, '.', '');
}
}
+2 -1
View File
@@ -16,8 +16,9 @@ class StaffTimeOffLinkService
public function __construct(?string $secret = null, ?int $ttlSeconds = null) public function __construct(?string $secret = null, ?int $ttlSeconds = null)
{ {
helper('jwt'); helper('jwt');
helper('security');
$this->secret = $secret ?: (string)env('JWT_SECRET', 'change-me-in-env'); $this->secret = $secret ?: require_env('JWT_SECRET');
$this->ttl = ($ttlSeconds !== null && $ttlSeconds > 0) ? $ttlSeconds : self::DEFAULT_TTL; $this->ttl = ($ttlSeconds !== null && $ttlSeconds > 0) ? $ttlSeconds : self::DEFAULT_TTL;
} }
@@ -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, '.', '');
}
}
+135
View File
@@ -0,0 +1,135 @@
<?php
namespace App\Listeners;
use Config\Services;
class DecisionEmailListener
{
public static function handle(array $payload): void
{
$studentId = (int)($payload['student_id'] ?? 0);
$studentName = (string)($payload['student_name'] ?? '');
$classSection= (string)($payload['class_section_name'] ?? '');
$semester = (string)($payload['semester'] ?? '');
$schoolYear = (string)($payload['school_year'] ?? '');
$decision = (string)($payload['decision'] ?? '');
$notes = (string)($payload['notes'] ?? '');
$scores = is_array($payload['scores'] ?? null) ? $payload['scores'] : [];
$allSemesters = is_array($payload['all_semesters'] ?? null) ? $payload['all_semesters'] : [];
if ($studentId <= 0) {
log_message('warning', 'DecisionEmail: missing student_id');
return;
}
$db = \Config\Database::connect();
$rows = $db->query(
"SELECT u.firstname, u.lastname, u.email, fg.is_primary
FROM family_students fs
JOIN family_guardians fg ON fg.family_id = fs.family_id
JOIN users u ON u.id = fg.user_id
WHERE fs.student_id = ?
AND fg.receive_emails = 1
AND u.email IS NOT NULL AND u.email != ''
ORDER BY fg.is_primary DESC, u.lastname, u.firstname",
[$studentId]
)->getResultArray();
if (empty($rows)) {
log_message('warning', 'DecisionEmail: no guardian emails for student_id=' . $studentId);
return;
}
$emails = [];
foreach ($rows as $row) {
$em = trim((string)($row['email'] ?? ''));
if ($em !== '') $emails[$em] = true;
}
$emails = array_keys($emails);
$primary = $rows[0] ?? [];
$parentName = trim((string)($primary['firstname'] ?? '') . ' ' . (string)($primary['lastname'] ?? ''));
$subject = (string)($payload['subject'] ?? '');
if ($subject === '') {
$subject = 'Academic Decision';
if ($studentName !== '') $subject .= ' — ' . $studentName;
if ($semester !== '' || $schoolYear !== '') {
$subject .= ' (' . trim($semester . ' ' . $schoolYear) . ')';
}
}
$emailData = [
'title' => $subject,
'parent_name' => $parentName !== '' ? $parentName : 'Parent/Guardian',
'student_name' => $studentName !== '' ? $studentName : 'your student',
'class_section_name' => $classSection,
'school_year' => $schoolYear,
'decision' => $decision,
'notes' => $notes,
'scores' => $scores,
'all_semesters' => $allSemesters,
];
$html = trim((string)($payload['html'] ?? ''));
if ($html === '') {
$html = view('emails/below_sixty_decision', $emailData, ['saveData' => true]);
}
$okAny = false;
foreach ($emails as $to) {
$ok = self::sendViaEmailService($to, $subject, $html);
if (!$ok) {
$ok = self::sendViaCiEmail($to, $subject, $html);
}
$okAny = $okAny || $ok;
}
if ($okAny) {
log_message('info', 'DecisionEmail: sent for student_id=' . $studentId);
} else {
log_message('error', 'DecisionEmail: failed for student_id=' . $studentId);
}
}
protected static function sendViaEmailService(string $to, string $subject, string $html): bool
{
try {
$svc = function_exists('service') ? service('emailService') : null;
if (!$svc && method_exists(Services::class, 'emailService')) {
$svc = Services::emailService();
}
if (!$svc) return false;
return (bool)$svc->send($to, $subject, $html, 'general');
} catch (\Throwable $e) {
log_message('debug', 'DecisionEmail sendViaEmailService failed: ' . $e->getMessage());
return false;
}
}
protected static function sendViaCiEmail(string $to, string $subject, string $html): bool
{
try {
$email = Services::email();
$cfg = config('Email');
$fromEmail = $cfg->fromEmail ?? $cfg->SMTPUser ?? 'no-reply@example.com';
$fromName = $cfg->fromName ?? 'Al Rahma Sunday School';
$email->setTo($to);
$email->setFrom($fromEmail, $fromName);
$email->setSubject($subject);
$email->setMessage($html);
$email->setMailType('html');
$ok = $email->send();
if (!$ok) {
$dbg = method_exists($email, 'printDebugger') ? $email->printDebugger(['headers', 'subject']) : 'no debugger';
log_message('debug', 'DecisionEmail CI send failed: ' . print_r($dbg, true));
}
return $ok;
} catch (\Throwable $e) {
log_message('debug', 'DecisionEmail sendViaCiEmail exception: ' . $e->getMessage());
return false;
}
}
}
+1 -1
View File
@@ -35,7 +35,7 @@ class AdditionalChargeModel extends Model
'description' => 'permit_empty|string', 'description' => 'permit_empty|string',
'amount' => 'required|decimal', 'amount' => 'required|decimal',
'due_date' => 'permit_empty|valid_date', 'due_date' => 'permit_empty|valid_date',
'status' => 'required|in_list[pending,applied]', 'status' => 'required|in_list[pending,applied,voided]',
'created_by' => 'permit_empty|integer', 'created_by' => 'permit_empty|integer',
]; ];
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class BelowSixtyDecisionModel extends Model
{
protected $table = 'below_sixty_decisions';
protected $primaryKey = 'id';
protected $allowedFields = [
'student_id',
'semester',
'school_year',
'decision',
'notes',
'decided_by',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
}
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class CertificateRecordModel extends Model
{
protected $table = 'certificate_records';
protected $primaryKey = 'id';
protected $useTimestamps = true;
protected $allowedFields = [
'certificate_number',
'verification_token',
'student_id',
'student_name',
'grade',
'cert_date',
'school_year',
'class_section_id',
'issued_by',
'issued_at',
];
/**
* Generates the next certificate number for a given school year.
* Format: ARSS-{school_year}-{4-digit sequence} e.g. ARSS-2025-2026-0003
* Uses a transaction + row count to guarantee uniqueness within a request.
* Academic Records and Student Services (ARSS)
*/
public function nextNumber(string $schoolYear): string
{
$db = \Config\Database::connect();
$db->transStart();
$count = $db->table($this->table)
->where('school_year', $schoolYear)
->countAllResults();
$seq = str_pad($count + 1, 4, '0', STR_PAD_LEFT);
$db->transComplete();
return 'ARSS-' . $schoolYear . '-' . $seq;
}
public function generateVerificationToken(): string
{
$db = \Config\Database::connect();
do {
$token = bin2hex(random_bytes(16));
$exists = $db->table($this->table)
->select('id')
->where('verification_token', $token)
->limit(1)
->get()
->getRowArray();
} while ($exists);
return $token;
}
/** Returns paginated records with the issuing admin's name joined. */
public function getAuditLog(?string $schoolYear = null, int $perPage = 50): array
{
$builder = $this->db->table($this->table . ' cr')
->select('cr.*, u.firstname AS admin_firstname, u.lastname AS admin_lastname')
->join('users u', 'u.id = cr.issued_by', 'left')
->orderBy('cr.issued_at', 'DESC');
if ($schoolYear) {
$builder->where('cr.school_year', $schoolYear);
}
return $builder->get()->getResultArray();
}
/** Total certificates issued per school year, ordered by year DESC. */
public function yearSummary(): array
{
return $this->db->table($this->table)
->select('school_year, COUNT(*) AS total')
->groupBy('school_year')
->orderBy('school_year', 'DESC')
->get()->getResultArray();
}
}
+12
View File
@@ -15,8 +15,20 @@ class EventChargesModel extends Model
'student_id', 'student_id',
'participation', 'participation',
'charged', 'charged',
'waiver_signed',
'event_paid',
'event_payment_id',
'class_section_id',
'external_firstname',
'external_lastname',
'external_note',
'external_parent_firstname',
'external_parent_lastname',
'external_parent_phone',
'external_parent_email',
'semester', 'semester',
'school_year', 'school_year',
'created_by',
'updated_by', 'updated_by',
'created_at', 'created_at',
'updated_at' 'updated_at'
-38
View File
@@ -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
}
+2
View File
@@ -17,6 +17,7 @@ class PaymentModel extends Model
'paid_amount', 'paid_amount',
'balance', 'balance',
'number_of_installments', 'number_of_installments',
'installment_seq',
'transaction_id', 'transaction_id',
'check_file', 'check_file',
'check_number', 'check_number',
@@ -114,6 +115,7 @@ class PaymentModel extends Model
->selectSum('paid_amount', 'total_paid') ->selectSum('paid_amount', 'total_paid')
->where('parent_id', $parentId) ->where('parent_id', $parentId)
->where('school_year', $schoolYear) ->where('school_year', $schoolYear)
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
->get() ->get()
->getRowArray(); ->getRowArray();
-30
View File
@@ -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;
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class StudentDecisionModel extends Model
{
protected $table = 'student_decisions';
protected $primaryKey = 'id';
protected $allowedFields = [
'student_id',
'school_year',
'class_section_name',
'year_score',
'decision',
'source',
'notes',
'generated_by',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
}
+40
View File
@@ -8,6 +8,7 @@ class EmailService
{ {
protected array $senders; protected array $senders;
protected EmailController $mailer; protected EmailController $mailer;
protected int $lastCcBatchCount = 0;
public function __construct() public function __construct()
{ {
@@ -73,6 +74,45 @@ class EmailService
return $allOk; return $allOk;
} }
/**
* Send one email with all recipients in CC.
*/
public function sendCc(array $ccList, string $subject, string $message, string $fromKey = 'general', array $attachments = [], array $headers = []): bool
{
$this->lastCcBatchCount = 0;
if (empty($ccList)) {
return true;
}
$sender = $this->getSenderDetails($fromKey);
$to = trim((string) ($sender['email'] ?? ''));
if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
$fallback = trim((string) (getenv('SMTP_USER') ?: ''));
$to = filter_var($fallback, FILTER_VALIDATE_EMAIL) ? $fallback : 'no-reply@alrahmaisgl.org';
}
$attachmentsPayload = $this->normalizeAttachments($attachments);
$chunks = array_chunk(array_values($ccList), 10);
$this->lastCcBatchCount = count($chunks);
$allOk = true;
foreach ($chunks as $index => $chunk) {
$ok = $this->mailer->sendEmailWithCc($to, $chunk, $subject, $message, $fromKey, null, null, $attachmentsPayload);
if (!$ok) {
$allOk = false;
log_message('error', 'EmailService::sendCc failed for batch ' . ($index + 1) . ' of ' . count($chunks));
}
}
return $allOk;
}
public function getLastCcBatchCount(): int
{
return $this->lastCcBatchCount;
}
/** /**
* Normalize various attachment inputs to the format expected by EmailController. * Normalize various attachment inputs to the format expected by EmailController.
*/ */
+2 -2
View File
@@ -61,7 +61,7 @@ class FeeCalculationService
// Retrieve fee configs // Retrieve fee configs
$firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350); $firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350);
$secondStudentFee = (float) ($configModel->getConfig('second_student_fee') ?? 200); $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) // Assign tuition_fee to all students (before filtering refunds)
$regularCount = 0; $regularCount = 0;
@@ -148,7 +148,7 @@ class FeeCalculationService
$firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350); $firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350);
$secondStudentFee = (float) ($configModel->getConfig('second_student_fee') ?? 200); $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 // ✅ Pre-fetch and assign grade/class section names before sorting
foreach ($students as &$student) { foreach ($students as &$student) {
+17 -2
View File
@@ -72,11 +72,26 @@ class SemesterRangeService
$y1 = (int)$m[1]; $y1 = (int)$m[1];
$y2 = (int)$m[2]; $y2 = (int)$m[2];
$normalized = ucfirst(strtolower(trim($semester))); $normalized = ucfirst(strtolower(trim($semester)));
$fallStartCfg = (string)($this->configModel->getConfig('fall_semester_start') ?? '');
$fallEndCfg = (string)($this->configModel->getConfig('fall_end_date') ?? '');
$springStartCfg = (string)($this->configModel->getConfig('spring_semester_start') ?? '');
$springEndCfg = (string)($this->configModel->getConfig('last_school_day') ?? '');
$md = static fn(string $cfg, int $year, string $fallback): string =>
$cfg !== '' ? sprintf('%04d-%s', $year, date('m-d', strtotime($cfg))) : $fallback;
if ($normalized === 'Fall') { if ($normalized === 'Fall') {
return [sprintf('%04d-09-21', $y1), sprintf('%04d-01-18', $y2)]; return [
$md($fallStartCfg, $y1, sprintf('%04d-09-21', $y1)),
$md($fallEndCfg, $y2, sprintf('%04d-01-18', $y2)),
];
} }
if ($normalized === 'Spring') { if ($normalized === 'Spring') {
return [sprintf('%04d-01-25', $y2), sprintf('%04d-05-31', $y2)]; return [
$md($springStartCfg, $y2, sprintf('%04d-01-25', $y2)),
$md($springEndCfg, $y2, sprintf('%04d-05-31', $y2)),
];
} }
return null; return null;
} }
+6 -6
View File
@@ -212,42 +212,42 @@
<div class="col-4"> <div class="col-4">
<img <img
class="img-fluid rounded bg-light p-1" class="img-fluid rounded bg-light p-1"
src=""assets/images/classes-1.jpg" src="assets/images/classes-1.jpg"
alt="" alt=""
/> />
</div> </div>
<div class="col-4"> <div class="col-4">
<img <img
class="img-fluid rounded bg-light p-1" class="img-fluid rounded bg-light p-1"
src=""assets/images/classes-2.jpg" src="assets/images/classes-2.jpg"
alt="" alt=""
/> />
</div> </div>
<div class="col-4"> <div class="col-4">
<img <img
class="img-fluid rounded bg-light p-1" class="img-fluid rounded bg-light p-1"
src=""assets/images/classes-3.jpg" src="assets/images/classes-3.jpg"
alt="" alt=""
/> />
</div> </div>
<div class="col-4"> <div class="col-4">
<img <img
class="img-fluid rounded bg-light p-1" class="img-fluid rounded bg-light p-1"
src=""assets/images/classes-4.jpg" src="assets/images/classes-4.jpg"
alt="" alt=""
/> />
</div> </div>
<div class="col-4"> <div class="col-4">
<img <img
class="img-fluid rounded bg-light p-1" class="img-fluid rounded bg-light p-1"
src=""assets/images/classes-5.jpg" src="assets/images/classes-5.jpg"
alt="" alt=""
/> />
</div> </div>
<div class="col-4"> <div class="col-4">
<img <img
class="img-fluid rounded bg-light p-1" class="img-fluid rounded bg-light p-1"
src=""assets/images/classes-6.jpg" src="assets/images/classes-6.jpg"
alt="" alt=""
/> />
</div> </div>
+7 -7
View File
@@ -44,7 +44,7 @@
<!-- Navbar Start --> <!-- Navbar Start -->
<nav class="navbar navbar-expand-lg bg-white navbar-light sticky-top px-4 px-lg-5 py-lg-0"> <nav class="navbar navbar-expand-lg bg-white navbar-light sticky-top px-4 px-lg-5 py-lg-0">
<a href="<?= base_url('/') ?>" class="navbar-brand d-flex align-items-center"> <a href="<?= base_url('/') ?>" class="navbar-brand d-flex align-items-center">
<img src="<?= base_url('images/logo.png') ?>" alt="Al Rahma Sunday School" style="height: 40px;"> <img src="<?= base_url('images/logo.png') ?>" alt="Al Rahma Sunday School" style="height: 40px; width: 40px; border-radius: 50%; object-fit: cover;">
<h1 class="m-0 ms-2 green-title">Al Rahma Sunday School</h1> <h1 class="m-0 ms-2 green-title">Al Rahma Sunday School</h1>
</a> </a>
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"> <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
@@ -170,22 +170,22 @@
<h3 class="text-white mb-4">Photo Gallery</h3> <h3 class="text-white mb-4">Photo Gallery</h3>
<div class="row g-2 pt-2"> <div class="row g-2 pt-2">
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-1.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-1.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-2.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-2.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-3.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-3.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-4.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-4.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-5.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-5.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-6.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-6.jpg') ?>" alt="">
</div> </div>
</div> </div>
</div> </div>
@@ -0,0 +1,97 @@
<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<div class="container-fluid py-4">
<div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
<div>
<h2 class="mb-0"><i class="bi bi-journal-check me-2"></i>Certificate Audit Log</h2>
<div class="text-muted small">Every issued certificate is recorded here for tracking and auditing.</div>
</div>
<a href="<?= site_url('administrator/certificates') ?>" class="btn btn-outline-secondary btn-sm">
<i class="bi bi-award me-1"></i>Generate Certificates
</a>
</div>
<!-- Year summary cards -->
<?php if (!empty($yearSummary)): ?>
<div class="row g-3 mb-4">
<?php foreach ($yearSummary as $yr): ?>
<div class="col-auto">
<div class="card shadow-sm text-center px-4 py-2" style="min-width:150px;">
<div class="fw-bold fs-4"><?= (int) $yr['total'] ?></div>
<div class="text-muted small"><?= esc($yr['school_year']) ?></div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<!-- Year filter -->
<div class="card shadow-sm mb-4">
<div class="card-body py-2">
<form method="get" action="<?= site_url('administrator/certificates/log') ?>" class="row g-2 align-items-center">
<div class="col-auto">
<label class="col-form-label fw-semibold">School Year</label>
</div>
<div class="col-auto">
<select name="school_year" class="form-select form-select-sm" onchange="this.form.submit()">
<option value="">— All years —</option>
<?php foreach ($yearSummary as $yr): ?>
<option value="<?= esc($yr['school_year']) ?>"
<?= ($yr['school_year'] === $schoolYear) ? 'selected' : '' ?>>
<?= esc($yr['school_year']) ?> (<?= (int) $yr['total'] ?>)
</option>
<?php endforeach; ?>
</select>
</div>
</form>
</div>
</div>
<!-- Records table -->
<div class="card shadow-sm">
<div class="card-header d-flex justify-content-between align-items-center">
<span class="fw-semibold">Issued Certificates
<span class="badge bg-secondary ms-1"><?= count($records) ?></span>
</span>
</div>
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover table-striped align-middle mb-0 no-mgmt-sticky">
<thead class="table-light">
<tr>
<th>Certificate #</th>
<th>Student</th>
<th>Grade</th>
<!--th>Cert Date</th-->
<th>School Year</th>
<!--th>Issued By</th-->
<th>Issued At</th>
</tr>
</thead>
<tbody>
<?php if (empty($records)): ?>
<tr><td colspan="7" class="text-center text-muted py-4">No certificates issued yet.</td></tr>
<?php else: ?>
<?php foreach ($records as $r): ?>
<tr>
<td><code><?= esc($r['certificate_number']) ?></code></td>
<td><?= esc($r['student_name']) ?></td>
<td><?= esc($r['grade'] ?? '—') ?></td>
<td><?= $r['cert_date'] ? esc(date('m/d/Y', strtotime($r['cert_date']))) : '—' ?></td>
<td><?= esc($r['school_year'] ?? '—') ?></td>
<td><?= esc(trim(($r['admin_firstname'] ?? '') . ' ' . ($r['admin_lastname'] ?? '')) ?: '—') ?></td>
<td><?= esc($r['issued_at'] ? date('m/d/Y g:i A', strtotime($r['issued_at'])) : '—') ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?= $this->endSection() ?>
+643
View File
@@ -0,0 +1,643 @@
<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<div class="container-fluid">
<div class="wrapper">
<?php
// ── Group sections by grade (mirrors daily_attendance logic) ─────────────────
$gradeGroups = []; // sortKey => ['label'=>, 'slug'=>, 'csids'=>[]]
foreach ($statsPerClass as $csid => $cs) {
$name = $cs['name'];
$lower = strtolower(trim($name));
if (preg_match('/grade\s*(\d+)/i', $name, $m)) {
$n = (int)$m[1];
$label = 'Grade ' . $n;
$sortKey = '1_' . str_pad($n, 3, '0', STR_PAD_LEFT);
$slug = 'grade' . $n;
} elseif (strpos($lower, 'kg') !== false || strpos($lower, 'kindergarten') !== false) {
$label = 'KG';
$sortKey = '0_kg';
$slug = 'kg';
} elseif (strpos($lower, 'arabic') !== false) {
$label = 'Arabic';
$sortKey = '2_arabic';
$slug = 'arabic';
} elseif (strpos($lower, 'youth') !== false) {
$label = 'Youth';
$sortKey = '5_youth';
$slug = 'youth';
} else {
$label = $name;
$sortKey = '3_' . $lower;
$slug = preg_replace('/[^a-z0-9]+/', '-', $lower);
}
if (!isset($gradeGroups[$sortKey])) {
$gradeGroups[$sortKey] = ['label' => $label, 'slug' => $slug, 'csids' => []];
}
$gradeGroups[$sortKey]['csids'][] = $csid;
}
ksort($gradeGroups);
$gradeKeys = array_keys($gradeGroups);
$defaultKey = $gradeKeys[0] ?? null;
$decisionBadge = [
'Pass' => 'success',
'Repeat Class' => 'danger',
'Make-up exam in fall' => 'info',
'Deferred decision' => 'info',
'Expel' => 'danger',
'Withdrawn' => 'secondary',
];
?>
<h2 class="text-center mt-4 mb-3">
<i class="bi bi-award me-2"></i>Generate Certificates
</h2>
<!-- School year filter -->
<div class="d-flex justify-content-end mb-3">
<form method="get" action="<?= site_url('administrator/certificates') ?>" class="d-flex gap-2 align-items-center">
<label class="form-label mb-0 me-1 text-muted small">School Year</label>
<input type="text"
name="school_year"
class="form-control form-control-sm"
style="width:130px;"
value="<?= esc($schoolYear) ?>"
placeholder="e.g. 2024-2025">
<button type="submit" class="btn btn-sm btn-outline-primary">
<i class="bi bi-arrow-repeat me-1"></i>Reload
</button>
</form>
</div>
<?php if (session()->getFlashdata('error')): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?= esc(session()->getFlashdata('error')) ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if (empty($gradeGroups)): ?>
<div class="alert alert-info">No classes found for <?= esc($schoolYear) ?>.</div>
<?php else: ?>
<!-- Grade tabs -->
<ul class="nav nav-tabs justify-content-center" id="certTabs" role="tablist" style="flex-wrap:wrap;row-gap:.25rem;">
<?php foreach ($gradeGroups as $key => $group): ?>
<?php
$slug = $group['slug'];
$label = $group['label'];
$total = array_sum(array_map(fn($id) => $statsPerClass[$id]['total'] ?? 0, $group['csids']));
$grpPass = array_sum(array_map(fn($id) => $statsPerClass[$id]['pass'] ?? 0, $group['csids']));
$grpCert = array_sum(array_map(fn($id) => $statsPerClass[$id]['cert'] ?? 0, $group['csids']));
$fullyDone = $grpPass > 0 && $grpCert >= $grpPass;
$hasPass = $grpPass > 0;
$isActive = ($key === $defaultKey);
$statusTitle = $hasPass
? ($fullyDone ? 'Fully generated (' . $grpCert . '/' . $grpPass . ')' : 'Not fully generated (' . $grpCert . '/' . $grpPass . ')')
: 'No eligible students';
?>
<li class="nav-item" role="presentation">
<a class="nav-link <?= $isActive ? 'active' : '' ?>"
id="cert-<?= esc($slug) ?>-tab"
data-bs-toggle="tab"
href="#cert-<?= esc($slug) ?>"
role="tab"
aria-controls="cert-<?= esc($slug) ?>"
aria-selected="<?= $isActive ? 'true' : 'false' ?>">
<span class="cert-status-dot <?= !$hasPass ? 'no-eligible' : ($fullyDone ? 'done' : 'pending') ?>"
title="<?= esc($statusTitle) ?>"></span>
<?= esc($label) ?>
<span class="badge bg-secondary ms-1"><?= $total ?></span>
</a>
</li>
<?php endforeach; ?>
</ul>
<!-- Tab content -->
<div class="tab-content mt-3" id="certTabContent">
<?php foreach ($gradeGroups as $key => $group): ?>
<?php $isActive = ($key === $defaultKey); ?>
<div class="tab-pane fade <?= $isActive ? 'show active' : '' ?>"
id="cert-<?= esc($group['slug']) ?>"
role="tabpanel"
aria-labelledby="cert-<?= esc($group['slug']) ?>-tab">
<?php foreach ($group['csids'] as $csid): ?>
<?php
$cs = $statsPerClass[$csid];
$students = $studentsByClass[$csid] ?? [];
$csPass = $cs['pass'];
$csCert = $cs['cert'];
$csRemain = max(0, $csPass - $csCert);
$formId = 'certForm-' . $csid;
$tableId = 'studentsTable-' . $csid;
?>
<h4 class="mt-4 mb-2 text-center"><?= esc($cs['name']) ?></h4>
<?php if (empty($students)): ?>
<p class="text-muted text-center">No active students.</p>
<?php else: ?>
<form method="post"
action="<?= site_url('administrator/certificates/generate') ?>"
id="<?= esc($formId) ?>"
class="cert-form mb-5">
<?= csrf_field() ?>
<input type="hidden" name="class_section_id" value="<?= (int)$csid ?>">
<input type="hidden" name="school_year" value="<?= esc($schoolYear) ?>">
<!-- Stats + date picker -->
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
<div class="d-flex align-items-center gap-4 flex-wrap">
<span class="fw-semibold">
Students <span class="badge bg-secondary ms-1"><?= count($students) ?></span>
</span>
<span class="text-muted small">
<strong class="text-success"><?= $csPass ?></strong> Pass
</span>
<span class="text-muted small">
<strong class="text-primary"><?= $csCert ?></strong> Generated
</span>
<span class="text-muted small">
<strong class="<?= $csRemain > 0 ? 'text-warning' : 'text-muted' ?>">
<?= $csRemain ?>
</strong>
Remaining
</span>
</div>
<div class="input-group input-group-sm" style="width:200px;">
<span class="input-group-text"><i class="bi bi-calendar3"></i></span>
<input type="date"
class="form-control cert-date-picker"
value="<?= date('Y-m-d') ?>"
title="Certificate date">
<input type="hidden"
name="cert_date"
class="cert-date-hidden"
value="<?= esc($certDate) ?>">
</div>
</div>
<!-- Student table -->
<div class="table-responsive">
<table class="table table-hover table-striped align-middle mb-0 cert-students-table"
id="<?= esc($tableId) ?>">
<thead class="table-light">
<tr>
<th style="width:40px;" class="text-center">
<input class="form-check-input cert-select-all" type="checkbox">
</th>
<th>First Name</th>
<th>Last Name</th>
<th class="text-center">Year Score</th>
<th>Decision</th>
<th>Certificate No.</th>
</tr>
</thead>
<tbody>
<?php foreach ($students as $s): ?>
<?php
$sid = (int)$s['student_id'];
$stuDec = $decisionsByStudent[$sid] ?? [];
$certNo = $certsByStudent[$sid] ?? null;
$allDecs = array_map(
fn($d) => trim((string)($d['decision'] ?? '')),
$stuDec
);
$hasPending = in_array('', $allDecs, true);
$unique = array_values(array_unique(array_filter(
$allDecs,
fn($d) => $d !== ''
)));
$isPass = !empty($stuDec) && !$hasPending && $unique === ['Pass'];
$displayDecs = $isPass
? ['Pass']
: array_values(array_filter($unique, fn($d) => $d !== 'Pass'));
$yearScore = null;
foreach ($stuDec as $d) {
if (
array_key_exists('year_score', $d)
&& $d['year_score'] !== null
&& $d['year_score'] !== ''
) {
$yearScore = $d['year_score'];
break;
}
}
$fmtYearScore = is_numeric($yearScore)
? number_format((float)$yearScore, 2)
: '—';
?>
<tr>
<td class="text-center">
<input class="form-check-input cert-student-check"
type="checkbox"
name="student_ids[]"
value="<?= $sid ?>"
<?= $isPass ? '' : 'disabled' ?>>
</td>
<td><?= esc($s['firstname']) ?></td>
<td><?= esc($s['lastname']) ?></td>
<td class="text-center fw-semibold">
<?= esc($fmtYearScore) ?>
</td>
<td>
<?php if (empty($stuDec)): ?>
<span class="text-muted small">—</span>
<?php elseif ($hasPending || empty($unique) || empty($displayDecs)): ?>
<span class="badge bg-warning text-dark">Pending</span>
<?php else: ?>
<?php foreach ($displayDecs as $dec): ?>
<?php $color = $decisionBadge[$dec] ?? 'secondary'; ?>
<span class="badge bg-<?= esc($color) ?> me-1">
<?= esc($dec) ?>
</span>
<?php endforeach; ?>
<?php endif; ?>
</td>
<td>
<?php if ($certNo): ?>
<a href="<?= site_url('administrator/certificates/reprint/' . rawurlencode($certNo)) ?>"
target="_blank"
class="font-monospace small">
<?= esc($certNo) ?>
</a>
<?php else: ?>
<span class="text-muted">—</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<!-- Footer -->
<div class="d-flex justify-content-between align-items-center mt-2">
<span class="text-muted small cert-selected-count">0 students selected</span>
<button type="submit" class="btn btn-success cert-generate-btn" disabled>
<i class="bi bi-printer me-1"></i>Generate &amp; Print Certificates
</button>
</div>
</form>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div><!-- .wrapper -->
</div><!-- .container-fluid -->
<script>
(function () {
const csrfRefreshUrl = <?= json_encode(site_url('administrator/certificates/csrf-token'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
let currentCsrfTokenName = <?= json_encode(csrf_token(), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
function cssEscape(v) {
return window.CSS?.escape ? window.CSS.escape(v) : String(v).replace(/(["\\.#:[\],= ])/g, '\\$1');
}
function updateCsrfInForm(form, name, hash) {
if (!form || !name || !hash) return;
form.querySelectorAll('input[type="hidden"]').forEach(inp => {
if (inp.name === name || inp.name === currentCsrfTokenName) {
inp.name = name;
inp.value = hash;
}
});
let inp = form.querySelector(`input[name="${cssEscape(name)}"]`);
if (!inp) {
inp = document.createElement('input');
inp.type = 'hidden';
inp.name = name;
form.appendChild(inp);
}
inp.value = hash;
currentCsrfTokenName = name;
}
async function refreshCsrf(form) {
const r = await fetch(csrfRefreshUrl, {
method: 'GET',
credentials: 'same-origin',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Cache-Control': 'no-store'
}
});
if (!r.ok) throw new Error('CSRF refresh failed');
const d = await r.json();
if (d?.csrf_token && d?.csrf_hash) {
updateCsrfInForm(form, d.csrf_token, d.csrf_hash);
}
}
let pdfWindow = null;
let activePdfBlobUrl = null;
function openPdfWindow() {
if (!pdfWindow || pdfWindow.closed) {
pdfWindow = window.open('', 'certificatePdfWindow');
}
if (!pdfWindow) return null;
pdfWindow.document.open();
pdfWindow.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Certificate PDF</title>
<style>
html,body{margin:0;height:100%;background:#f3f4f6;font-family:Arial,sans-serif}
.viewer-shell{display:flex;flex-direction:column;height:100%}
.viewer-status{padding:12px 16px;background:#111827;color:#fff;font-size:14px}
.viewer-frame{flex:1;width:100%;border:0;background:#cbd5e1}
</style></head>
<body>
<div class="viewer-shell">
<div class="viewer-status" id="viewerStatus">Preparing certificate PDF...</div>
<iframe class="viewer-frame" id="pdfFrame"></iframe>
</div>
<script>
window.showCertificatePdf=function(url,fn){
const f=document.getElementById('pdfFrame'),s=document.getElementById('viewerStatus');
if(s)s.textContent=fn?'Showing '+fn:'Certificate PDF ready';
if(f)f.src=url;
document.title=fn||'Certificate PDF';
};
<\/script>
</body></html>`);
pdfWindow.document.close();
return pdfWindow;
}
function showError(pane, msg) {
let el = pane.querySelector('.cert-inline-error');
if (!el) {
el = document.createElement('div');
el.className = 'alert alert-danger alert-dismissible fade show cert-inline-error';
pane.prepend(el);
}
el.innerHTML = `${msg}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
}
document.querySelectorAll('.cert-form').forEach(function (form) {
const pane = form.closest('.tab-pane') || form.parentElement;
const selectAll = form.querySelector('.cert-select-all');
const checks = form.querySelectorAll('.cert-student-check');
const eligibleChecks = form.querySelectorAll('.cert-student-check:not([disabled])');
const generateBtn = form.querySelector('.cert-generate-btn');
const selectedCount = form.querySelector('.cert-selected-count');
const datePicker = form.querySelector('.cert-date-picker');
const dateHidden = form.querySelector('.cert-date-hidden');
if (datePicker && dateHidden) {
datePicker.addEventListener('change', function () {
const d = new Date(this.value + 'T00:00:00');
if (!isNaN(d)) {
dateHidden.value =
String(d.getMonth() + 1).padStart(2, '0') + '/' +
String(d.getDate()).padStart(2, '0') + '/' +
d.getFullYear();
}
});
}
function updateState() {
const chosen = form.querySelectorAll('.cert-student-check:checked').length;
if (selectedCount) {
selectedCount.textContent = chosen + ' student' + (chosen !== 1 ? 's' : '') + ' selected';
}
if (generateBtn) {
generateBtn.disabled = chosen === 0;
}
if (selectAll) {
const ec = eligibleChecks.length;
selectAll.checked = ec > 0 && chosen === ec;
selectAll.indeterminate = chosen > 0 && chosen < ec;
}
}
if (selectAll) {
selectAll.addEventListener('change', function () {
eligibleChecks.forEach(c => {
c.checked = this.checked;
});
updateState();
});
}
checks.forEach(c => c.addEventListener('change', updateState));
updateState();
form.addEventListener('submit', async function (e) {
e.preventDefault();
const chosen = form.querySelectorAll('.cert-student-check:checked').length;
if (chosen === 0) {
showError(pane, 'Please select at least one student.');
return;
}
const win = openPdfWindow();
if (!win) {
showError(pane, 'Unable to open PDF tab — please allow pop-ups.');
return;
}
const origHtml = generateBtn.innerHTML;
generateBtn.disabled = true;
generateBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Generating...';
try {
await refreshCsrf(form);
const csrfVal = form.querySelector(`input[name="${cssEscape(currentCsrfTokenName)}"]`)?.value || '';
const fd = new FormData(form);
if (csrfVal) {
fd.set(currentCsrfTokenName, csrfVal);
}
const resp = await fetch(form.action, {
method: 'POST',
body: fd,
credentials: 'same-origin',
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});
const nn = resp.headers.get('X-CSRF-TOKEN-NAME');
const nh = resp.headers.get('X-CSRF-TOKEN');
if (nn && nh) {
updateCsrfInForm(form, nn, nh);
}
const ct = resp.headers.get('Content-Type') || '';
if (!resp.ok || !ct.toLowerCase().includes('application/pdf')) {
let msg = 'Certificate generation failed.';
try {
const d = await resp.json();
if (d?.error) {
msg = d.error;
}
} catch (_) {
try {
msg = await resp.text() || msg;
} catch (_2) {}
}
win.close();
showError(pane, msg);
await refreshCsrf(form).catch(() => {});
return;
}
const disp = resp.headers.get('Content-Disposition') || '';
const fn = (disp.match(/filename="?([^"]+)"?/i) || [])[1] || 'Certificates.pdf';
const url = URL.createObjectURL(await resp.blob());
if (activePdfBlobUrl) {
URL.revokeObjectURL(activePdfBlobUrl);
}
activePdfBlobUrl = url;
win.showCertificatePdf(url, fn);
const activePane = form.closest('.tab-pane');
if (activePane?.id) {
window.location.hash = activePane.id;
}
window.location.reload();
} catch (_) {
showError(pane, 'Certificate generation failed. Please try again.');
await refreshCsrf(form).catch(() => {});
} finally {
generateBtn.innerHTML = origHtml;
updateState();
}
});
});
})();
</script>
<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
// Restore tab from hash — runs after Bootstrap is loaded
(function () {
const hash = window.location.hash;
if (!hash) return;
const tabLink = document.querySelector('a[href="' + hash + '"][data-bs-toggle="tab"]');
if (tabLink && window.bootstrap?.Tab) {
new bootstrap.Tab(tabLink).show();
}
})();
</script>
<style>
.cert-status-dot {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 5px;
vertical-align: middle;
flex-shrink: 0;
}
.cert-status-dot.done {
background-color: #198754;
}
.cert-status-dot.pending {
background-color: #dc3545;
}
.cert-status-dot.no-eligible {
background-color: #adb5bd;
}
</style>
<script>
(function () {
if (!window.$ || !$.fn?.DataTable) return;
$(function () {
document.querySelectorAll('.cert-students-table').forEach(function (tbl) {
if ($.fn.DataTable.isDataTable(tbl)) return;
try {
$(tbl).DataTable({
order: [[1, 'asc'], [2, 'asc']],
pageLength: 100,
lengthMenu: [25, 50, 100, 200],
columnDefs: [
{ orderable: false, targets: [0, 4, 5] }
]
});
} catch (_) {}
});
});
})();
</script>
<?= $this->endSection() ?>
@@ -28,7 +28,7 @@
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Description</label> <label class="form-label">Description</label>
<textarea name="description" class="form-control"></textarea> <textarea id="event_description" name="description" class="form-control"></textarea>
</div> </div>
<div class="mb-3"> <div class="mb-3">
@@ -56,9 +56,89 @@
<input type="text" name="school_year" class="form-control" required> <input type="text" name="school_year" class="form-control" required>
</div> </div>
<div class="card mb-3">
<div class="card-header">School Calendar</div>
<div class="card-body">
<div class="form-check mb-2">
<input class="form-check-input" type="checkbox" id="add_to_calendar" name="add_to_calendar" value="1">
<label class="form-check-label" for="add_to_calendar">
Add this event to the school calendar
</label>
</div>
<div id="calendar_recipients" class="ms-3" style="display:none;">
<div class="mb-2 fw-semibold">Visible On Calendars</div>
<div class="d-flex flex-wrap gap-3">
<label class="form-check-label">
<input class="form-check-input me-1" type="checkbox" name="notify_parent" value="1" checked>
Parents
</label>
<label class="form-check-label">
<input class="form-check-input me-1" type="checkbox" name="notify_teacher" value="1" checked>
Teachers
</label>
<label class="form-check-label">
<input class="form-check-input me-1" type="checkbox" name="notify_admin" value="1" checked>
Admins
</label>
</div>
<div class="form-text">If none are selected, the event is visible to everyone.</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">Parent Email Broadcast</div>
<div class="card-body">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="send_email_parent" name="send_email_parent" value="1">
<label class="form-check-label" for="send_email_parent">
Send one event email to all parents and add all parent emails in CC
</label>
</div>
<div class="form-text">The email is sent once. The school sender address stays in To, and all parent emails are placed in CC.</div>
</div>
</div>
<button type="submit" class="btn btn-success">Create Event</button> <button type="submit" class="btn btn-success">Create Event</button>
<a href="<?= site_url('administrator/events') ?>" class="btn btn-secondary">Cancel</a> <a href="<?= site_url('administrator/events') ?>" class="btn btn-secondary">Cancel</a>
</form> </form>
</div> </div>
<?= $this->endSection() ?> <?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script src="<?= base_url('assets/tinymce/tinymce.min.js') ?>"></script>
<script>
(function () {
const toggle = document.getElementById('add_to_calendar');
const recipients = document.getElementById('calendar_recipients');
const description = document.getElementById('event_description');
if (toggle && recipients) {
function sync() {
recipients.style.display = toggle.checked ? '' : 'none';
}
toggle.addEventListener('change', sync);
sync();
}
if (description && window.tinymce) {
tinymce.init({
selector: '#event_description',
base_url: '<?= base_url('assets/tinymce') ?>',
suffix: '.min',
license_key: 'gpl',
height: 320,
menubar: true,
branding: false,
promotion: false,
plugins: 'advlist autolink lists link charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime table help wordcount',
toolbar: 'undo redo | blocks | bold italic underline strikethrough forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link table | removeformat | preview code',
convert_urls: false,
content_style: 'body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; font-size: 14px; }'
});
}
})();
</script>
<?= $this->endSection() ?>
+89 -3
View File
@@ -4,6 +4,12 @@
<div class="container mt-4"> <div class="container mt-4">
<h2>Edit Event</h2> <h2>Edit Event</h2>
<?php
$defaultCategories = ['Fun Event-1', 'Fun Event-2', 'Fun Event-3'];
$existingCategories = array_map('strval', $categories ?? []);
$allCategories = array_unique(array_merge($defaultCategories, $existingCategories));
?>
<?php if (session()->getFlashdata('error')): ?> <?php if (session()->getFlashdata('error')): ?>
<div class="alert alert-danger"><?= session()->getFlashdata('error') ?></div> <div class="alert alert-danger"><?= session()->getFlashdata('error') ?></div>
<?php endif; ?> <?php endif; ?>
@@ -23,7 +29,7 @@
<label class="form-label">Category</label> <label class="form-label">Category</label>
<select name="event_category" class="form-control" required> <select name="event_category" class="form-control" required>
<option value="" disabled <?= empty($event['event_category']) ? 'selected' : '' ?>>Select category</option> <option value="" disabled <?= empty($event['event_category']) ? 'selected' : '' ?>>Select category</option>
<?php foreach (($categories ?? []) as $category): ?> <?php foreach ($allCategories as $category): ?>
<option value="<?= esc($category) ?>" <?= (string)($event['event_category'] ?? '') === (string)$category ? 'selected' : '' ?>> <option value="<?= esc($category) ?>" <?= (string)($event['event_category'] ?? '') === (string)$category ? 'selected' : '' ?>>
<?= esc(ucwords($category)) ?> <?= esc(ucwords($category)) ?>
</option> </option>
@@ -33,7 +39,7 @@
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Description</label> <label class="form-label">Description</label>
<textarea name="description" class="form-control"><?= esc($event['description']) ?></textarea> <textarea id="event_description" name="description" class="form-control"><?= esc($event['description']) ?></textarea>
</div> </div>
<div class="mb-3"> <div class="mb-3">
@@ -44,7 +50,7 @@
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Current Flyer</label><br> <label class="form-label">Current Flyer</label><br>
<?php if ($event['flyer']): ?> <?php if ($event['flyer']): ?>
<img src="<?= base_url('writable/uploads/' . $event['flyer']) ?>" width="150" class="mb-2"> <img src="<?= base_url('uploads/' . ltrim((string) $event['flyer'], '/')) ?>" width="150" class="mb-2">
<?php else: ?> <?php else: ?>
<div class="text-muted">No flyer uploaded.</div> <div class="text-muted">No flyer uploaded.</div>
<?php endif; ?> <?php endif; ?>
@@ -70,9 +76,89 @@
<input type="text" name="school_year" class="form-control" value="<?= esc($event['school_year']) ?>" required> <input type="text" name="school_year" class="form-control" value="<?= esc($event['school_year']) ?>" required>
</div> </div>
<div class="card mb-3">
<div class="card-header">School Calendar</div>
<div class="card-body">
<div class="form-check mb-2">
<input class="form-check-input" type="checkbox" id="add_to_calendar" name="add_to_calendar" value="1">
<label class="form-check-label" for="add_to_calendar">
Add this event to the school calendar
</label>
</div>
<div id="calendar_recipients" class="ms-3" style="display:none;">
<div class="mb-2 fw-semibold">Visible On Calendars</div>
<div class="d-flex flex-wrap gap-3">
<label class="form-check-label">
<input class="form-check-input me-1" type="checkbox" name="notify_parent" value="1" checked>
Parents
</label>
<label class="form-check-label">
<input class="form-check-input me-1" type="checkbox" name="notify_teacher" value="1" checked>
Teachers
</label>
<label class="form-check-label">
<input class="form-check-input me-1" type="checkbox" name="notify_admin" value="1" checked>
Admins
</label>
</div>
<div class="form-text">If none are selected, the event is visible to everyone.</div>
</div>
</div>
</div>
<div class="card mb-3">
<div class="card-header">Parent Email Broadcast</div>
<div class="card-body">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="send_email_parent" name="send_email_parent" value="1">
<label class="form-check-label" for="send_email_parent">
Send one event email to all parents and add all parent emails in CC
</label>
</div>
<div class="form-text">Use this when you want to rebroadcast the updated event to all parents in a single email.</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Update Event</button> <button type="submit" class="btn btn-primary">Update Event</button>
<a href="<?= site_url('administrator/events') ?>" class="btn btn-secondary">Cancel</a> <a href="<?= site_url('administrator/events') ?>" class="btn btn-secondary">Cancel</a>
</form> </form>
</div> </div>
<?= $this->endSection() ?> <?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script src="<?= base_url('assets/tinymce/tinymce.min.js') ?>"></script>
<script>
(function () {
const toggle = document.getElementById('add_to_calendar');
const recipients = document.getElementById('calendar_recipients');
const description = document.getElementById('event_description');
if (toggle && recipients) {
function sync() {
recipients.style.display = toggle.checked ? '' : 'none';
}
toggle.addEventListener('change', sync);
sync();
}
if (description && window.tinymce) {
tinymce.init({
selector: '#event_description',
base_url: '<?= base_url('assets/tinymce') ?>',
suffix: '.min',
license_key: 'gpl',
height: 320,
menubar: true,
branding: false,
promotion: false,
plugins: 'advlist autolink lists link charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime table help wordcount',
toolbar: 'undo redo | blocks | bold italic underline strikethrough forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link table | removeformat | preview code',
convert_urls: false,
content_style: 'body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; font-size: 14px; }'
});
}
})();
</script>
<?= $this->endSection() ?>
+633 -48
View File
@@ -3,6 +3,54 @@
<div class="container mt-5"> <div class="container mt-5">
<h3>Event Charges</h3> <h3>Event Charges</h3>
<style>
.event-card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.event-card-header-actions {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.sortable-header {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0;
border: 0;
background: transparent;
color: inherit;
font-weight: 600;
text-decoration: none;
}
.sortable-header:hover,
.sortable-header:focus {
color: var(--bs-primary);
text-decoration: none;
}
.sortable-header::after {
content: '↕';
font-size: 0.85rem;
opacity: 0.45;
}
.sortable-header.sorted-asc::after {
content: '↑';
opacity: 1;
}
.sortable-header.sorted-desc::after {
content: '↓';
opacity: 1;
}
@media print {
.no-print {
display: none !important;
}
}
</style>
<?php if (session()->getFlashdata('success')): ?> <?php if (session()->getFlashdata('success')): ?>
<div class="alert alert-success"><?= session()->getFlashdata('success') ?></div> <div class="alert alert-success"><?= session()->getFlashdata('success') ?></div>
@@ -12,6 +60,14 @@
<?php endif; ?> <?php endif; ?>
<?php <?php
$classSectionNames = $classSectionNames ?? [];
$semesterOptions = $semesterOptions ?? [];
$schoolYearOptions = $schoolYearOptions ?? [];
?>
<?php
$filterParentId = $filterParentId ?? 0;
$parentBalances = $parentBalances ?? [];
$selectedEvent = null; $selectedEvent = null;
if (!empty($filterEventId)) { if (!empty($filterEventId)) {
foreach ($events as $event) { foreach ($events as $event) {
@@ -22,18 +78,58 @@
} }
} }
?> ?>
<div class="card mb-4">
<div class="card-body">
<form method="get" action="<?= site_url('administrator/event-charges') ?>" class="row g-3 align-items-end">
<?php if ($filterEventId > 0): ?>
<input type="hidden" name="event_id" value="<?= esc($filterEventId) ?>">
<?php endif; ?>
<?php if ($filterParentId > 0): ?>
<input type="hidden" name="parent_id" value="<?= esc($filterParentId) ?>">
<?php endif; ?>
<div class="col-md-4">
<label for="semester_filter" class="form-label">Semester</label>
<select id="semester_filter" name="semester" class="form-select">
<option value="">-- All semesters --</option>
<?php foreach ($semesterOptions as $option): ?>
<option value="<?= esc($option) ?>" <?= $semester === $option ? 'selected' : '' ?>>
<?= esc($option) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-4">
<label for="school_year_filter" class="form-label">School Year</label>
<select id="school_year_filter" name="school_year" class="form-select">
<option value="">-- All school years --</option>
<?php foreach ($schoolYearOptions as $option): ?>
<option value="<?= esc($option) ?>" <?= $school_year === $option ? 'selected' : '' ?>>
<?= esc($option) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-outline-primary">Filter</button>
</div>
</form>
</div>
</div>
<!-- Add New Charge Form --> <!-- Add New Charge Form -->
<div class="card mb-4"> <div class="card mb-4">
<div class="card-body"> <div class="card-body">
<form action="<?= site_url('payment/event_charges') ?>" method="post"> <form id="event-participant-form" action="<?= site_url('payment/event_charges') ?>" method="post">
<?= csrf_field() ?> <?= csrf_field() ?>
<input type="hidden" name="school_year" value="<?= esc($school_year) ?>">
<input type="hidden" name="semester" value="<?= esc($semester) ?>">
<div class="row g-3"> <div class="row g-3">
<div class="col-md-4"> <div class="col-md-4">
<label for="event_id" class="form-label">Select Event</label> <label for="event_id" class="form-label">Select Event</label>
<select name="event_id" id="event_id" class="form-select" required> <select name="event_id" id="event_id" class="form-select" required>
<option value="">-- All events --</option> <option value="">-- All events --</option>
<?php foreach ($events as $event): ?> <?php foreach ($events as $event): ?>
<option value="<?= esc($event['id']) ?>" <?= isset($filterEventId) && $filterEventId == $event['id'] ? 'selected' : '' ?>> <option value="<?= esc($event['id']) ?>" data-amount="<?= esc(number_format($event['amount'] ?? 0, 2, '.', '')) ?>" <?= isset($filterEventId) && $filterEventId == $event['id'] ? 'selected' : '' ?>>
<?= esc($event['event_name']) ?> <?= esc($event['event_name']) ?>
</option> </option>
<?php endforeach; ?> <?php endforeach; ?>
@@ -49,9 +145,24 @@
$<?= esc(number_format($selectedEvent['amount'] ?? 0, 2)) ?> fee $<?= esc(number_format($selectedEvent['amount'] ?? 0, 2)) ?> fee
</span> </span>
</div> </div>
<p class="mb-1 text-muted small"> <?php $eventDescription = trim((string) ($selectedEvent['description'] ?? '')); ?>
<?= esc($selectedEvent['description'] ?: 'No description provided for this event.') ?> <div class="mb-1">
</p> <button type="button"
class="btn btn-link btn-sm px-0 py-0 text-decoration-none event-description-toggle"
data-bs-toggle="collapse"
data-bs-target="#selectedEventDescription"
aria-expanded="false"
aria-controls="selectedEventDescription"
data-label-collapsed="Show description"
data-label-expanded="Hide description">
Show description
</button>
<div class="collapse mt-2" id="selectedEventDescription">
<div class="text-muted small" style="white-space: pre-line;">
<?= esc($eventDescription !== '' ? $eventDescription : 'No description provided for this event.') ?>
</div>
</div>
</div>
<?php if (!empty($selectedEvent['expiration_date'])): ?> <?php if (!empty($selectedEvent['expiration_date'])): ?>
<small class="text-secondary"> <small class="text-secondary">
Expires: <?= esc(local_date($selectedEvent['expiration_date'], 'm-d-Y')) ?> Expires: <?= esc(local_date($selectedEvent['expiration_date'], 'm-d-Y')) ?>
@@ -61,15 +172,12 @@
</div> </div>
<?php endif; ?> <?php endif; ?>
</div>
<div class="row g-3 mt-2">
<div class="col-md-4"> <div class="col-md-4">
<label for="parent_id" class="form-label">Parents List</label> <label for="parent_id" class="form-label">Parents List</label>
<select id="parent_id" name="parent_id" class="form-select" required> <select id="parent_id" name="parent_id" class="form-select">
<option value="">-- Select Parent --</option> <option value="">-- Select Parent --</option>
<?php foreach ($parents as $parent): ?> <?php foreach ($parents as $parent): ?>
<option value="<?= $parent['id'] ?>"> <option value="<?= esc($parent['id']) ?>" <?= $filterParentId && $filterParentId == $parent['id'] ? 'selected' : '' ?>>
<?= esc($parent['firstname'] . ' ' . $parent['lastname']) ?> (<?= esc($parent['school_id']) ?>) <?= esc($parent['firstname'] . ' ' . $parent['lastname']) ?> (<?= esc($parent['school_id']) ?>)
</option> </option>
<?php endforeach; ?> <?php endforeach; ?>
@@ -82,6 +190,15 @@
<div id="studentList" class="row g-3"></div> <div id="studentList" class="row g-3"></div>
</div> </div>
<div class="mt-4">
<?php if (!in_array(strtolower((string)(session()->get('role') ?? '')), ['parent', 'teacher', 'teacher_assistant'], true)): ?>
<button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#externalParticipantModal">
Add non-school participant
</button>
<?php endif; ?>
<div class="form-text">Enrolled students are saved when you click Submit. Non-school participants are saved immediately and will then appear in all browsers.</div>
</div>
<div class="d-flex flex-wrap gap-2 mt-3"> <div class="d-flex flex-wrap gap-2 mt-3">
<button type="submit" class="btn btn-primary">Submit</button> <button type="submit" class="btn btn-primary">Submit</button>
<a href="<?= site_url('administrator/events') ?>" class="btn btn-success">Event List</a> <a href="<?= site_url('administrator/events') ?>" class="btn btn-success">Event List</a>
@@ -89,77 +206,326 @@
</form> </form>
</div> </div>
</div> </div>
<!-- Charge Tables grouped by event --> <!-- Charge Tables grouped by event -->
<?php <?php
$grouped = []; $grouped = [];
foreach ($charges as $charge) { foreach ($charges as $charge) {
$label = $charge['event_name'] ?? 'N/A'; $eventId = (int)($charge['event_id'] ?? 0);
$grouped[$label][] = $charge; if (!isset($grouped[$eventId])) {
$grouped[$eventId] = [
'label' => $charge['event_name'] ?? 'N/A',
'rows' => [],
];
}
$grouped[$eventId]['rows'][] = $charge;
} }
?> ?>
<?php if (empty($grouped)): ?> <?php if (empty($grouped)): ?>
<div class="alert alert-info">No charges found.</div> <div class="alert alert-info">No charges found.</div>
<?php else: ?> <?php else: ?>
<?php foreach ($grouped as $eventLabel => $rows): ?> <?php
<div class="card mb-4"> $printBaseParams = array_filter([
<div class="card-header bg-light fw-semibold"> 'school_year' => $school_year,
<?= esc($eventLabel) ?> 'semester' => $semester,
'parent_id' => $filterParentId > 0 ? $filterParentId : null,
'event_id' => $filterEventId > 0 ? $filterEventId : null,
], static fn ($value) => $value !== null && $value !== '');
$printAllUrl = site_url('administrator/event-charges/pdf');
if (!empty($printBaseParams)) {
$printAllUrl .= '?' . http_build_query($printBaseParams);
}
?>
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3 no-print">
<p class="text-muted mb-0">Click a column header to sort the participants list.</p>
<a href="<?= esc($printAllUrl) ?>"
class="btn btn-outline-secondary pdf-print-link"
data-base-href="<?= esc($printAllUrl) ?>"
data-print-scope="all">
Print All Participant Lists
</a>
</div>
<div id="eventChargeCards">
<?php foreach ($grouped as $eventId => $data): ?>
<?php $eventLabel = $data['label']; ?>
<?php $rows = $data['rows']; ?>
<?php
$singlePrintParams = array_filter([
'school_year' => $school_year,
'semester' => $semester,
'parent_id' => $filterParentId > 0 ? $filterParentId : null,
'event_id' => $eventId,
], static fn ($value) => $value !== null && $value !== '');
$singlePrintUrl = site_url('administrator/event-charges/pdf') . '?' . http_build_query($singlePrintParams);
?>
<div class="card mb-4 event-card" data-event-id="<?= esc($eventId) ?>">
<div class="card-header bg-light fw-semibold event-card-header">
<span><?= esc($eventLabel) ?></span>
<div class="event-card-header-actions no-print">
<a href="<?= esc($singlePrintUrl) ?>"
class="btn btn-outline-secondary btn-sm pdf-print-link"
data-base-href="<?= esc($singlePrintUrl) ?>"
data-print-scope="single"
data-event-id="<?= esc($eventId) ?>">
Print This List
</a>
</div>
</div> </div>
<div class="card-body p-0"> <div class="card-body p-0">
<?php
$totalParticipants = 0;
$totalCharged = 0.0;
?>
<div class="table-responsive"> <div class="table-responsive">
<table class="table table-bordered table-striped mb-0 no-mgmt-sticky"> <table id="eventTable_<?= esc($eventId) ?>" class="table table-bordered table-striped mb-0 no-mgmt-sticky event-charges-table">
<thead class="table-light"> <thead class="table-light">
<tr> <tr>
<th>ID</th> <th><button type="button" class="sortable-header" data-sort-index="0" data-sort-type="number">ID</button></th>
<th>Parent Name</th> <th><button type="button" class="sortable-header" data-sort-index="1" data-sort-type="text">Parent Name</button></th>
<th>Student Name</th> <th><button type="button" class="sortable-header" data-sort-index="2" data-sort-type="text">Student Name</button></th>
<th>Charged Amount</th> <th><button type="button" class="sortable-header" data-sort-index="3" data-sort-type="text">External Info</button></th>
<th>Is Participating</th> <th><button type="button" class="sortable-header" data-sort-index="4" data-sort-type="text">Class Section</button></th>
<th>Semester</th> <th><button type="button" class="sortable-header" data-sort-index="5" data-sort-type="number">Charged Amount</button></th>
<th>Year</th> <th><button type="button" class="sortable-header" data-sort-index="6" data-sort-type="date">Created</button></th>
<th>Created</th> <th><button type="button" class="sortable-header" data-sort-index="7" data-sort-type="text">Waiver</button></th>
<th>Description</th> <th><button type="button" class="sortable-header" data-sort-index="8" data-sort-type="text">Fees Paid</button></th>
<th>Event Fees</th> <th><button type="button" class="sortable-header" data-sort-index="9" data-sort-type="text">Payment</button></th>
<th>Actions</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php foreach ($rows as $charge): ?> <?php foreach ($rows as $charge): ?>
<tr> <?php
<td><?= esc($charge['id']) ?></td> $isParticipating = ($charge['participation'] === 'yes');
<td><?= esc($charge['parent_firstname'] . ' ' . $charge['parent_lastname']) ?></td> $isEventPaid = !empty($charge['event_paid']);
<td> $returnParams = [];
<?= $charge['student_firstname'] if (!empty($semester)) {
? esc($charge['student_firstname'] . ' ' . $charge['student_lastname']) $returnParams['semester'] = $semester;
: '-' ?> }
if (!empty($school_year)) {
$returnParams['school_year'] = $school_year;
}
if (!empty($filterEventId)) {
$returnParams['event_id'] = $filterEventId;
}
if (!empty($filterParentId)) {
$returnParams['parent_id'] = $filterParentId;
}
$returnTo = site_url('administrator/event-charges')
. (!empty($returnParams) ? '?' . http_build_query($returnParams) : '')
. '#eventTable_' . (int) ($charge['event_id'] ?? 0);
?>
<tr data-charge-id="<?= esc((string) ($charge['id'] ?? '')) ?>">
<td data-sort-value="<?= esc((string) ($charge['id'] ?? '')) ?>"><?= esc($charge['id']) ?></td>
<?php
$studentName = $charge['student_firstname']
? trim($charge['student_firstname'] . ' ' . $charge['student_lastname'])
: '';
$externalName = trim(
($charge['external_firstname'] ?? '') . ' ' .
($charge['external_lastname'] ?? '')
);
$displayName = $studentName ?: ($externalName ?: '—');
$externalNote = $charge['external_note'] ?? '';
$externalParentLabel = trim(
($charge['external_parent_firstname'] ?? '') . ' ' .
($charge['external_parent_lastname'] ?? '')
);
$externalParentPhone = $charge['external_parent_phone'] ?? '';
$externalParentEmail = $charge['external_parent_email'] ?? '';
$parentPhone = $charge['parent_cellphone'] ?? '';
$standardParentName = trim($charge['parent_firstname'] . ' ' . $charge['parent_lastname']);
$parentColumnName = $externalParentLabel ?: ($standardParentName ?: '—');
$isExternalParticipant = $externalName !== '';
$infoPhone = $isExternalParticipant ? $externalParentPhone : $parentPhone;
$infoEmail = $isExternalParticipant ? $externalParentEmail : '';
$externalInfoValue = trim(implode(' ', array_filter([
$infoPhone,
$infoEmail,
$externalNote,
])));
?>
<td data-sort-value="<?= esc(strtolower($parentColumnName)) ?>"><?= esc($parentColumnName) ?></td>
<td data-sort-value="<?= esc(strtolower($displayName)) ?>">
<?= esc($displayName) ?>
<?php if ($externalNote): ?>
<small class="text-muted d-block"><?= esc($externalNote) ?></small>
<?php endif; ?>
</td> </td>
<td>$<?= esc(number_format($charge['charged'] ?? 0, 2)) ?></td> <td data-sort-value="<?= esc(strtolower($externalInfoValue)) ?>">
<td> <?php if ($infoPhone): ?>
<?= $charge['participation'] <div class="text-muted small"><?= esc($infoPhone) ?></div>
? '<span class="badge bg-success">Yes</span>' <?php endif; ?>
: '<span class="badge bg-warning">No</span>' ?> <?php if ($infoEmail): ?>
<div class="text-muted small"><?= esc($infoEmail) ?></div>
<?php endif; ?>
<?php if (!$infoPhone && !$infoEmail): ?>
<span class="text-muted small">—</span>
<?php endif; ?>
</td>
<td data-sort-value="<?= esc(strtolower((string) ($classSectionNames[$charge['class_section_id'] ?? ''] ?? ''))) ?>">
<?= esc($classSectionNames[$charge['class_section_id'] ?? ''] ?? '—') ?>
</td>
<td data-sort-value="<?= esc(number_format((float) ($charge['event_amount'] ?? 0), 2, '.', '')) ?>">$<?= esc(number_format($charge['event_amount'] ?? 0, 2)) ?></td>
<td data-sort-value="<?= esc((string) ($charge['created_at'] ?? '')) ?>"><?= esc(!empty($charge['created_at']) ? local_datetime($charge['created_at'], 'm-d-Y H:i') : '') ?></td>
<?php
$feeAmount = (float) ($charge['event_amount'] ?? 0);
$hasBalanceRecord = array_key_exists((int)$charge['parent_id'], $parentBalances);
$parentBalance = $hasBalanceRecord ? (float)$parentBalances[$charge['parent_id']] : null;
$waiverSigned = !empty($charge['waiver_signed']);
$feeIsPaid = $isParticipating && ($isEventPaid || ($hasBalanceRecord && $parentBalance <= 0));
?>
<td class="text-center" data-sort-value="<?= $waiverSigned ? 'signed' : 'unsigned' ?>">
<form method="post" action="<?= site_url('administrator/event-charges/waiver/' . esc($charge['id'])) ?>" class="d-inline-flex align-items-center">
<?= csrf_field() ?>
<input type="hidden" name="return_to" value="<?= esc($returnTo) ?>">
<input type="hidden" name="waiver_signed" value="<?= $waiverSigned ? '1' : '0' ?>">
<input type="checkbox" class="form-check-input" id="eventWaiver_<?= esc($charge['id']) ?>"
<?= $waiverSigned ? 'checked' : '' ?>
onchange="this.form.waiver_signed.value = this.checked ? 1 : 0; this.form.submit();">
<label class="form-check-label ms-2" for="eventWaiver_<?= esc($charge['id']) ?>" aria-hidden="true">
<?= $waiverSigned ? 'Signed' : 'Unsigned' ?>
</label>
</form>
</td>
<td class="text-center" data-sort-value="<?= $feeIsPaid ? 'paid' : 'unpaid' ?>">
<?php if ($feeIsPaid): ?>
<span class="badge bg-success">Paid</span>
<?php else: ?>
<span class="badge bg-danger">Unpaid</span>
<?php endif; ?>
</td>
<td class="text-center" data-sort-value="<?= $isEventPaid ? 'paid' : 'unpaid' ?>">
<form method="post" action="<?= site_url('administrator/event-charges/payment/' . esc($charge['id'])) ?>" class="d-inline-flex align-items-center">
<?= csrf_field() ?>
<input type="hidden" name="return_to" value="<?= esc($returnTo) ?>">
<input type="hidden" name="paid" value="<?= $feeIsPaid ? '1' : '0' ?>">
<input type="checkbox" class="form-check-input" id="eventPayment_<?= esc($charge['id']) ?>"
<?= $isEventPaid ? 'checked' : '' ?>
onchange="this.form.paid.value = this.checked ? 1 : 0; this.form.submit();">
<label class="form-check-label ms-2" for="eventPayment_<?= esc($charge['id']) ?>" aria-hidden="true">Paid</label>
</form>
</td>
<td class="text-nowrap">
<div class="d-flex gap-1 align-items-center">
<a href="<?= site_url('administrator/event-charges') ?>?event_id=<?= esc($charge['event_id']) ?>&parent_id=<?= esc($charge['parent_id']) ?>#event-participant-form" class="btn btn-outline-primary btn-sm">
Edit
</a>
<form action="<?= site_url('administrator/event-charges/remove/' . esc($charge['id'])) ?>" method="post" onsubmit="return confirm('Remove this participation and update the charge?');">
<?= csrf_field() ?>
<input type="hidden" name="return_to" value="<?= esc($returnTo) ?>">
<button type="submit" class="btn btn-outline-danger btn-sm">Remove</button>
</form>
</div>
</td> </td>
<td><?= esc($charge['semester'] ?? '-') ?></td>
<td><?= esc($charge['school_year'] ?? '-') ?></td>
<td><?= esc(!empty($charge['created_at']) ? local_datetime($charge['created_at'], 'm-d-Y H:i') : '') ?></td>
<td><?= esc($charge['event_description'] ?? '—') ?></td>
<td>$<?= esc(number_format($charge['event_amount'] ?? 0, 2)) ?></td>
</tr> </tr>
<?php
if ($isParticipating) {
$totalParticipants++;
$totalCharged += (float) ($charge['event_amount'] ?? 0);
}
?>
<?php endforeach; ?> <?php endforeach; ?>
</tbody> </tbody>
<tfoot class="table-light">
<tr>
<th colspan="4">Totals</th>
<th>$<?= esc(number_format($totalCharged, 2)) ?></th>
<th colspan="6">
<span class="badge bg-secondary">
<?= esc($totalParticipants) ?> participating
</span>
</th>
</tr>
</tfoot>
</table> </table>
</div> </div>
</div> </div>
</div> </div>
<?php endforeach; ?> <?php endforeach; ?>
<?php endif; ?> </div>
<?php endif; ?>
</div> </div>
<?php if (!in_array(strtolower((string)(session()->get('role') ?? '')), ['parent', 'teacher', 'teacher_assistant'], true)): ?>
<div class="modal fade" id="externalParticipantModal" tabindex="-1" aria-labelledby="externalParticipantModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form id="externalParticipantForm" class="needs-validation" novalidate>
<?= csrf_field() ?>
<div class="modal-header">
<h5 class="modal-title" id="externalParticipantModalLabel">Add Non-School Participant</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p class="small text-muted">Provide the students name and the accompanying guardian/contact details.</p>
<div class="mb-3">
<label class="form-label">Student / Kid Info</label>
<div class="row g-3">
<div class="col-md-6">
<input type="text" class="form-control" id="modalExternalFirstName" placeholder="First name" required>
</div>
<div class="col-md-6">
<input type="text" class="form-control" id="modalExternalLastName" placeholder="Last name" required>
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label">Parent / Contact Info</label>
<div class="row g-3">
<div class="col-md-6">
<input type="text" class="form-control" id="modalParentFirstName" placeholder="Parent first name" required>
</div>
<div class="col-md-6">
<input type="text" class="form-control" id="modalParentLastName" placeholder="Parent last name" required>
</div>
<div class="col-12">
<input type="text" class="form-control" id="modalParentPhone" placeholder="Parent phone or contact">
</div>
<div class="col-12">
<input type="email" class="form-control" id="modalParentEmail" placeholder="Parent email" required>
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label" for="modalExternalNote">Note <span class="text-muted small">(optional)</span></label>
<textarea rows="2" class="form-control" id="modalExternalNote" placeholder="Additional info (e.g., guest, sibling, etc.)"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="externalParticipantSave">
Add to list
</button>
</div>
</form>
</div>
</div>
</div>
<?php endif; ?>
<?= $this->endSection() ?> <?= $this->endSection() ?>
<?= $this->section('scripts') ?> <?= $this->section('scripts') ?>
<script> <script>
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.event-description-toggle').forEach(function (button) {
const targetSelector = button.getAttribute('data-bs-target');
const target = targetSelector ? document.querySelector(targetSelector) : null;
if (!target) {
return;
}
target.addEventListener('show.bs.collapse', function () {
button.textContent = button.dataset.labelExpanded || 'Hide description';
});
target.addEventListener('hide.bs.collapse', function () {
button.textContent = button.dataset.labelCollapsed || 'Show description';
});
});
});
function loadStudentsWithCharges() { function loadStudentsWithCharges() {
let parentId = $('#parent_id').val(); let parentId = $('#parent_id').val();
let eventId = $('#event_id').val(); let eventId = $('#event_id').val();
@@ -201,7 +567,20 @@ function loadStudentsWithCharges() {
} }
} }
$(function() { const capitalizeName = (value) => {
if (!value) return '';
return value
.split(' ')
.map(part => {
const trimmed = part.trim();
if (!trimmed) return '';
return trimmed.charAt(0).toUpperCase() + trimmed.slice(1).toLowerCase();
})
.filter(Boolean)
.join(' ');
};
$(function() {
$('#parent_id').on('change', loadStudentsWithCharges); $('#parent_id').on('change', loadStudentsWithCharges);
$('#event_id').on('change', function() { $('#event_id').on('change', function() {
@@ -214,6 +593,212 @@ $(function() {
} }
window.location.href = url.toString(); window.location.href = url.toString();
}); });
if ($('#event_id').val() && $('#parent_id').val()) {
loadStudentsWithCharges();
}
const $externalSaveButton = $('#externalParticipantSave');
const modalElement = document.getElementById('externalParticipantModal');
const modalInstance = modalElement ? new bootstrap.Modal(modalElement) : null;
function clearModalInputs() {
$('#modalExternalFirstName').val('');
$('#modalExternalLastName').val('');
$('#modalExternalNote').val('');
$('#modalParentFirstName').val('');
$('#modalParentLastName').val('');
$('#modalParentPhone').val('');
$('#modalParentEmail').val('');
}
function appendHiddenField(form, name, value) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = value;
form.appendChild(input);
}
function submitExternalParticipant(payload) {
const form = document.createElement('form');
form.method = 'post';
form.action = '<?= site_url('payment/event_charges') ?>';
appendHiddenField(form, '<?= csrf_token() ?>', '<?= csrf_hash() ?>');
appendHiddenField(form, 'school_year', '<?= esc($school_year) ?>');
appendHiddenField(form, 'semester', '<?= esc($semester) ?>');
appendHiddenField(form, 'event_id', payload.eventId);
appendHiddenField(form, 'external_participants[new][firstname]', payload.firstname);
appendHiddenField(form, 'external_participants[new][lastname]', payload.lastname);
appendHiddenField(form, 'external_participants[new][note]', payload.note);
appendHiddenField(form, 'external_participants[new][parent_firstname]', payload.parentFirstname);
appendHiddenField(form, 'external_participants[new][parent_lastname]', payload.parentLastname);
appendHiddenField(form, 'external_participants[new][parent_phone]', payload.parentPhone);
appendHiddenField(form, 'external_participants[new][parent_email]', payload.parentEmail);
appendHiddenField(form, 'external_participants[new][waiver_signed]', '0');
appendHiddenField(form, 'external_participants[new][paid]', '0');
document.body.appendChild(form);
form.submit();
}
function getSortValue(row, columnIndex, sortType) {
const cell = row.children[columnIndex];
if (!cell) {
return sortType === 'number' ? 0 : '';
}
const rawValue = cell.getAttribute('data-sort-value');
const fallbackValue = (cell.textContent || '').trim();
const value = rawValue !== null ? rawValue : fallbackValue;
if (sortType === 'number') {
const parsed = parseFloat(String(value).replace(/[^0-9.-]/g, ''));
return Number.isNaN(parsed) ? 0 : parsed;
}
if (sortType === 'date') {
const time = Date.parse(value);
return Number.isNaN(time) ? 0 : time;
}
return String(value).toLowerCase();
}
function updateSortIndicators(table, columnIndex, direction) {
$(table).find('.sortable-header').each(function() {
const isCurrent = Number($(this).data('sortIndex')) === Number(columnIndex);
$(this)
.toggleClass('sorted-asc', isCurrent && direction === 'asc')
.toggleClass('sorted-desc', isCurrent && direction === 'desc')
.attr('aria-sort', isCurrent ? direction : 'none');
});
}
function sortEventTable(table, columnIndex, sortType, direction) {
if (!table || !table.tBodies.length) {
return;
}
const tbody = table.tBodies[0];
const rows = Array.from(tbody.rows);
rows.sort((a, b) => {
const first = getSortValue(a, columnIndex, sortType);
const second = getSortValue(b, columnIndex, sortType);
if (first < second) {
return direction === 'asc' ? -1 : 1;
}
if (first > second) {
return direction === 'asc' ? 1 : -1;
}
return 0;
});
rows.forEach((row) => tbody.appendChild(row));
table.dataset.sortColumn = String(columnIndex);
table.dataset.sortType = sortType;
table.dataset.sortDirection = direction;
updateSortIndicators(table, columnIndex, direction);
}
function applyActiveSort(table) {
if (!table || !table.dataset || !table.dataset.sortColumn) {
return;
}
sortEventTable(
table,
Number(table.dataset.sortColumn),
table.dataset.sortType || 'text',
table.dataset.sortDirection || 'asc'
);
}
function getTableRowOrder(table) {
if (!table || !table.tBodies.length) {
return [];
}
return Array.from(table.tBodies[0].rows)
.map((row) => String(row.dataset.chargeId || '').trim())
.filter(Boolean);
}
function buildPdfUrl(link) {
const baseHref = String(link.dataset.baseHref || link.getAttribute('href') || '');
const url = new URL(baseHref, window.location.origin);
const scope = String(link.dataset.printScope || 'single');
if (scope === 'all') {
document.querySelectorAll('.event-card').forEach((card) => {
const eventId = String(card.dataset.eventId || '').trim();
const table = card.querySelector('.event-charges-table');
const rowOrder = getTableRowOrder(table);
if (eventId && rowOrder.length) {
url.searchParams.set(`row_order[${eventId}]`, rowOrder.join(','));
}
});
return url.toString();
}
const eventId = String(link.dataset.eventId || '').trim();
const table = eventId ? document.getElementById(`eventTable_${eventId}`) : null;
const rowOrder = getTableRowOrder(table);
if (eventId && rowOrder.length) {
url.searchParams.set(`row_order[${eventId}]`, rowOrder.join(','));
}
return url.toString();
}
$('.sortable-header').on('click', function() {
const $button = $(this);
const table = $button.closest('table').get(0);
const columnIndex = Number($button.data('sortIndex'));
const sortType = String($button.data('sortType') || 'text');
const currentColumn = Number(table.dataset.sortColumn);
const currentDirection = table.dataset.sortDirection || 'asc';
const direction = currentColumn === columnIndex && currentDirection === 'asc' ? 'desc' : 'asc';
sortEventTable(table, columnIndex, sortType, direction);
});
$('.pdf-print-link').on('click', function() {
this.href = buildPdfUrl(this);
});
$('#externalParticipantSave').on('click', function() {
const firstName = capitalizeName($('#modalExternalFirstName').val().trim());
const lastName = capitalizeName($('#modalExternalLastName').val().trim());
const note = $('#modalExternalNote').val().trim();
if (!firstName && !lastName) {
alert('Please provide at least a first or last name for the non-school participant.');
return;
}
const parentFirst = capitalizeName($('#modalParentFirstName').val().trim());
const parentLast = capitalizeName($('#modalParentLastName').val().trim());
const parentPhone = $('#modalParentPhone').val().trim();
const parentEmail = $('#modalParentEmail').val().trim();
const eventId = $('#event_id').val();
if (!eventId) {
alert('Select an event before adding a non-school participant.');
return;
}
const explicitParentName = `${parentFirst} ${parentLast}`.trim();
if (!explicitParentName) {
alert('Please enter the external kid parent name.');
return;
}
if (!parentEmail) {
alert('Please enter the external kid parent email.');
return;
}
submitExternalParticipant({
firstname: firstName,
lastname: lastName,
note: note,
parentFirstname: parentFirst,
parentLastname: parentLast,
parentPhone: parentPhone,
parentEmail: parentEmail,
eventId: eventId
});
clearModalInputs();
});
}); });
</script> </script>
<?= $this->endSection() ?> <?= $this->endSection() ?>
@@ -0,0 +1,207 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event Participant Lists</title>
<style>
@page {
margin: 24px;
}
body {
font-family: DejaVu Sans, sans-serif;
font-size: 11px;
color: #1f2933;
}
h1 {
margin: 0 0 6px;
font-size: 20px;
}
.meta {
margin: 0 0 18px;
color: #52606d;
font-size: 10px;
}
.event-card {
margin-bottom: 22px;
page-break-inside: avoid;
}
.event-title {
margin: 0 0 8px;
padding: 8px 10px;
background: #f5f7fa;
border: 1px solid #d9e2ec;
font-size: 14px;
font-weight: 700;
}
table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}
th,
td {
border: 1px solid #d9e2ec;
padding: 6px 7px;
vertical-align: top;
word-wrap: break-word;
}
th {
background: #f5f7fa;
text-align: left;
font-weight: 700;
}
tfoot th {
background: #f5f7fa;
}
.small {
color: #52606d;
font-size: 10px;
}
.status-paid {
color: #166534;
font-weight: 700;
}
.status-unpaid {
color: #b42318;
font-weight: 700;
}
.status-neutral {
color: #52606d;
font-weight: 700;
}
</style>
</head>
<body>
<?php
$title = !empty($filterEventId) ? 'Event Participant List' : 'All Event Participant Lists';
if (!empty($filterParentId)) {
$title .= ' for Selected Parent';
}
?>
<h1><?= esc($title) ?></h1>
<p class="meta">
Generated on <?= esc($generatedAt) ?>
| School Year: <?= esc($school_year ?: 'N/A') ?>
| Semester: <?= esc($semester ?: 'N/A') ?>
</p>
<?php if (empty($groupedCharges)): ?>
<p>No charges found for the selected filters.</p>
<?php else: ?>
<?php foreach ($groupedCharges as $eventId => $data): ?>
<?php
$rows = $data['rows'] ?? [];
$totalParticipants = 0;
$totalCharged = 0.0;
?>
<section class="event-card">
<h2 class="event-title"><?= esc($data['label'] ?? 'N/A') ?></h2>
<table>
<thead>
<tr>
<th style="width: 4%;">ID</th>
<th style="width: 15%;">Parent Name</th>
<th style="width: 14%;">Student Name</th>
<th style="width: 15%;">External Info</th>
<th style="width: 11%;">Class Section</th>
<th style="width: 8%;">Charged Amount</th>
<th style="width: 10%;">Created</th>
<th style="width: 7%;">Waiver</th>
<th style="width: 7%;">Fees Paid</th>
<th style="width: 9%;">Payment</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $charge): ?>
<?php
$isParticipating = ($charge['participation'] ?? '') === 'yes';
$isEventPaid = !empty($charge['event_paid']);
$feeAmount = (float) ($charge['event_amount'] ?? 0);
$hasBalanceRecord = array_key_exists((int) ($charge['parent_id'] ?? 0), $parentBalances);
$parentBalance = $hasBalanceRecord ? (float) $parentBalances[(int) $charge['parent_id']] : null;
$waiverSigned = !empty($charge['waiver_signed']);
$feeIsPaid = $isParticipating && ($isEventPaid || ($hasBalanceRecord && $parentBalance <= 0));
$studentName = !empty($charge['student_firstname'])
? trim(($charge['student_firstname'] ?? '') . ' ' . ($charge['student_lastname'] ?? ''))
: '';
$externalName = trim(($charge['external_firstname'] ?? '') . ' ' . ($charge['external_lastname'] ?? ''));
$displayName = $studentName ?: ($externalName ?: '—');
$externalNote = trim((string) ($charge['external_note'] ?? ''));
$externalParentLabel = trim(($charge['external_parent_firstname'] ?? '') . ' ' . ($charge['external_parent_lastname'] ?? ''));
$externalParentPhone = trim((string) ($charge['external_parent_phone'] ?? ''));
$externalParentEmail = trim((string) ($charge['external_parent_email'] ?? ''));
$parentPhone = trim((string) ($charge['parent_cellphone'] ?? ''));
$standardParentName = trim(($charge['parent_firstname'] ?? '') . ' ' . ($charge['parent_lastname'] ?? ''));
$parentColumnName = $externalParentLabel ?: ($standardParentName ?: '—');
$isExternalParticipant = $externalName !== '';
$infoPhone = $isExternalParticipant ? $externalParentPhone : $parentPhone;
$infoEmail = $isExternalParticipant ? $externalParentEmail : '';
$classSectionName = $classSectionNames[$charge['class_section_id'] ?? ''] ?? '—';
if ($isParticipating) {
$totalParticipants++;
$totalCharged += $feeAmount;
}
?>
<tr>
<td><?= esc($charge['id'] ?? '') ?></td>
<td><?= esc($parentColumnName) ?></td>
<td>
<?= esc($displayName) ?>
<?php if ($externalNote !== ''): ?>
<div class="small"><?= esc($externalNote) ?></div>
<?php endif; ?>
</td>
<td>
<?php if ($infoPhone !== ''): ?>
<div class="small"><?= esc($infoPhone) ?></div>
<?php endif; ?>
<?php if ($infoEmail !== ''): ?>
<div class="small"><?= esc($infoEmail) ?></div>
<?php endif; ?>
<?php if ($infoPhone === '' && $infoEmail === ''): ?>
<span class="small">—</span>
<?php endif; ?>
</td>
<td><?= esc($classSectionName) ?></td>
<td>$<?= esc(number_format($feeAmount, 2)) ?></td>
<td><?= esc(!empty($charge['created_at']) ? local_datetime($charge['created_at'], 'm-d-Y H:i') : '') ?></td>
<td class="<?= $waiverSigned ? 'status-paid' : 'status-neutral' ?>">
<?= $waiverSigned ? 'Signed' : 'Unsigned' ?>
</td>
<td class="<?= $feeIsPaid ? 'status-paid' : 'status-unpaid' ?>">
<?= $feeIsPaid ? 'Paid' : 'Unpaid' ?>
</td>
<td class="<?= $isEventPaid ? 'status-paid' : 'status-unpaid' ?>">
<?= $isEventPaid ? 'Paid' : 'Unpaid' ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<th colspan="5">Totals</th>
<th>$<?= esc(number_format($totalCharged, 2)) ?></th>
<th colspan="4"><?= esc($totalParticipants) ?> participating</th>
</tr>
</tfoot>
</table>
</section>
<?php endforeach; ?>
<?php endif; ?>
</body>
</html>
@@ -12,6 +12,14 @@
<div class="alert alert-danger"><?= session()->getFlashdata('error') ?></div> <div class="alert alert-danger"><?= session()->getFlashdata('error') ?></div>
<?php endif; ?> <?php endif; ?>
<?php if (session()->getFlashdata('email_status')): ?>
<div class="alert alert-info"><?= session()->getFlashdata('email_status') ?></div>
<?php endif; ?>
<?php if (session()->getFlashdata('email_error')): ?>
<div class="alert alert-warning"><?= session()->getFlashdata('email_error') ?></div>
<?php endif; ?>
<?php if (empty($events)): ?> <?php if (empty($events)): ?>
<div class="alert alert-info mb-3 d-inline-block">No events found.</div> <div class="alert alert-info mb-3 d-inline-block">No events found.</div>
<?php else: ?> <?php else: ?>
+6 -3
View File
@@ -13,6 +13,9 @@ $schoolYear = $schoolYear ?? '';
$semester = $semester ?? ''; $semester = $semester ?? '';
$maxUploadBytes = $maxUploadBytes ?? (12 * 1024 * 1024); $maxUploadBytes = $maxUploadBytes ?? (12 * 1024 * 1024);
$allowedExtensions = $allowedExtensions ?? ['doc', 'docx', 'pdf']; $allowedExtensions = $allowedExtensions ?? ['doc', 'docx', 'pdf'];
$reviewActionUrl = $reviewActionUrl ?? base_url('administrator/exam-drafts/review');
$legacyUploadUrl = $legacyUploadUrl ?? base_url('administrator/exam-drafts/upload-legacy');
$reviewPortalLabel = $reviewPortalLabel ?? 'Administrator';
$renderBadge = static function (string $status, array $badges): string { $renderBadge = static function (string $status, array $badges): string {
$b = $badges[$status] ?? ['label' => $status, 'class' => 'bg-secondary text-white']; $b = $badges[$status] ?? ['label' => $status, 'class' => 'bg-secondary text-white'];
@@ -27,7 +30,7 @@ $fileAccept = implode(',', array_map(static fn ($x) => '.' . $x, $allowedExtensi
<div> <div>
<h1 class="h3 mb-1">Exam draft submissions</h1> <h1 class="h3 mb-1">Exam draft submissions</h1>
<p class="text-muted mb-0 small"> <p class="text-muted mb-0 small">
<?= esc($semester ?: 'Semester') ?> <?= esc($schoolYear ?: '') ?> <?= esc($reviewPortalLabel) ?> review portal · <?= esc($semester ?: 'Semester') ?> <?= esc($schoolYear ?: '') ?>
</p> </p>
</div> </div>
<div class="text-muted small d-flex flex-column align-items-lg-end"> <div class="text-muted small d-flex flex-column align-items-lg-end">
@@ -205,7 +208,7 @@ $fileAccept = implode(',', array_map(static fn ($x) => '.' . $x, $allowedExtensi
</div> </div>
</td> </td>
<td style="min-width: 280px;"> <td style="min-width: 280px;">
<?= form_open_multipart(base_url('administrator/exam-drafts/review'), ['class' => 'vstack gap-2', 'id' => $formId]) ?> <?= form_open_multipart($reviewActionUrl, ['class' => 'vstack gap-2', 'id' => $formId]) ?>
<?= csrf_field() ?> <?= csrf_field() ?>
<input type="hidden" name="draft_id" value="<?= (int) ($draft['id'] ?? 0) ?>"> <input type="hidden" name="draft_id" value="<?= (int) ($draft['id'] ?? 0) ?>">
<?php $selectedStatus = ''; ?> <?php $selectedStatus = ''; ?>
@@ -276,7 +279,7 @@ $fileAccept = implode(',', array_map(static fn ($x) => '.' . $x, $allowedExtensi
<span class="badge bg-primary-subtle text-primary">Admin only</span> <span class="badge bg-primary-subtle text-primary">Admin only</span>
</div> </div>
<div class="card-body"> <div class="card-body">
<?= form_open_multipart(base_url('administrator/exam-drafts/upload-legacy'), ['class' => 'row g-3']) ?> <?= form_open_multipart($legacyUploadUrl, ['class' => 'row g-3']) ?>
<?= csrf_field() ?> <?= csrf_field() ?>
<div class="col-md-4"> <div class="col-md-4">
<label class="form-label small">Class sections</label> <label class="form-label small">Class sections</label>
@@ -1,82 +0,0 @@
<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<div class="container-fluid">
<div class="wrapper">
<div class="content"></div>
<h2 class="text-center mt-4 mb-3">PayPal Transactions</h2>
<?= $this->include('partials/academic_filter') ?>
<!-- Export Button -->
<div class="d-flex gap-2 mb-3 justify-content-end">
<a href="<?= base_url('admin/paypal-transactions/export') . ($keyword ? '?q=' . urlencode($keyword) : '') ?>"
class="btn btn-success">
Export CSV
</a>
</div>
<!-- Search Form -->
<!--form method="get" action="<--?= base_url('admin/paypal-transactions') ?>" class="mb-3">
<--?= csrf_field(); ?>
<div class="input-group">
<input type="text" name="q" value="<--?= esc($keyword) ?>" class="form-control"
placeholder="Search by transaction ID, email, order ID, or event type">
<button type="submit" class="btn btn-primary">Search</button>
<--?php if ($keyword): ?>
<a href="<--?= base_url('admin/paypal-transactions') ?>" class="btn btn-secondary">Clear</a>
<--?php endif; ?>
</div>
</form-->
<!-- Transactions Table -->
<table id="myTable" class="display table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Transaction ID</th>
<th>Order ID</th>
<th>Parent School ID</th>
<th>Email</th>
<th>Amount</th>
<th>Net Amount</th>
<th>Currency</th>
<th>Status</th>
<th>Event Type</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php foreach ($transactions as $t): ?>
<tr>
<td><?= esc($t['id']) ?></td>
<td><?= esc($t['transaction_id']) ?></td>
<td><?= esc($t['order_id']) ?></td>
<td><?= esc($t['parent_school_id']) ?></td>
<td><?= esc($t['payer_email']) ?></td>
<td>$<?= esc(number_format($t['amount'], 2)) ?></td>
<td>$<?= esc(number_format($t['net_amount'], 2)) ?></td>
<td><?= esc($t['currency']) ?></td>
<td><?= esc($t['status']) ?></td>
<td><?= esc($t['event_type']) ?></td>
<td><?= esc(local_datetime($t['created_at'], 'm-d-Y H:i')) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<!-- Pagination -->
<div class="d-flex justify-content-center">
<?= $pager->links() ?>
</div>
</div>
</div>
<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
$('#myTable').DataTable({
"order": [
[0, "desc"]
],
"pageLength": 10
});
});
</script>
<?= $this->endSection() ?>
+389
View File
@@ -0,0 +1,389 @@
<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<?php
$classResults = $classResults ?? [];
$selectedYear = $selectedYear ?? '';
$selectedPercentile = $selectedPercentile ?? 75;
$years = $years ?? [];
$totalStudents = array_sum(array_column($classResults, 'student_count'));
$totalScored = array_sum(array_column($classResults, 'scored_count'));
$totalTrophies = array_sum(array_column($classResults, 'trophy_count'));
$totalBoys = array_sum(array_column($classResults, 'boys'));
$totalGirls = array_sum(array_column($classResults, 'girls'));
$totalTrophyBoys = array_sum(array_column($classResults, 'trophy_boys'));
$totalTrophyGirls = array_sum(array_column($classResults, 'trophy_girls'));
$pctBoys = $totalStudents > 0 ? round($totalBoys / $totalStudents * 100) : 0;
$pctGirls = $totalStudents > 0 ? round($totalGirls / $totalStudents * 100) : 0;
$pctTrophyBoys = $totalBoys > 0 ? round($totalTrophyBoys / $totalBoys * 100) : 0;
$pctTrophyGirls = $totalGirls > 0 ? round($totalTrophyGirls / $totalGirls * 100) : 0;
$pctTrophyAll = $totalStudents > 0 ? round($totalTrophies / $totalStudents * 100) : 0;
?>
<div class="container-fluid">
<!-- Header -->
<div class="d-flex flex-wrap align-items-center justify-content-between mb-3 gap-2">
<div>
<h2 class="mb-1"><i class="bi bi-trophy-fill text-warning me-2"></i>Trophy Projections</h2>
<p class="text-muted mb-0">
Fall scores are used to calculate a per-class threshold at the
<strong><?= (int) $selectedPercentile ?>th percentile</strong> and project which students are on track
for a year-end trophy. Minimum 3 trophies per class. Names are hidden by default.
</p>
</div>
<div class="d-flex gap-2">
<a href="<?= site_url('administrator/trophy/winners?' . http_build_query(['school_year' => $selectedYear, 'percentile' => $selectedPercentile])) ?>"
class="btn btn-warning btn-sm">
<i class="bi bi-eye-fill me-1"></i>Reveal Winners
</a>
<a href="<?= site_url('administrator/trophy/final?' . http_build_query(['school_year' => $selectedYear, 'percentile' => $selectedPercentile])) ?>"
class="btn btn-success btn-sm">
<i class="bi bi-bar-chart-steps me-1"></i>Final vs Predicted
</a>
</div>
</div>
<!-- Year filter -->
<form method="get" action="<?= site_url('administrator/trophy') ?>" class="row g-2 align-items-end mb-4">
<div class="col-auto">
<label class="form-label mb-1 small fw-semibold">School Year</label>
<select name="school_year" class="form-select form-select-sm" style="min-width:130px;">
<?php foreach ($years as $yr): ?>
<option value="<?= esc($yr) ?>" <?= $yr === $selectedYear ? 'selected' : '' ?>>
<?= esc($yr) ?>
</option>
<?php endforeach; ?>
<?php if (empty($years)): ?>
<option value="<?= esc($selectedYear) ?>" selected><?= esc($selectedYear) ?></option>
<?php endif; ?>
</select>
</div>
<div class="col-auto">
<label class="form-label mb-1 small fw-semibold">Percentile threshold</label>
<div class="input-group input-group-sm" style="width:130px;">
<input type="number" name="percentile" class="form-control"
min="1" max="99" step="1"
value="<?= (int) $selectedPercentile ?>"
title="Students scoring above this percentile receive a trophy (min 3 per class)">
<span class="input-group-text">%</span>
</div>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary btn-sm">Apply</button>
</div>
</form>
<?php if (empty($classResults)): ?>
<div class="alert alert-info">No class or fall-score data found for the selected school year.</div>
<?php else: ?>
<!-- ── Global stats ── -->
<div class="row g-3 mb-4">
<div class="col-6 col-sm-4 col-lg-2">
<div class="card text-center shadow-sm border-warning h-100">
<div class="card-body py-3">
<div class="fs-2 text-warning"><i class="bi bi-trophy-fill"></i></div>
<div class="fs-3 fw-bold"><?= $totalTrophies ?></div>
<div class="text-muted small">Trophies</div>
<span class="badge bg-warning text-dark mt-1"><?= $pctTrophyAll ?>% of students</span>
</div>
</div>
</div>
<div class="col-6 col-sm-4 col-lg-2">
<div class="card text-center shadow-sm h-100">
<div class="card-body py-3">
<div class="fs-2 text-primary"><i class="bi bi-people-fill"></i></div>
<div class="fs-3 fw-bold"><?= $totalStudents ?></div>
<div class="text-muted small">Students</div>
<span class="badge bg-secondary mt-1"><?= count($classResults) ?> classes</span>
</div>
</div>
</div>
<div class="col-6 col-sm-4 col-lg-2">
<div class="card text-center shadow-sm h-100">
<div class="card-body py-3">
<div class="fs-2 text-success"><i class="bi bi-bar-chart-fill"></i></div>
<div class="fs-3 fw-bold"><?= $totalScored ?></div>
<div class="text-muted small">With Fall Scores</div>
<span class="badge bg-success mt-1"><?= $totalStudents > 0 ? round($totalScored/$totalStudents*100) : 0 ?>%</span>
</div>
</div>
</div>
<div class="col-6 col-sm-4 col-lg-2">
<div class="card text-center shadow-sm h-100">
<div class="card-body py-3">
<div class="fs-2" style="color:#4A90E2"><i class="bi bi-gender-male"></i></div>
<div class="fs-3 fw-bold"><?= $totalBoys ?></div>
<div class="text-muted small">Boys</div>
<span class="badge text-white mt-1" style="background:#4A90E2"><?= $pctBoys ?>% of students</span>
</div>
</div>
</div>
<div class="col-6 col-sm-4 col-lg-2">
<div class="card text-center shadow-sm h-100">
<div class="card-body py-3">
<div class="fs-2" style="color:#E47AB0"><i class="bi bi-gender-female"></i></div>
<div class="fs-3 fw-bold"><?= $totalGirls ?></div>
<div class="text-muted small">Girls</div>
<span class="badge text-white mt-1" style="background:#E47AB0"><?= $pctGirls ?>% of students</span>
</div>
</div>
</div>
<div class="col-6 col-sm-4 col-lg-2">
<div class="card text-center shadow-sm h-100">
<div class="card-body py-3">
<div class="fs-2 text-warning"><i class="bi bi-award-fill"></i></div>
<div class="fs-3 fw-bold">
<span style="color:#4A90E2"><?= $totalTrophyBoys ?></span>
<span class="text-muted fs-5">/</span>
<span style="color:#E47AB0"><?= $totalTrophyGirls ?></span>
</div>
<div class="text-muted small">Trophy M / F</div>
<span class="small">
<span style="color:#4A90E2"><?= $pctTrophyBoys ?>%</span>
&nbsp;·&nbsp;
<span style="color:#E47AB0"><?= $pctTrophyGirls ?>%</span>
</span>
</div>
</div>
</div>
</div>
<!-- ── Per-class summary ── -->
<div class="card shadow-sm">
<div class="card-header bg-white fw-semibold py-2">Class Breakdown</div>
<div class="table-responsive">
<table class="table table-hover table-sm align-middle mb-0 no-mgmt-sticky" id="trophy-breakdown-table" data-no-mgmt-sticky>
<thead class="table-light">
<tr>
<th class="ps-3">Class</th>
<th class="text-center">Students</th>
<th class="text-center">Scored</th>
<th class="text-center">
<i class="bi bi-trophy-fill text-warning"></i> Trophies
</th>
<th class="text-center" style="color:#4A90E2">
<i class="bi bi-gender-male"></i> Boys
</th>
<th class="text-center" style="color:#E47AB0">
<i class="bi bi-gender-female"></i> Girls
</th>
<th class="text-center" style="color:#4A90E2">Trophy Boys</th>
<th class="text-center" style="color:#E47AB0">Trophy Girls</th>
<th class="text-center">Rate</th>
<th class="text-end">Threshold</th>
<th class="text-center">Custom Threshold</th>
</tr>
</thead>
<tbody>
<?php foreach ($classResults as $cls):
$scores = array_filter(
array_column($cls['students'], 'fall_score'),
fn($s) => $s !== null
);
$scoresJson = json_encode(array_values($scores));
$clsId = 'cls' . $cls['section_id'];
?>
<tr id="row-<?= $clsId ?>">
<td class="ps-3 fw-semibold"><?= esc($cls['section_name']) ?></td>
<td class="text-center"><?= $cls['student_count'] ?></td>
<td class="text-center">
<?php if ($cls['scored_count'] < 3): ?>
<span class="badge bg-danger" title="Fewer than 3 fall scores — minimum of 3 trophies cannot be enforced">
<?= $cls['scored_count'] ?> <i class="bi bi-exclamation-triangle-fill"></i>
</span>
<?php else: ?>
<?= $cls['scored_count'] ?>
<?php endif; ?>
</td>
<td class="text-center" id="trophy-cell-<?= $clsId ?>">
<span class="badge bg-warning text-dark">
<i class="bi bi-trophy-fill"></i>
<span id="trophy-count-<?= $clsId ?>"><?= $cls['trophy_count'] ?></span>
</span>
</td>
<td class="text-center">
<?= $cls['boys'] ?>
<span class="text-muted small">(<?= $cls['pct_boys'] ?>%)</span>
</td>
<td class="text-center">
<?= $cls['girls'] ?>
<span class="text-muted small">(<?= $cls['pct_girls'] ?>%)</span>
</td>
<td class="text-center" id="trophy-boys-<?= $clsId ?>"><?= $cls['trophy_boys'] ?><?php if ($cls['boys'] > 0): ?> <span class="text-muted small">(<?= $cls['pct_trophy_boys'] ?>%)</span><?php endif; ?></td>
<td class="text-center" id="trophy-girls-<?= $clsId ?>"><?= $cls['trophy_girls'] ?><?php if ($cls['girls'] > 0): ?> <span class="text-muted small">(<?= $cls['pct_trophy_girls'] ?>%)</span><?php endif; ?></td>
<td class="text-center">
<div class="progress" style="height:8px;min-width:60px;">
<div class="progress-bar bg-warning" id="rate-bar-<?= $clsId ?>" style="width:<?= $cls['pct_trophy_total'] ?>%;"></div>
</div>
<span class="small text-muted" id="rate-txt-<?= $clsId ?>"><?= $cls['pct_trophy_total'] ?>%</span>
</td>
<td class="text-end text-muted small" id="auto-threshold-<?= $clsId ?>">
<?= $cls['threshold'] !== null ? number_format((float)$cls['threshold'], 1) : '—' ?>
</td>
<td>
<div class="input-group input-group-sm" style="min-width:150px;">
<input type="number" id="custom-threshold-<?= $clsId ?>"
class="form-control form-control-sm"
step="0.1" min="0"
placeholder="e.g. <?= $cls['threshold'] !== null ? number_format((float)$cls['threshold'], 1) : '80.0' ?>"
data-scores='<?= $scoresJson ?>'
data-clsid="<?= $clsId ?>"
data-boys='<?= json_encode(array_values(array_filter(array_map(fn($s) => $s['gender'] === 'Male' ? $s['fall_score'] : null, $cls['students']), fn($s) => $s !== null))) ?>'
data-girls='<?= json_encode(array_values(array_filter(array_map(fn($s) => $s['gender'] === 'Female' ? $s['fall_score'] : null, $cls['students']), fn($s) => $s !== null))) ?>'
data-total="<?= $cls['student_count'] ?>"
data-nboys="<?= $cls['boys'] ?>"
data-ngirls="<?= $cls['girls'] ?>">
<button class="btn btn-outline-primary btn-sm" type="button"
onclick="applyCustomThreshold('<?= $clsId ?>')">
Apply
</button>
</div>
<div id="custom-note-<?= $clsId ?>" class="text-muted" style="font-size:.7rem;"></div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot class="table-light fw-semibold">
<tr>
<td class="ps-3">Total</td>
<td class="text-center"><?= $totalStudents ?></td>
<td class="text-center"><?= $totalScored ?></td>
<td class="text-center">
<span class="badge bg-warning text-dark">
<i class="bi bi-trophy-fill"></i> <?= $totalTrophies ?>
</span>
</td>
<td class="text-center">
<?= $totalBoys ?>
<span class="text-muted small fw-normal">(<?= $pctBoys ?>%)</span>
</td>
<td class="text-center">
<?= $totalGirls ?>
<span class="text-muted small fw-normal">(<?= $pctGirls ?>%)</span>
</td>
<td class="text-center">
<?= $totalTrophyBoys ?>
<span class="text-muted small fw-normal">(<?= $pctTrophyBoys ?>%)</span>
</td>
<td class="text-center">
<?= $totalTrophyGirls ?>
<span class="text-muted small fw-normal">(<?= $pctTrophyGirls ?>%)</span>
</td>
<td class="text-center">
<div class="progress" style="height:8px;min-width:60px;">
<div class="progress-bar bg-warning" style="width:<?= $pctTrophyAll ?>%;"></div>
</div>
<span class="small text-muted"><?= $pctTrophyAll ?>%</span>
</td>
<td></td>
<td class="pe-3"></td>
</tr>
</tfoot>
</table>
</div>
</div>
<?php endif; ?>
</div>
<script>
var TROPHY_NS = 'trophy_custom_<?= esc($selectedYear) ?>_<?= (int)$selectedPercentile ?>';
function countAtOrAbove(arr, t) {
return arr.filter(function(s) { return s >= t; }).length;
}
function applyThreshold(clsId, val) {
var input = document.getElementById('custom-threshold-' + clsId);
var note = document.getElementById('custom-note-' + clsId);
var scores = JSON.parse(input.dataset.scores);
var boys = JSON.parse(input.dataset.boys);
var girls = JSON.parse(input.dataset.girls);
var nTotal = parseInt(input.dataset.total);
var nBoys = parseInt(input.dataset.nboys);
var nGirls = parseInt(input.dataset.ngirls);
var MIN = 3;
var winners = countAtOrAbove(scores, val);
var usedThreshold = val;
var forced = false;
if (winners < MIN && scores.length >= MIN) {
var desc = scores.slice().sort(function(a, b) { return b - a; });
usedThreshold = desc[MIN - 1];
winners = countAtOrAbove(scores, usedThreshold);
forced = true;
} else if (winners < MIN) {
winners = scores.length;
usedThreshold = scores.length > 0 ? Math.min.apply(null, scores) : val;
forced = true;
}
var trophyBoys = countAtOrAbove(boys, usedThreshold);
var trophyGirls = countAtOrAbove(girls, usedThreshold);
var rate = nTotal > 0 ? Math.round(winners / nTotal * 100) : 0;
var pctTB = nBoys > 0 ? Math.round(trophyBoys / nBoys * 100) : 0;
var pctTG = nGirls > 0 ? Math.round(trophyGirls / nGirls * 100) : 0;
document.getElementById('trophy-count-' + clsId).textContent = winners;
document.getElementById('trophy-boys-' + clsId).textContent = trophyBoys + (nBoys > 0 ? ' (' + pctTB + '%)' : '');
document.getElementById('trophy-girls-' + clsId).textContent = trophyGirls + (nGirls > 0 ? ' (' + pctTG + '%)' : '');
document.getElementById('rate-bar-' + clsId).style.width = rate + '%';
document.getElementById('rate-txt-' + clsId).textContent = rate + '%';
document.getElementById('auto-threshold-' + clsId).textContent = usedThreshold.toFixed(1);
if (forced) {
note.style.color = '#dc3545';
note.textContent = 'Min 3 enforced → threshold lowered to ' + usedThreshold.toFixed(1);
} else {
note.style.color = '#6c757d';
note.textContent = 'Custom threshold: ' + usedThreshold.toFixed(1);
}
var badge = document.getElementById('trophy-cell-' + clsId).querySelector('.badge');
badge.classList.remove('bg-warning');
badge.classList.add('bg-primary');
}
function applyCustomThreshold(clsId) {
var input = document.getElementById('custom-threshold-' + clsId);
var val = parseFloat(input.value);
if (isNaN(val)) {
document.getElementById('custom-note-' + clsId).textContent = 'Enter a valid number.';
return;
}
applyThreshold(clsId, val);
// Persist so the value survives filter changes within the same percentile/year
try {
var saved = JSON.parse(localStorage.getItem(TROPHY_NS) || '{}');
saved[clsId] = val;
localStorage.setItem(TROPHY_NS, JSON.stringify(saved));
} catch (e) {}
}
// Restore saved custom thresholds on page load
document.addEventListener('DOMContentLoaded', function () {
try {
var saved = JSON.parse(localStorage.getItem(TROPHY_NS) || '{}');
Object.keys(saved).forEach(function (clsId) {
var input = document.getElementById('custom-threshold-' + clsId);
if (!input) return;
input.value = saved[clsId];
applyThreshold(clsId, saved[clsId]);
});
} catch (e) {}
});
// Clear all custom thresholds when the percentile/year form is submitted
document.querySelector('form[action*="trophy"]').addEventListener('submit', function () {
try { localStorage.removeItem(TROPHY_NS); } catch (e) {}
});
</script>
<?= $this->endSection() ?>
File diff suppressed because it is too large Load Diff
+480
View File
@@ -0,0 +1,480 @@
<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<?php
$classResults = $classResults ?? [];
$selectedYear = $selectedYear ?? '';
$selectedPercentile = $selectedPercentile ?? 75;
$years = $years ?? [];
$totalWinners = array_sum(array_map(fn($c) => count($c['winners']), $classResults));
$totalStudents = array_sum(array_column($classResults, 'student_count'));
$totalBoys = array_sum(array_column($classResults, 'boys'));
$totalGirls = array_sum(array_column($classResults, 'girls'));
$totalTrophyBoys = array_sum(array_column($classResults, 'trophy_boys'));
$totalTrophyGirls = array_sum(array_column($classResults, 'trophy_girls'));
$pctWinners = $totalStudents > 0 ? round($totalWinners / $totalStudents * 100) : 0;
$pctTrophyBoys = $totalBoys > 0 ? round($totalTrophyBoys / $totalBoys * 100) : 0;
$pctTrophyGirls = $totalGirls > 0 ? round($totalTrophyGirls / $totalGirls * 100) : 0;
$pctBoys = $totalStudents > 0 ? round($totalBoys / $totalStudents * 100) : 0;
$pctGirls = $totalStudents > 0 ? round($totalGirls / $totalStudents * 100) : 0;
?>
<style>
/* ── Screen: hide print-only blocks ── */
.print-only { display: none !important; }
/* ── Print ── */
@media print {
.no-print { display: none !important; }
.print-only { display: block !important; }
.screen-only { display: none !important; }
body { font-size: 11px; }
.container-fluid { padding: 0 !important; }
h2, h3 { font-size: 14px; margin-bottom: .4rem; }
.print-page-break { break-before: page; }
table { width: 100%; border-collapse: collapse; font-size: 10px; }
table th,
table td { border: 1px solid #bbb; padding: 3px 6px; }
table thead { background: #333 !important; color: #fff !important;
-webkit-print-color-adjust: exact; print-color-adjust: exact; }
table thead th { position: static !important; top: auto !important; box-shadow: none !important; }
table tfoot { background: #eee !important;
-webkit-print-color-adjust: exact; print-color-adjust: exact; }
.badge-m { color: #4A90E2; font-weight: bold; }
.badge-f { color: #E47AB0; font-weight: bold; }
}
</style>
<div class="container-fluid">
<!-- ══ SCREEN HEADER ══════════════════════════════════════════════════════ -->
<div class="d-flex flex-wrap align-items-center justify-content-between mb-3 gap-2 no-print">
<div>
<h2 class="mb-1"><i class="bi bi-trophy-fill text-warning me-2"></i>Trophy Winners</h2>
<p class="text-muted mb-0">
<?= esc($selectedYear) ?> &mdash; <?= (int)$selectedPercentile ?>th percentile &mdash;
<strong><?= $totalWinners ?></strong> winners across <strong><?= count($classResults) ?></strong> classes
</p>
</div>
<div class="d-flex gap-2">
<button onclick="window.print()" class="btn btn-primary btn-sm">
<i class="bi bi-printer-fill me-1"></i>Print
</button>
<a href="<?= site_url('administrator/trophy?' . http_build_query(['school_year' => $selectedYear, 'percentile' => $selectedPercentile])) ?>"
class="btn btn-outline-secondary btn-sm">
<i class="bi bi-arrow-left me-1"></i>Back
</a>
</div>
</div>
<!-- Filter (screen only) -->
<form method="get" action="<?= site_url('administrator/trophy/winners') ?>"
class="row g-2 align-items-end mb-4 no-print">
<div class="col-auto">
<label class="form-label mb-1 small fw-semibold">School Year</label>
<select name="school_year" class="form-select form-select-sm" style="min-width:130px;">
<?php foreach ($years as $yr): ?>
<option value="<?= esc($yr) ?>" <?= $yr === $selectedYear ? 'selected' : '' ?>><?= esc($yr) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="col-auto">
<label class="form-label mb-1 small fw-semibold">Percentile</label>
<div class="input-group input-group-sm" style="width:110px;">
<input type="number" name="percentile" class="form-control"
min="1" max="99" step="1" value="<?= (int)$selectedPercentile ?>">
<span class="input-group-text">%</span>
</div>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary btn-sm">Apply</button>
</div>
</form>
<?php if (empty($classResults)): ?>
<div class="alert alert-info no-print">No projected trophy winners found.</div>
<?php else: ?>
<!-- ══ PRINT VIEW ════════════════════════════════════════════════════════ -->
<div class="print-only">
<!-- Print title -->
<div style="text-align:center;margin-bottom:12px;border-bottom:2px solid #333;padding-bottom:8px;">
<h2 style="margin:0;">Trophy Winners — <?= esc($selectedYear) ?></h2>
<p style="margin:4px 0 0;font-size:10px;color:#555;">
<?= (int)$selectedPercentile ?>th percentile &mdash;
<?= $totalWinners ?> winners / <?= $totalStudents ?> students &mdash;
<?= count($classResults) ?> classes
</p>
</div>
<!-- TABLE 1: All winners -->
<h3 style="margin-bottom:4px;">Winners</h3>
<table data-no-mgmt-sticky>
<thead>
<tr>
<th>#</th>
<th>Class</th>
<th>Name</th>
<th style="text-align:center;">Gender</th>
<th style="text-align:right;">Fall Score</th>
<th style="text-align:right;">Spring Score</th>
<th style="text-align:right;">Year Score</th>
</tr>
</thead>
<tbody>
<?php
$globalRank = 0;
foreach ($classResults as $cls):
foreach ($cls['winners'] as $student):
$globalRank++;
$isMale = strtolower($student['gender'] ?? '') === 'male';
?>
<tr>
<td style="text-align:center;"><?= $globalRank ?></td>
<td><?= esc($cls['section_name']) ?></td>
<td><strong><?= esc($student['name']) ?></strong></td>
<td style="text-align:center;">
<span class="<?= $isMale ? 'badge-m' : 'badge-f' ?>">
<?= $isMale ? 'M' : 'F' ?>
</span>
</td>
<td style="text-align:right;font-weight:bold;">
<?= $student['fall_score'] !== null ? number_format($student['fall_score'], 1) : '—' ?>
</td>
<td style="text-align:right;">
<?= $student['spring_score'] !== null ? number_format($student['spring_score'], 1) : '—' ?>
</td>
<td style="text-align:right;font-weight:bold;color:#155724;">
<?= $student['year_score'] !== null ? number_format($student['year_score'], 1) : '—' ?>
</td>
</tr>
<?php endforeach; endforeach; ?>
</tbody>
<tfoot>
<tr>
<td colspan="2" style="font-weight:bold;">Total</td>
<td colspan="2" style="font-weight:bold;"><?= $totalWinners ?> winners</td>
<td colspan="3" style="text-align:right;font-weight:bold;"><?= $pctWinners ?>% of students</td>
</tr>
</tfoot>
</table>
<!-- TABLE 2: Year summary (new page) -->
<div class="print-page-break"></div>
<h3 style="margin-bottom:4px;">Year Summary — <?= esc($selectedYear) ?></h3>
<table style="margin-bottom:16px;" data-no-mgmt-sticky>
<thead>
<tr>
<th>Class</th>
<th style="text-align:center;">Students</th>
<th style="text-align:center;">Boys</th>
<th style="text-align:center;">Girls</th>
<th style="text-align:center;">Winners</th>
<th style="text-align:center;">Trophy Boys</th>
<th style="text-align:center;">Trophy Girls</th>
<th style="text-align:center;">Rate</th>
<th style="text-align:right;">Fall Threshold</th>
</tr>
</thead>
<tbody>
<?php foreach ($classResults as $cls): ?>
<tr>
<td><?= esc($cls['section_name']) ?></td>
<td style="text-align:center;"><?= $cls['student_count'] ?></td>
<td style="text-align:center;"><?= $cls['boys'] ?> (<?= $cls['pct_boys'] ?>%)</td>
<td style="text-align:center;"><?= $cls['girls'] ?> (<?= $cls['pct_girls'] ?>%)</td>
<td style="text-align:center;font-weight:bold;"><?= count($cls['winners']) ?></td>
<td style="text-align:center;">
<span class="badge-m"><?= $cls['trophy_boys'] ?></span>
<?= $cls['boys'] > 0 ? '(' . $cls['pct_trophy_boys'] . '%)' : '' ?>
</td>
<td style="text-align:center;">
<span class="badge-f"><?= $cls['trophy_girls'] ?></span>
<?= $cls['girls'] > 0 ? '(' . $cls['pct_trophy_girls'] . '%)' : '' ?>
</td>
<td style="text-align:center;"><?= $cls['pct_trophy_total'] ?>%</td>
<td style="text-align:right;"><?= $cls['threshold'] !== null ? number_format((float)$cls['threshold'], 1) : '—' ?></td>
</tr>
<?php endforeach; ?>
</tbody>
<tfoot>
<tr>
<td style="font-weight:bold;">Total</td>
<td style="text-align:center;font-weight:bold;"><?= $totalStudents ?></td>
<td style="text-align:center;font-weight:bold;"><?= $totalBoys ?> (<?= $pctBoys ?>%)</td>
<td style="text-align:center;font-weight:bold;"><?= $totalGirls ?> (<?= $pctGirls ?>%)</td>
<td style="text-align:center;font-weight:bold;"><?= $totalWinners ?></td>
<td style="text-align:center;font-weight:bold;">
<span class="badge-m"><?= $totalTrophyBoys ?></span> (<?= $pctTrophyBoys ?>%)
</td>
<td style="text-align:center;font-weight:bold;">
<span class="badge-f"><?= $totalTrophyGirls ?></span> (<?= $pctTrophyGirls ?>%)
</td>
<td style="text-align:center;font-weight:bold;"><?= $pctWinners ?>%</td>
<td></td>
</tr>
</tfoot>
</table>
</div><!-- /print-only -->
<!-- ══ SCREEN VIEW ═══════════════════════════════════════════════════════ -->
<div class="screen-only">
<!-- Per-class cards -->
<?php foreach ($classResults as $cls):
$nW = count($cls['winners']);
?>
<div class="card shadow-sm mb-4">
<div class="card-header d-flex flex-wrap align-items-center justify-content-between gap-2 py-2"
style="background:#fff8e1;">
<div class="d-flex align-items-center gap-2">
<span class="fw-bold fs-6"><?= esc($cls['section_name']) ?></span>
<span class="badge bg-warning text-dark">
<i class="bi bi-trophy-fill"></i> <?= $nW ?> winner<?= $nW !== 1 ? 's' : '' ?>
</span>
<?php if ($cls['threshold'] !== null): ?>
<span class="text-muted small">Fall &#8805; <?= number_format((float)$cls['threshold'], 1) ?></span>
<?php endif; ?>
</div>
<div class="d-flex gap-3 small">
<span>
<i class="bi bi-gender-male" style="color:#4A90E2"></i>
<strong style="color:#4A90E2"><?= $cls['trophy_boys'] ?></strong>/<?= $cls['boys'] ?> boys
<?php if ($cls['boys'] > 0): ?><span class="text-muted">(<?= $cls['pct_trophy_boys'] ?>%)</span><?php endif; ?>
</span>
<span>
<i class="bi bi-gender-female" style="color:#E47AB0"></i>
<strong style="color:#E47AB0"><?= $cls['trophy_girls'] ?></strong>/<?= $cls['girls'] ?> girls
<?php if ($cls['girls'] > 0): ?><span class="text-muted">(<?= $cls['pct_trophy_girls'] ?>%)</span><?php endif; ?>
</span>
<span class="text-muted"><?= $nW ?>/<?= $cls['student_count'] ?> (<?= $cls['pct_trophy_total'] ?>%)</span>
</div>
</div>
<div class="card-body p-0">
<table class="table table-sm table-hover mb-0 align-middle" data-no-mgmt-sticky>
<thead class="table-light">
<tr>
<th class="ps-3" style="width:2.2rem;">#</th>
<th>Name</th>
<th class="text-center" style="width:3rem;">Gender</th>
<th class="text-end">Fall Score</th>
<th class="text-end">Spring Score</th>
<th class="text-end pe-3">Year Score</th>
</tr>
</thead>
<tbody>
<?php foreach ($cls['winners'] as $i => $student):
$isMale = strtolower($student['gender'] ?? '') === 'male';
?>
<tr>
<td class="ps-3 text-muted small"><?= $i + 1 ?></td>
<td class="fw-semibold small"><?= esc($student['name']) ?></td>
<td class="text-center">
<span class="badge" style="background:<?= $isMale ? '#4A90E2' : '#E47AB0' ?>;font-size:.65rem;">
<?= $isMale ? 'M' : 'F' ?>
</span>
</td>
<td class="text-end small fw-semibold">
<?= $student['fall_score'] !== null ? number_format($student['fall_score'], 1) : '<span class="text-muted">—</span>' ?>
</td>
<td class="text-end small">
<?= $student['spring_score'] !== null
? '<span class="fw-semibold">' . number_format($student['spring_score'], 1) . '</span>'
: '<span class="text-muted">—</span>' ?>
</td>
<td class="text-end pe-3 small fw-semibold" style="color:#155724;">
<?= $student['year_score'] !== null ? number_format($student['year_score'], 1) : '<span class="text-muted">—</span>' ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<?php endforeach; ?>
<!-- Overall year stats -->
<div class="card shadow-sm mt-2">
<div class="card-header bg-dark text-white fw-semibold py-2">
<i class="bi bi-bar-chart-fill me-2"></i>Overall Year Summary — <?= esc($selectedYear) ?>
</div>
<div class="card-body">
<div class="row g-3 mb-3">
<?php foreach ([
[$totalWinners, 'Total Winners', 'warning', 'text-dark', $pctWinners . '% of students', null],
[$totalStudents, 'Total Students', 'secondary', 'text-white', count($classResults) . ' classes', null],
[$totalBoys, 'Total Boys', null, null, $pctBoys . '%', '#4A90E2'],
[$totalGirls, 'Total Girls', null, null, $pctGirls . '%', '#E47AB0'],
[$totalTrophyBoys, 'Trophy Boys', null, null, $pctTrophyBoys . '% of boys', '#4A90E2'],
[$totalTrophyGirls, 'Trophy Girls', null, null, $pctTrophyGirls . '% of girls', '#E47AB0'],
] as [$val, $label, $bg, $tc, $sub, $color]): ?>
<div class="col-6 col-sm-4 col-lg-2">
<div class="border rounded text-center p-3 h-100">
<div class="fs-3 fw-bold" <?= isset($color) ? 'style="color:' . $color . '"' : ($bg ? 'class="text-' . $bg . '"' : '') ?>>
<?= $val ?>
</div>
<div class="small text-muted"><?= $label ?></div>
<div class="badge mt-1 <?= $bg ? 'bg-' . $bg . ' ' . $tc : 'text-white' ?>"
<?= isset($color) && !$bg ? 'style="background:' . $color . '"' : '' ?>>
<?= $sub ?>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="row g-4 mt-1">
<!-- Stacked bar: trophies per class (boys + girls) -->
<div class="col-12 col-lg-7">
<div class="border rounded p-3 h-100">
<div class="small fw-semibold text-muted mb-2">
<i class="bi bi-trophy-fill text-warning me-1"></i>Trophy Winners per Class
</div>
<canvas id="chart-per-class" style="max-height:260px;"></canvas>
</div>
</div>
<!-- Doughnut: trophy gender split + rate per class -->
<div class="col-12 col-lg-5">
<div class="row g-3 h-100">
<div class="col-12">
<div class="border rounded p-3">
<div class="small fw-semibold text-muted mb-2">
<i class="bi bi-gender-ambiguous me-1"></i>Winners by Gender
</div>
<canvas id="chart-gender" style="max-height:160px;"></canvas>
</div>
</div>
<div class="col-12">
<div class="border rounded p-3">
<div class="small fw-semibold text-muted mb-2">
<i class="bi bi-bar-chart-fill me-1"></i>Trophy Rate per Class (%)
</div>
<canvas id="chart-rate" style="max-height:130px;"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div><!-- /screen-only -->
<?php endif; ?>
</div>
<?= $this->section('scripts') ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<script>
(function () {
<?php
$chartLabels = [];
$chartBoys = [];
$chartGirls = [];
$chartRates = [];
foreach ($classResults as $cls) {
$chartLabels[] = $cls['section_name'];
$chartBoys[] = $cls['trophy_boys'];
$chartGirls[] = $cls['trophy_girls'];
$chartRates[] = $cls['pct_trophy_total'];
}
?>
var labels = <?= json_encode($chartLabels) ?>;
var boys = <?= json_encode($chartBoys) ?>;
var girls = <?= json_encode($chartGirls) ?>;
var rates = <?= json_encode($chartRates) ?>;
var BOY_COLOR = '#4A90E2';
var GIRL_COLOR = '#E47AB0';
var RATE_COLOR = '#f0a500';
/* ── Chart 1: stacked horizontal bar per class ── */
new Chart(document.getElementById('chart-per-class'), {
type: 'bar',
data: {
labels: labels,
datasets: [
{ label: 'Boys', data: boys, backgroundColor: BOY_COLOR, stack: 'winners' },
{ label: 'Girls', data: girls, backgroundColor: GIRL_COLOR, stack: 'winners' }
]
},
options: {
indexAxis: 'y',
responsive: true,
maintainAspectRatio: true,
plugins: { legend: { position: 'bottom' } },
scales: {
x: { stacked: true, ticks: { stepSize: 1 }, grid: { color: '#f0f0f0' } },
y: { stacked: true }
}
}
});
/* ── Chart 2: doughnut gender split ── */
new Chart(document.getElementById('chart-gender'), {
type: 'doughnut',
data: {
labels: ['Trophy Boys', 'Trophy Girls'],
datasets: [{
data: [<?= $totalTrophyBoys ?>, <?= $totalTrophyGirls ?>],
backgroundColor: [BOY_COLOR, GIRL_COLOR],
borderWidth: 2
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
legend: { position: 'bottom' },
tooltip: {
callbacks: {
label: function(ctx) {
var total = ctx.dataset.data.reduce(function(a,b){ return a+b; }, 0);
var pct = total > 0 ? Math.round(ctx.parsed / total * 100) : 0;
return ctx.label + ': ' + ctx.parsed + ' (' + pct + '%)';
}
}
}
}
}
});
/* ── Chart 3: bar chart rate per class ── */
new Chart(document.getElementById('chart-rate'), {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Trophy Rate %',
data: rates,
backgroundColor: rates.map(function(r) {
return r > 30 ? '#dc3545' : r > 20 ? RATE_COLOR : '#28a745';
}),
borderRadius: 3
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: { legend: { display: false } },
scales: {
y: {
beginAtZero: true, max: 100,
ticks: { callback: function(v) { return v + '%'; } },
grid: { color: '#f0f0f0' }
}
}
}
});
})();
</script>
<?= $this->endSection() ?>
<?= $this->endSection() ?>
@@ -0,0 +1,265 @@
<?= $this->extend('layout/management_layout') ?>
<?= $this->section('content') ?>
<?php
$filters = $filters ?? [];
$result = $result ?? null;
$summary = $result['summary'] ?? [];
$mode = $filters['calculator_mode'] ?? 'compare';
$fmtMoney = static fn($value): string => '$' . number_format((float) $value, 2);
$warningText = static function (array $warnings): string {
$warnings = array_values(array_filter(array_map('trim', $warnings), 'strlen'));
return $warnings === [] ? 'None' : implode(' | ', $warnings);
};
?>
<div class="container-fluid mt-4">
<div class="d-flex flex-wrap justify-content-between align-items-end gap-3 mb-4">
<div>
<h2 class="mt-4 mb-1">Tuition Collection Forecast</h2>
<p class="text-muted mb-0">Uses actual enrollment families from the selected school year to compare old and new projected tuition income.</p>
</div>
<?php if ($result): ?>
<?php
$exportQuery = http_build_query([
'school_year' => $result['school_year'] ?? '',
'semester' => $result['semester'] ?? '',
'calculator_mode' => $result['calculator_mode'] ?? 'compare',
'include_withdrawn_mode' => $filters['include_withdrawn_mode'] ?? 'refund_deadline',
'include_payment_pending' => !empty($filters['include_payment_pending']) ? '1' : '0',
'include_event_only' => !empty($filters['include_event_only']) ? '1' : '0',
'include_paid_invoices' => !empty($filters['include_paid_invoices']) ? '1' : '0',
'unit_price' => $filters['unit_price'] ?? '',
'youth_unit_price' => $filters['youth_unit_price'] ?? '',
]);
?>
<a href="<?= site_url('administrator/tuition-forecast/export?' . $exportQuery) ?>" class="btn btn-success">
Export CSV
</a>
<?php endif; ?>
</div>
<div class="card shadow-sm mb-4">
<div class="card-body">
<form method="get" action="<?= site_url('administrator/tuition-forecast') ?>" class="row g-3 align-items-end">
<div class="col-md-3">
<label for="school_year" class="form-label">School Year</label>
<select id="school_year" name="school_year" class="form-select">
<?php foreach (($schoolYears ?? []) as $schoolYear): ?>
<option value="<?= esc($schoolYear) ?>" <?= ($filters['school_year'] ?? '') === $schoolYear ? 'selected' : '' ?>>
<?= esc($schoolYear) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-2">
<label for="semester" class="form-label">Semester Filter</label>
<select id="semester" name="semester" class="form-select">
<option value="" <?= ($filters['semester'] ?? '') === '' ? 'selected' : '' ?>>All Year</option>
<?php foreach (($semesters ?? []) as $semester): ?>
<option value="<?= esc($semester) ?>" <?= ($filters['semester'] ?? '') === $semester ? 'selected' : '' ?>>
<?= esc($semester) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-2">
<label for="calculator_mode" class="form-label">Calculator Mode</label>
<select id="calculator_mode" name="calculator_mode" class="form-select">
<option value="compare" <?= $mode === 'compare' ? 'selected' : '' ?>>Compare Both</option>
<option value="old" <?= $mode === 'old' ? 'selected' : '' ?>>Old Only</option>
<option value="new" <?= $mode === 'new' ? 'selected' : '' ?>>New Only</option>
</select>
</div>
<div class="col-md-2">
<label for="include_withdrawn_mode" class="form-label">Withdrawn Students</label>
<select id="include_withdrawn_mode" name="include_withdrawn_mode" class="form-select">
<option value="refund_deadline" <?= ($filters['include_withdrawn_mode'] ?? 'refund_deadline') === 'refund_deadline' ? 'selected' : '' ?>>Use Refund Deadline Rule</option>
<option value="include" <?= ($filters['include_withdrawn_mode'] ?? '') === 'include' ? 'selected' : '' ?>>Always Include</option>
<option value="exclude" <?= ($filters['include_withdrawn_mode'] ?? '') === 'exclude' ? 'selected' : '' ?>>Always Exclude</option>
</select>
</div>
<div class="col-md-3">
<label for="unit_price" class="form-label">Grades Unit Price</label>
<input
type="number"
min="0"
step="0.01"
id="unit_price"
name="unit_price"
class="form-control"
value="<?= esc((string) ($filters['unit_price'] ?? ($summary['unit_price'] ?? ''))) ?>"
placeholder="New tuition unit price for grades">
</div>
<div class="col-md-3">
<label for="youth_unit_price" class="form-label">Youth Unit Price</label>
<input
type="number"
min="0"
step="0.01"
id="youth_unit_price"
name="youth_unit_price"
class="form-control"
value="<?= esc((string) ($filters['youth_unit_price'] ?? ($summary['youth_unit_price'] ?? ''))) ?>"
placeholder="New tuition unit price for youth">
</div>
<div class="col-md-2">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="include_payment_pending" name="include_payment_pending" value="1" <?= !empty($filters['include_payment_pending']) ? 'checked' : '' ?>>
<label class="form-check-label" for="include_payment_pending">Include payment-pending students</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="include_event_only" name="include_event_only" value="1" <?= !empty($filters['include_event_only']) ? 'checked' : '' ?>>
<label class="form-check-label" for="include_event_only">Show event-only students in warnings</label>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Run Forecast</button>
</div>
</form>
</div>
</div>
<?php if ($result): ?>
<div class="row g-3 mb-4">
<div class="col-xl col-lg-3 col-md-4">
<div class="card border-0 shadow-sm h-100">
<div class="card-body">
<div class="text-muted small">Total Parents</div>
<div class="fs-4 fw-semibold"><?= esc((string) ($summary['family_count'] ?? 0)) ?></div>
</div>
</div>
</div>
<div class="col-xl col-lg-3 col-md-4">
<div class="card border-0 shadow-sm h-100">
<div class="card-body">
<div class="text-muted small">Total Students</div>
<div class="fs-4 fw-semibold"><?= esc((string) ($summary['student_count'] ?? 0)) ?></div>
<div class="small text-muted">Billable: <?= esc((string) ($summary['billable_student_count'] ?? 0)) ?></div>
</div>
</div>
</div>
<div class="col-xl col-lg-3 col-md-4">
<div class="card border-0 shadow-sm h-100">
<div class="card-body">
<div class="text-muted small">Old Projected Income</div>
<div class="fs-5 fw-semibold"><?= esc($fmtMoney($summary['old_projected_income'] ?? ($summary['old_projected_tuition'] ?? 0))) ?></div>
</div>
</div>
</div>
<div class="col-xl col-lg-3 col-md-4">
<div class="card border-0 shadow-sm h-100">
<div class="card-body">
<div class="text-muted small">New Projected Income</div>
<div class="fs-5 fw-semibold"><?= esc($fmtMoney($summary['new_projected_income'] ?? ($summary['new_projected_tuition'] ?? 0))) ?></div>
</div>
</div>
</div>
<div class="col-xl col-lg-3 col-md-4">
<div class="card border-0 shadow-sm h-100">
<div class="card-body">
<div class="text-muted small">Grades Unit Price</div>
<div class="fs-5 fw-semibold"><?= esc($fmtMoney($summary['unit_price'] ?? 0)) ?></div>
</div>
</div>
</div>
<div class="col-xl col-lg-3 col-md-4">
<div class="card border-0 shadow-sm h-100">
<div class="card-body">
<div class="text-muted small">Youth Unit Price</div>
<div class="fs-5 fw-semibold"><?= esc($fmtMoney($summary['youth_unit_price'] ?? 0)) ?></div>
</div>
</div>
</div>
<div class="col-xl col-lg-3 col-md-4">
<div class="card border-0 shadow-sm h-100">
<div class="card-body">
<div class="text-muted small">Difference</div>
<div class="fs-5 fw-semibold <?= ((float) ($summary['difference'] ?? 0)) >= 0 ? 'text-success' : 'text-danger' ?>">
<?= esc($fmtMoney($summary['difference'] ?? 0)) ?>
</div>
</div>
</div>
</div>
</div>
<div class="card shadow-sm">
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered align-middle">
<thead class="table-light">
<tr>
<th>Parent / Family</th>
<th>Student Count</th>
<th>Billable Student Count</th>
<th>Old Tuition Total</th>
<th>New Tuition Total</th>
<th>Difference</th>
<th>Warnings</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<?php if (!empty($result['families'])): ?>
<?php foreach ($result['families'] as $family): ?>
<tr>
<td><?= esc($family['parent_name'] ?? '') ?></td>
<td><?= esc((string) ($family['student_count'] ?? 0)) ?></td>
<td><?= esc((string) ($family['billable_student_count'] ?? 0)) ?></td>
<td><?= esc($fmtMoney($family['old_total'] ?? 0)) ?></td>
<td><?= esc($fmtMoney($family['new_total'] ?? 0)) ?></td>
<td class="<?= ((float) ($family['difference'] ?? 0)) >= 0 ? 'text-success' : 'text-danger' ?>">
<?= esc($fmtMoney($family['difference'] ?? 0)) ?>
</td>
<td class="small"><?= esc($warningText($family['warnings'] ?? [])) ?></td>
<td>
<details>
<summary>Students</summary>
<div class="table-responsive mt-2">
<table class="table table-sm table-striped mb-0">
<thead>
<tr>
<th>Student</th>
<th>Grade</th>
<th>Billable</th>
<th>Excluded Reason</th>
<th>Old Rule</th>
<th>Old Amount</th>
<th>New Rule</th>
<th>New Amount</th>
</tr>
</thead>
<tbody>
<?php foreach (($family['student_details'] ?? []) as $detail): ?>
<tr>
<td><?= esc($detail['student_name'] ?? '') ?></td>
<td><?= esc($detail['grade_level'] ?? '') ?></td>
<td><?= !empty($detail['billable']) ? 'Yes' : 'No' ?></td>
<td><?= esc((string) ($detail['excluded_reason'] ?? '')) ?></td>
<td><?= esc((string) ($detail['old_rule'] ?? '')) ?></td>
<td><?= esc($fmtMoney($detail['old_amount'] ?? 0)) ?></td>
<td><?= esc((string) ($detail['new_rule'] ?? '')) ?></td>
<td><?= esc($fmtMoney($detail['new_amount'] ?? 0)) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</details>
</td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="8" class="text-center text-muted">No forecastable families matched the selected filters.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div>
<?php endif; ?>
</div>
<?= $this->endSection() ?>
+7 -7
View File
@@ -48,7 +48,7 @@
<!-- Navbar Start --> <!-- Navbar Start -->
<nav class="navbar navbar-expand-lg bg-white navbar-light sticky-top px-4 px-lg-5 py-lg-0"> <nav class="navbar navbar-expand-lg bg-white navbar-light sticky-top px-4 px-lg-5 py-lg-0">
<a href="<?= base_url('/') ?>" class="navbar-brand d-flex align-items-center"> <a href="<?= base_url('/') ?>" class="navbar-brand d-flex align-items-center">
<img src="<?= base_url('images/logo.png') ?>" alt="Al Rahma Sunday School" style="height: 40px;"> <img src="<?= base_url('images/logo.png') ?>" alt="Al Rahma Sunday School" style="height: 40px; width: 40px; border-radius: 50%; object-fit: cover;">
<h1 class="m-0 ms-2 green-title">Al Rahma Sunday School</h1> <h1 class="m-0 ms-2 green-title">Al Rahma Sunday School</h1>
</a> </a>
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"> <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
@@ -195,22 +195,22 @@
<h3 class="text-white mb-4">Photo Gallery</h3> <h3 class="text-white mb-4">Photo Gallery</h3>
<div class="row g-2 pt-2"> <div class="row g-2 pt-2">
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-1.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-1.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-2.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-2.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-3.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-3.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-4.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-4.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-5.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-5.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-6.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-6.jpg') ?>" alt="">
</div> </div>
</div> </div>
</div> </div>
+2 -1
View File
@@ -14,7 +14,7 @@
<?= csrf_field() ?> <?= csrf_field() ?>
<div class="text-center mb-4"> <div class="text-center mb-4">
<a href="<?= base_url('/') ?>"> <a href="<?= base_url('/') ?>">
<img src="<?= base_url('assets/images/alrahma_logo.png') ?>" alt="" style="width: 180px; height: 120px;"> <img src="<?= base_url('assets/images/alrahma_logo.png') ?>" alt="" style="width: 120px; height: 120px; border-radius: 50%; object-fit: cover;">
</a> </a>
</div> </div>
@@ -25,6 +25,7 @@
<br> <br>
<input type="hidden" name="selected_role" id="selected_role"> <input type="hidden" name="selected_role" id="selected_role">
<input type="hidden" name="redirect_to" value="<?= esc((string) ($redirect_to ?? '')) ?>">
<div class="d-flex flex-wrap justify-content-center gap-3 mt-3"> <div class="d-flex flex-wrap justify-content-center gap-3 mt-3">
<?php foreach ($roles as $role): ?> <?php foreach ($roles as $role): ?>
+7 -7
View File
@@ -48,7 +48,7 @@
<!-- Navbar Start --> <!-- Navbar Start -->
<nav class="navbar navbar-expand-lg bg-white navbar-light sticky-top px-4 px-lg-5 py-lg-0"> <nav class="navbar navbar-expand-lg bg-white navbar-light sticky-top px-4 px-lg-5 py-lg-0">
<a href="<?= base_url('/') ?>" class="navbar-brand d-flex align-items-center"> <a href="<?= base_url('/') ?>" class="navbar-brand d-flex align-items-center">
<img src="<?= base_url('images/logo.png') ?>" alt="Al Rahma Sunday School" style="height: 40px;"> <img src="<?= base_url('images/logo.png') ?>" alt="Al Rahma Sunday School" style="height: 40px; width: 40px; border-radius: 50%; object-fit: cover;">
<h1 class="m-0 ms-2 green-title">Al Rahma Sunday School</h1> <h1 class="m-0 ms-2 green-title">Al Rahma Sunday School</h1>
</a> </a>
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"> <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
@@ -155,22 +155,22 @@
<h3 class="text-white mb-4">Photo Gallery</h3> <h3 class="text-white mb-4">Photo Gallery</h3>
<div class="row g-2 pt-2"> <div class="row g-2 pt-2">
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-1.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-1.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-2.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-2.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-3.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-3.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-4.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-4.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-5.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-5.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src=""assets/images/classes-6.jpg" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-6.jpg') ?>" alt="">
</div> </div>
</div> </div>
</div> </div>
+89
View File
@@ -0,0 +1,89 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Certificate Verification Al Rahma Sunday School</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.7.2/font/bootstrap-icons.min.css">
<style>
body { background: #f4f6f9; }
.verify-card { max-width: 520px; margin: 60px auto; }
.badge-valid { background: #198754; }
.badge-invalid { background: #dc3545; }
.cert-logo { width: 70px; height: 70px; border-radius: 50%; object-fit: cover; }
.field-label { font-size: .8rem; text-transform: uppercase; letter-spacing: .05em; color: #6c757d; }
.field-value { font-size: 1.05rem; font-weight: 500; }
</style>
</head>
<body>
<div class="verify-card px-3">
<!-- Header -->
<div class="text-center mb-4 mt-5">
<img src="<?= base_url('assets/images/alrahma_logo.png') ?>" alt="Al Rahma Sunday School" class="cert-logo mb-3">
<h4 class="fw-bold mb-0">Certificate Verification</h4>
<p class="text-muted small">Al Rahma Sunday School</p>
</div>
<?php if ($record): ?>
<!-- Valid -->
<div class="card shadow-sm border-0">
<div class="card-body p-4">
<div class="d-flex align-items-center gap-2 mb-4">
<span class="badge badge-valid text-white px-3 py-2 fs-6">
<i class="bi bi-patch-check-fill me-1"></i>Verified
</span>
<code class="text-muted"><?= esc($record['certificate_number']) ?></code>
</div>
<div class="row g-3">
<div class="col-12">
<div class="field-label">Student Name</div>
<div class="field-value"><?= esc($record['student_name']) ?></div>
</div>
<div class="col-6">
<div class="field-label">Grade / Class</div>
<div class="field-value"><?= esc($record['grade'] ?? '—') ?></div>
</div>
<div class="col-6">
<div class="field-label">School Year</div>
<div class="field-value"><?= esc($record['school_year'] ?? '—') ?></div>
</div>
<div class="col-12">
<div class="field-label">Issued On</div>
<div class="field-value">
<?= $record['issued_at'] ? esc(date('F j, Y \a\t g:i A', strtotime($record['issued_at']))) : '—' ?>
</div>
</div>
</div>
</div>
<div class="card-footer text-muted small text-center py-2">
This certificate was officially issued by Al Rahma Sunday School.
</div>
</div>
<?php else: ?>
<!-- Not found -->
<div class="card shadow-sm border-0">
<div class="card-body p-4 text-center">
<span class="badge badge-invalid text-white px-3 py-2 fs-6 mb-3 d-inline-block">
<i class="bi bi-x-circle-fill me-1"></i>Not Found
</span>
<p class="mb-0">No certificate matching this code was found in our records.<br>
Please check the code and try again.</p>
</div>
</div>
<?php endif; ?>
<p class="text-center text-muted small mt-4">
&copy; <?= date('Y') ?> Al Rahma Sunday School
</p>
</div>
</body>
</html>
+10 -10
View File
@@ -45,7 +45,7 @@
<!-- Navbar Start --> <!-- Navbar Start -->
<nav class="navbar navbar-expand-lg bg-white navbar-light sticky-top px-4 px-lg-5 py-lg-0"> <nav class="navbar navbar-expand-lg bg-white navbar-light sticky-top px-4 px-lg-5 py-lg-0">
<a href="<?= base_url('/') ?>" class="navbar-brand d-flex align-items-center"> <a href="<?= base_url('/') ?>" class="navbar-brand d-flex align-items-center">
<img src="<?= base_url('images/logo.png') ?>" alt="Al Rahma Sunday School" style="height: 40px;"> <img src="<?= base_url('images/logo.png') ?>" alt="Al Rahma Sunday School" style="height: 40px; width: 40px; border-radius: 50%; object-fit: cover;">
<h1 class="m-0 ms-2 green-title">Al Rahma Sunday School</h1> <h1 class="m-0 ms-2 green-title">Al Rahma Sunday School</h1>
</a> </a>
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarCollapse"> <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
@@ -93,7 +93,7 @@
<div class="col-lg-4 col-md-6 wow fadeInUp" data-wow-delay="0.1s"> <div class="col-lg-4 col-md-6 wow fadeInUp" data-wow-delay="0.1s">
<div class="classes-item"> <div class="classes-item">
<div class="bg-light rounded-circle w-75 mx-auto p-3"> <div class="bg-light rounded-circle w-75 mx-auto p-3">
<img class="img-fluid rounded-circle" src=""assets/images/classes-1.jpg" alt=""> <img class="img-fluid rounded-circle" src="<?= base_url('assets/images/classes-1.jpg') ?>" alt="">
</div> </div>
<div class="bg-light rounded p-4 pt-5 mt-n5"> <div class="bg-light rounded p-4 pt-5 mt-n5">
<a class="d-block text-center h3 mt-3 mb-4" href="">Quran Learning</a> <a class="d-block text-center h3 mt-3 mb-4" href="">Quran Learning</a>
@@ -104,7 +104,7 @@
<div class="col-lg-4 col-md-6 wow fadeInUp" data-wow-delay="0.3s"> <div class="col-lg-4 col-md-6 wow fadeInUp" data-wow-delay="0.3s">
<div class="classes-item"> <div class="classes-item">
<div class="bg-light rounded-circle w-75 mx-auto p-3"> <div class="bg-light rounded-circle w-75 mx-auto p-3">
<img class="img-fluid rounded-circle" src=""assets/images/classes-2.jpg" alt=""> <img class="img-fluid rounded-circle" src="<?= base_url('assets/images/classes-2.jpg') ?>" alt="">
</div> </div>
<div class="bg-light rounded p-4 pt-5 mt-n5"> <div class="bg-light rounded p-4 pt-5 mt-n5">
<a class="d-block text-center h3 mt-3 mb-4" href="">Islamic Studies</a> <a class="d-block text-center h3 mt-3 mb-4" href="">Islamic Studies</a>
@@ -114,7 +114,7 @@
<div class="col-lg-4 col-md-6 wow fadeInUp" data-wow-delay="0.5s"> <div class="col-lg-4 col-md-6 wow fadeInUp" data-wow-delay="0.5s">
<div class="classes-item"> <div class="classes-item">
<div class="bg-light rounded-circle w-75 mx-auto p-3"> <div class="bg-light rounded-circle w-75 mx-auto p-3">
<img class="img-fluid rounded-circle" src=""assets/images/classes-3.jpg" alt=""> <img class="img-fluid rounded-circle" src="<?= base_url('assets/images/classes-3.jpg') ?>" alt="">
</div> </div>
<div class="bg-light rounded p-4 pt-5 mt-n5"> <div class="bg-light rounded p-4 pt-5 mt-n5">
<a class="d-block text-center h3 mt-3 mb-4" href="">Arabic Learning</a> <a class="d-block text-center h3 mt-3 mb-4" href="">Arabic Learning</a>
@@ -160,22 +160,22 @@
<h3 class="text-white mb-4">Photo Gallery</h3> <h3 class="text-white mb-4">Photo Gallery</h3>
<div class="row g-2 pt-2"> <div class="row g-2 pt-2">
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-1.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-1.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-2.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-2.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-3.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-3.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-4.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-4.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-5.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-5.jpg') ?>" alt="">
</div> </div>
<div class="col-4"> <div class="col-4">
<img class="img-fluid rounded bg-light p-1" src="<?= base_url('"assets/images/classes-6.jpg') ?>" alt=""> <img class="img-fluid rounded bg-light p-1" src="<?= base_url('assets/images/classes-6.jpg') ?>" alt="">
</div> </div>
</div> </div>
</div> </div>

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