Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6d543c52cc | |||
| 253be573ac |
@@ -0,0 +1,184 @@
|
||||
#--------------------------------------------------------------------
|
||||
# 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 =
|
||||
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
|
||||
+1
-53
@@ -1,54 +1,2 @@
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
/vendor/
|
||||
/node_modules/
|
||||
|
||||
/writable/cache/*
|
||||
/writable/debugbar/*
|
||||
/writable/logs/*
|
||||
/writable/session/*
|
||||
/writable/uploads/*
|
||||
/writable/tmp/*
|
||||
/writable/*.log
|
||||
|
||||
!/writable/.gitkeep
|
||||
!/writable/cache/.gitkeep
|
||||
!/writable/debugbar/.gitkeep
|
||||
!/writable/logs/.gitkeep
|
||||
!/writable/session/.gitkeep
|
||||
!/writable/uploads/.gitkeep
|
||||
!/writable/tmp/.gitkeep
|
||||
|
||||
/public/build/
|
||||
/public/hot/
|
||||
/public/uploads/**
|
||||
!/public/uploads/**/index.html
|
||||
!/public/uploads/.gitkeep
|
||||
|
||||
/uploads/**
|
||||
!/uploads/**/index.html
|
||||
!/uploads/.gitkeep
|
||||
|
||||
docker-compose.override.yml
|
||||
docker-compose.local.yml
|
||||
|
||||
*.log
|
||||
.swp
|
||||
.swo
|
||||
*~
|
||||
.tmp
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.idea/
|
||||
.vscode/
|
||||
.codex/
|
||||
|
||||
/coverage/
|
||||
/build/
|
||||
/builds
|
||||
/phpunit.xml.cache
|
||||
/.phpunit.result.cache
|
||||
/writable/reports/*
|
||||
/writable/test.txt
|
||||
writable/session/
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Commands;
|
||||
|
||||
use App\Libraries\InvoiceLedgerService;
|
||||
use App\Models\InvoiceModel;
|
||||
use CodeIgniter\CLI\BaseCommand;
|
||||
use CodeIgniter\CLI\CLI;
|
||||
|
||||
class RecalculateInvoices extends BaseCommand
|
||||
{
|
||||
protected $group = 'Financial';
|
||||
protected $name = 'financial:recalculate-invoices';
|
||||
protected $description = 'Audits invoice totals against the centralized ledger and optionally writes the corrected values.';
|
||||
protected $usage = 'financial:recalculate-invoices [--commit] [--invoice-id=123] [--parent-id=456] [--school-year=2025-2026] [--semester=Fall]';
|
||||
protected $options = [
|
||||
'--commit' => 'Persist recalculated totals. Without this flag the command runs in dry-run mode.',
|
||||
'--invoice-id' => 'Only process a single invoice ID.',
|
||||
'--parent-id' => 'Only process invoices for one parent.',
|
||||
'--school-year' => 'Only process invoices for the specified school year.',
|
||||
'--semester' => 'Only process invoices for the specified semester.',
|
||||
];
|
||||
|
||||
public function run(array $params)
|
||||
{
|
||||
$options = $this->parseOptions($params);
|
||||
$invoiceModel = new InvoiceModel();
|
||||
$ledgerService = new InvoiceLedgerService();
|
||||
$invoiceIds = $this->loadInvoiceIds($invoiceModel, $options);
|
||||
|
||||
if ($invoiceIds === []) {
|
||||
CLI::write('No invoices matched the provided filters.', 'yellow');
|
||||
return;
|
||||
}
|
||||
|
||||
$commit = !empty($options['commit']);
|
||||
CLI::write(($commit ? 'Applying' : 'Dry-run auditing') . ' ' . count($invoiceIds) . ' invoice(s)...', 'yellow');
|
||||
|
||||
$changed = 0;
|
||||
$unchanged = 0;
|
||||
$errors = 0;
|
||||
|
||||
foreach ($invoiceIds as $invoiceId) {
|
||||
$invoice = $invoiceModel->find($invoiceId);
|
||||
if (!$invoice) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$calculation = $ledgerService->calculateInvoice($invoiceId);
|
||||
$diffs = $this->diffInvoice($invoice, $calculation);
|
||||
|
||||
if ($diffs === []) {
|
||||
$unchanged++;
|
||||
CLI::write('Invoice #' . $invoiceId . ' unchanged.', 'green');
|
||||
continue;
|
||||
}
|
||||
|
||||
$changed++;
|
||||
CLI::write('Invoice #' . $invoiceId . ' requires recalculation:', 'light_yellow');
|
||||
foreach ($diffs as $label => $values) {
|
||||
CLI::write(sprintf(
|
||||
' %s: %s -> %s',
|
||||
$label,
|
||||
(string) $values['from'],
|
||||
(string) $values['to']
|
||||
));
|
||||
}
|
||||
|
||||
if ($commit) {
|
||||
$ledgerService->recalculateInvoice($invoiceId);
|
||||
CLI::write(' saved', 'blue');
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$errors++;
|
||||
CLI::error('Invoice #' . $invoiceId . ' failed: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
CLI::newLine();
|
||||
CLI::write('Processed: ' . count($invoiceIds), 'white');
|
||||
CLI::write('Changed: ' . $changed, $changed > 0 ? 'yellow' : 'white');
|
||||
CLI::write('Unchanged: ' . $unchanged, 'green');
|
||||
CLI::write('Errors: ' . $errors, $errors > 0 ? 'red' : 'white');
|
||||
|
||||
if (!$commit) {
|
||||
CLI::write('Dry-run complete. Re-run with --commit to persist corrections.', 'light_blue');
|
||||
}
|
||||
}
|
||||
|
||||
protected function parseOptions(array $params): array
|
||||
{
|
||||
$options = [
|
||||
'commit' => false,
|
||||
'invoice-id' => null,
|
||||
'parent-id' => null,
|
||||
'school-year' => null,
|
||||
'semester' => null,
|
||||
];
|
||||
|
||||
foreach ($params as $param) {
|
||||
$value = trim((string) $param);
|
||||
if ($value === '--commit') {
|
||||
$options['commit'] = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!str_starts_with($value, '--') || !str_contains($value, '=')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
[$key, $raw] = explode('=', substr($value, 2), 2);
|
||||
if (array_key_exists($key, $options)) {
|
||||
$options[$key] = $raw;
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
protected function loadInvoiceIds(InvoiceModel $invoiceModel, array $options): array
|
||||
{
|
||||
$builder = $invoiceModel->select('id')->orderBy('id', 'ASC');
|
||||
|
||||
if (!empty($options['invoice-id'])) {
|
||||
$builder->where('id', (int) $options['invoice-id']);
|
||||
}
|
||||
|
||||
if (!empty($options['parent-id'])) {
|
||||
$builder->where('parent_id', (int) $options['parent-id']);
|
||||
}
|
||||
|
||||
if (!empty($options['school-year'])) {
|
||||
$builder->where('school_year', (string) $options['school-year']);
|
||||
}
|
||||
|
||||
if (!empty($options['semester'])) {
|
||||
$builder->where('semester', (string) $options['semester']);
|
||||
}
|
||||
|
||||
return array_map(
|
||||
static fn (array $row): int => (int) ($row['id'] ?? 0),
|
||||
$builder->findAll()
|
||||
);
|
||||
}
|
||||
|
||||
protected function diffInvoice(array $invoice, array $calculation): array
|
||||
{
|
||||
$fields = [
|
||||
'total_amount' => 'total_amount',
|
||||
'paid_amount' => 'paid_amount',
|
||||
'balance' => 'balance',
|
||||
'status' => 'status',
|
||||
'has_discount' => 'has_discount',
|
||||
];
|
||||
$diffs = [];
|
||||
|
||||
foreach ($fields as $invoiceKey => $calcKey) {
|
||||
$current = (string) ($invoice[$invoiceKey] ?? '');
|
||||
$recalculated = (string) ($calculation[$calcKey] ?? '');
|
||||
if ($current !== $recalculated) {
|
||||
$diffs[$invoiceKey] = [
|
||||
'from' => $current,
|
||||
'to' => $recalculated,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $diffs;
|
||||
}
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Commands;
|
||||
|
||||
use App\Controllers\View\EmailController;
|
||||
use App\Models\ClassSectionModel;
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\TeacherSubmissionNotificationHistoryModel;
|
||||
use App\Models\UserModel;
|
||||
use CodeIgniter\CLI\BaseCommand;
|
||||
use CodeIgniter\CLI\CLI;
|
||||
use Config\Database;
|
||||
|
||||
class SendExamDraftDeadlineReminders extends BaseCommand
|
||||
{
|
||||
protected $group = 'Exam Drafts';
|
||||
protected $name = 'exam-drafts:deadline-reminders';
|
||||
protected $description = 'Sends exam draft deadline reminders to teachers who have not submitted drafts.';
|
||||
|
||||
public function run(array $params)
|
||||
{
|
||||
helper('date');
|
||||
|
||||
$configModel = new ConfigurationModel();
|
||||
$schoolYear = (string) ($configModel->getConfig('school_year') ?? '');
|
||||
$semester = (string) ($configModel->getConfig('semester') ?? '');
|
||||
$deadlineValue = trim((string) ($configModel->getConfig('exam_draft_deadline') ?? ''));
|
||||
if ($deadlineValue === '') {
|
||||
CLI::write('exam_draft_deadline is not configured.', 'yellow');
|
||||
return;
|
||||
}
|
||||
|
||||
$tz = new \DateTimeZone(config('App')->appTimezone ?? 'UTC');
|
||||
try {
|
||||
$deadline = new \DateTimeImmutable($deadlineValue, $tz);
|
||||
} catch (\Throwable $e) {
|
||||
CLI::write('Invalid exam_draft_deadline value.', 'red');
|
||||
return;
|
||||
}
|
||||
$deadline = $deadline->setTime(0, 0, 0);
|
||||
$today = new \DateTimeImmutable('now', $tz);
|
||||
$today = $today->setTime(0, 0, 0);
|
||||
|
||||
if ($today > $deadline) {
|
||||
CLI::write('Deadline has passed. No reminders sent.', 'yellow');
|
||||
return;
|
||||
}
|
||||
|
||||
$daysToDeadline = (int) $today->diff($deadline)->format('%r%a');
|
||||
if (!$this->shouldSendOnDay($daysToDeadline)) {
|
||||
CLI::write('No reminder scheduled for today.', 'yellow');
|
||||
return;
|
||||
}
|
||||
|
||||
$db = Database::connect();
|
||||
$teacherClassRows = $db->table('teacher_class')
|
||||
->select('teacher_id, class_section_id, school_year, semester')
|
||||
->when($schoolYear !== '', static function ($builder) use ($schoolYear) {
|
||||
return $builder->where('school_year', $schoolYear);
|
||||
})
|
||||
->when($semester !== '', static function ($builder) use ($semester) {
|
||||
return $builder->where('semester', $semester);
|
||||
})
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
if (empty($teacherClassRows)) {
|
||||
CLI::write('No teacher assignments found.', 'yellow');
|
||||
return;
|
||||
}
|
||||
|
||||
$draftTable = 'exam_drafts';
|
||||
$fields = $db->getFieldNames($draftTable);
|
||||
$teacherColumn = in_array('teacher_id', $fields, true) ? 'teacher_id' : 'author_id';
|
||||
$hasStatusColumn = in_array('status', $fields, true);
|
||||
$hasIsLegacyColumn = in_array('is_legacy', $fields, true);
|
||||
|
||||
$draftsQuery = $db->table($draftTable)
|
||||
->select("{$teacherColumn} AS teacher_id, class_section_id")
|
||||
->when($schoolYear !== '', static function ($builder) use ($schoolYear) {
|
||||
return $builder->where('school_year', $schoolYear);
|
||||
})
|
||||
->when($semester !== '', static function ($builder) use ($semester) {
|
||||
return $builder->where('semester', $semester);
|
||||
});
|
||||
|
||||
if ($hasStatusColumn) {
|
||||
$draftsQuery = $draftsQuery->where('status !=', 'legacy');
|
||||
}
|
||||
if ($hasIsLegacyColumn) {
|
||||
$draftsQuery = $draftsQuery->where('is_legacy', 0);
|
||||
}
|
||||
|
||||
$draftRows = $draftsQuery->get()->getResultArray();
|
||||
$submittedMap = [];
|
||||
foreach ($draftRows as $row) {
|
||||
$key = (int) ($row['teacher_id'] ?? 0) . '|' . (int) ($row['class_section_id'] ?? 0);
|
||||
$submittedMap[$key] = true;
|
||||
}
|
||||
|
||||
$missingByTeacher = [];
|
||||
foreach ($teacherClassRows as $row) {
|
||||
$teacherId = (int) ($row['teacher_id'] ?? 0);
|
||||
$classSectionId = (int) ($row['class_section_id'] ?? 0);
|
||||
if ($teacherId <= 0 || $classSectionId <= 0) {
|
||||
continue;
|
||||
}
|
||||
$key = $teacherId . '|' . $classSectionId;
|
||||
if (!isset($submittedMap[$key])) {
|
||||
$missingByTeacher[$teacherId][] = $classSectionId;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($missingByTeacher)) {
|
||||
CLI::write('All teachers have submitted drafts.', 'green');
|
||||
return;
|
||||
}
|
||||
|
||||
$userModel = new UserModel();
|
||||
$classSectionModel = new ClassSectionModel();
|
||||
$historyModel = new TeacherSubmissionNotificationHistoryModel();
|
||||
$mailer = new EmailController();
|
||||
|
||||
$classSections = $classSectionModel
|
||||
->select('class_section_id, class_section_name')
|
||||
->findAll();
|
||||
$classLookup = [];
|
||||
foreach ($classSections as $section) {
|
||||
$classLookup[(int) ($section['class_section_id'] ?? 0)] = $section['class_section_name'] ?? '';
|
||||
}
|
||||
|
||||
$todayStamp = $today->format('Y-m-d');
|
||||
foreach ($missingByTeacher as $teacherId => $sectionIds) {
|
||||
$teacher = $userModel->find($teacherId);
|
||||
$email = $teacher['email'] ?? '';
|
||||
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$alreadySent = $historyModel
|
||||
->where('teacher_id', $teacherId)
|
||||
->where('notification_category', 'exam_draft_deadline')
|
||||
->where('school_year', $schoolYear)
|
||||
->where('semester', $semester)
|
||||
->like('sent_at', $todayStamp)
|
||||
->countAllResults() > 0;
|
||||
if ($alreadySent) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$classNames = array_map(static function ($id) use ($classLookup) {
|
||||
return $classLookup[(int) $id] ?? "Class {$id}";
|
||||
}, $sectionIds);
|
||||
$classList = implode(', ', $classNames);
|
||||
$teacherName = trim(($teacher['firstname'] ?? '') . ' ' . ($teacher['lastname'] ?? ''));
|
||||
if ($teacherName === '') {
|
||||
$teacherName = 'Teacher';
|
||||
}
|
||||
|
||||
$subject = 'Reminder: Exam draft submission deadline';
|
||||
$body = '<p>Dear ' . esc($teacherName) . ',</p>'
|
||||
. '<p>This is a reminder to submit your exam draft(s) for: ' . esc($classList) . '.</p>'
|
||||
. '<p>Deadline: <strong>' . esc($deadline->format('Y-m-d')) . '</strong></p>'
|
||||
. '<p>Please submit your draft at <a href="' . esc(base_url('teacher/exam-drafts')) . '">Teacher Exam Drafts</a>.</p>'
|
||||
. '<p>Thank you.</p>';
|
||||
|
||||
$status = 'failed';
|
||||
if ($mailer->sendEmail($email, $subject, $body, 'notifications')) {
|
||||
$status = 'sent';
|
||||
CLI::write("Sent reminder to {$email}", 'green');
|
||||
}
|
||||
|
||||
$historyModel->insert([
|
||||
'teacher_id' => $teacherId,
|
||||
'class_section_id' => 0,
|
||||
'admin_id' => null,
|
||||
'notification_category' => 'exam_draft_deadline',
|
||||
'message' => strip_tags($body),
|
||||
'status' => $status,
|
||||
'school_year' => $schoolYear,
|
||||
'semester' => $semester,
|
||||
'sent_at' => utc_now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function shouldSendOnDay(int $daysToDeadline): bool
|
||||
{
|
||||
if ($daysToDeadline < 0) {
|
||||
return false;
|
||||
}
|
||||
if ($daysToDeadline <= 4) {
|
||||
return true;
|
||||
}
|
||||
return in_array($daysToDeadline, [28, 21, 14, 7], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
<?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
@@ -82,7 +82,7 @@ class App extends BaseConfig
|
||||
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
||||
|
|
||||
*/
|
||||
public string $permittedURIChars = 'a-z 0-9~%.:_\-,';
|
||||
public string $permittedURIChars = 'a-z 0-9~%.:_\-';
|
||||
|
||||
/**
|
||||
* --------------------------------------------------------------------------
|
||||
|
||||
@@ -16,11 +16,11 @@ class Commands extends BaseService
|
||||
\App\Commands\CleanupPasswordResets::class,
|
||||
\App\Commands\ConfigUpdate::class,
|
||||
\App\Commands\DeleteInactiveUsers::class,
|
||||
\App\Commands\RecalculateInvoices::class,
|
||||
\App\Commands\SendAbsenteesSummary::class,
|
||||
\App\Commands\SendLatesSummary::class,
|
||||
\App\Commands\SendMonthlyPaymentNotifications::class,
|
||||
\App\Commands\SendTestPaymentNotification::class,
|
||||
\App\Commands\SyncPaypalPayments::class,
|
||||
\App\Commands\RecalculateAttendance::class,
|
||||
];
|
||||
|
||||
@@ -30,4 +30,4 @@ class Commands extends BaseService
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-46
@@ -9,51 +9,43 @@ class Database extends Config
|
||||
public string $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
|
||||
public string $defaultGroup = 'default';
|
||||
|
||||
public array $default = [];
|
||||
public array $tests = [];
|
||||
public array $default = [
|
||||
'DSN' => '',
|
||||
'hostname' => 'localhost',
|
||||
'username' => 'u280815660_melabidi',
|
||||
'password' => '>tNxlRzP/W8',
|
||||
'database' => 'u280815660_school',
|
||||
'DBDriver' => 'MySQLi',
|
||||
'DBPrefix' => '',
|
||||
'pConnect' => false,
|
||||
'DBDebug' => (ENVIRONMENT !== 'development'),
|
||||
'charset' => 'utf8',
|
||||
'DBCollat' => 'utf8_general_ci',
|
||||
'swapPre' => '',
|
||||
'encrypt' => false,
|
||||
'compress' => false,
|
||||
'strictOn' => false,
|
||||
'failover' => [],
|
||||
'port' => 3306,
|
||||
];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->default = [
|
||||
'DSN' => '',
|
||||
'hostname' => env('database.default.hostname'),
|
||||
'username' => env('database.default.username'),
|
||||
'password' => env('database.default.password'),
|
||||
'database' => env('database.default.database'),
|
||||
'DBDriver' => env('database.default.DBDriver', 'MySQLi'),
|
||||
'DBPrefix' => '',
|
||||
'pConnect' => false,
|
||||
'DBDebug' => (ENVIRONMENT !== 'development'),
|
||||
'charset' => 'utf8',
|
||||
'DBCollat' => 'utf8_general_ci',
|
||||
'swapPre' => '',
|
||||
'encrypt' => false,
|
||||
'compress' => false,
|
||||
'strictOn' => false,
|
||||
'failover' => [],
|
||||
'port' => (int) env('database.default.port', 3306),
|
||||
];
|
||||
|
||||
$this->tests = [
|
||||
'DSN' => '',
|
||||
'hostname' => env('database.tests.hostname', env('database.default.hostname')),
|
||||
'username' => env('database.tests.username', env('database.default.username')),
|
||||
'password' => env('database.tests.password', env('database.default.password')),
|
||||
'database' => env('database.tests.database', env('database.default.database')),
|
||||
'DBDriver' => env('database.tests.DBDriver', env('database.default.DBDriver', 'MySQLi')),
|
||||
'DBPrefix' => env('database.tests.DBPrefix', 'db_'),
|
||||
'pConnect' => false,
|
||||
'DBDebug' => true,
|
||||
'charset' => 'utf8',
|
||||
'DBCollat' => 'utf8_general_ci',
|
||||
'swapPre' => '',
|
||||
'encrypt' => false,
|
||||
'compress' => false,
|
||||
'strictOn' => false,
|
||||
'failover' => [],
|
||||
'port' => (int) env('database.tests.port', env('database.default.port', 3306)),
|
||||
];
|
||||
}
|
||||
public array $tests = [
|
||||
'DSN' => '',
|
||||
'hostname' => 'localhost',
|
||||
'username' => 'u280815660_melabidi',
|
||||
'password' => '>tNxlRzP/W8',
|
||||
'database' => 'u280815660_school',
|
||||
'DBDriver' => 'MySQLi',
|
||||
'DBPrefix' => 'db_',
|
||||
'pConnect' => false,
|
||||
'DBDebug' => true,
|
||||
'charset' => 'utf8',
|
||||
'DBCollat' => 'utf8_general_ci',
|
||||
'swapPre' => '',
|
||||
'encrypt' => false,
|
||||
'compress' => false,
|
||||
'strictOn' => false,
|
||||
'failover' => [],
|
||||
'port' => 3306,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ use App\Listeners\SchoolEventListener;
|
||||
use App\Listeners\AttendanceConsequenceListener;
|
||||
use App\Listeners\WhatsappInviteListener;
|
||||
use App\Listeners\BelowSixtyEmailListener;
|
||||
use App\Listeners\DecisionEmailListener;
|
||||
|
||||
// Create an instance so we can use $this->emailService like your other handlers
|
||||
$waListener = new WhatsappInviteListener(service('emailService'));
|
||||
@@ -119,7 +118,6 @@ Events::on('attendance.follow_up', [AttendanceConsequenceListener::class, 'fol
|
||||
Events::on('attendance.final_warning', [AttendanceConsequenceListener::class, 'finalWarning']);
|
||||
Events::on('attendance.dismissal', [AttendanceConsequenceListener::class, 'dismissal']);
|
||||
Events::on('below60.email', [BelowSixtyEmailListener::class, 'handle']);
|
||||
Events::on('below60.decision_email', [DecisionEmailListener::class, 'handle']);
|
||||
|
||||
//Whatsapp Event listener
|
||||
Events::on('whatsapp_invites.send', [$waListener, 'handle']);
|
||||
|
||||
@@ -24,8 +24,6 @@ class Filters extends BaseConfig
|
||||
'honeypot' => Honeypot::class,
|
||||
'invalidchars' => InvalidChars::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
|
||||
'apiAuth' => \App\Filters\ApiAuthFilter::class, // JWT-based API authentication
|
||||
'cleanupScheduler' => \App\Filters\CleanupScheduler::class,
|
||||
@@ -44,9 +42,11 @@ class Filters extends BaseConfig
|
||||
public array $globals = [
|
||||
'before' => [
|
||||
'timezone',
|
||||
'sanitizeinput',
|
||||
'invalidchars',
|
||||
'csrf' => ['except' => [
|
||||
// Webhooks / integrations
|
||||
'api/paypal-webhook',
|
||||
'index.php/api/paypal-webhook',
|
||||
|
||||
// WhatsApp membership management (legacy allowances retained)
|
||||
'whatsapp/update-membership',
|
||||
'index.php/whatsapp/update-membership',
|
||||
@@ -80,7 +80,6 @@ class Filters extends BaseConfig
|
||||
]],
|
||||
],
|
||||
'after' => [
|
||||
'secureheaders',
|
||||
'toolbar',
|
||||
'cleanupScheduler' => ['except' => ['cleanup/*']],
|
||||
],
|
||||
@@ -113,7 +112,7 @@ class Filters extends BaseConfig
|
||||
* @var array<string, array<string, list<string>>>
|
||||
*/
|
||||
public array $filters = [
|
||||
'apiratelimit' => ['before' => ['api/*', 'index.php/api/*']],
|
||||
|
||||
];
|
||||
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ use CodeIgniter\Format\XMLFormatter;
|
||||
|
||||
class Format extends BaseConfig
|
||||
{
|
||||
public int $jsonEncodeDepth = 512;
|
||||
/**
|
||||
* --------------------------------------------------------------------------
|
||||
* Available Response Formats
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<?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
|
||||
}
|
||||
+75
-107
@@ -174,18 +174,6 @@ $routes->group('administrator/subject-curriculum', ['filter' => 'auth:update_cur
|
||||
$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');
|
||||
|
||||
|
||||
|
||||
/*
|
||||
@@ -242,10 +230,6 @@ $routes->get('reset_password', 'View\UserController::resetPassword');
|
||||
|
||||
//$routes->get('/blocked', 'View\UserController::blocked');
|
||||
|
||||
$routes->get('confirm_authorized_user', 'View\AuthorizedUsersController::confirm');
|
||||
$routes->get('set_authorized_user_password/(:num)', 'View\AuthorizedUsersController::setPassword/$1');
|
||||
$routes->post('set_authorized_user_password/(:num)', 'View\AuthorizedUsersController::savePassword/$1');
|
||||
|
||||
$routes->post('assign_class_student', 'View\StudentController::assignClassStudent');
|
||||
$routes->post('remove_class_student', 'View\StudentController::removeClassStudent');
|
||||
$routes->post('administrator/remove_class_student', 'View\StudentController::removeClassStudent'); // alias to avoid 404s
|
||||
@@ -257,17 +241,15 @@ $routes->post('administrator/sections/auto-distribute', 'View\StudentController:
|
||||
$routes->get('administrator/sections/promotion-totals', 'View\StudentController::promotionTotalsApi');
|
||||
|
||||
|
||||
$routes->get('refunds/list', 'View\RefundController::listRefunds', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('refunds/request', 'View\RefundController::requestRefund', ['filter' => 'auth:create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->post('refunds/approve/(:num)', 'View\RefundController::approveRefund/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/pay/(:num)', 'View\RefundController::payRefund/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/updateStatus/(:num)', 'View\RefundController::updateStatus/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/processRefunds', 'View\RefundController::processRefunds', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/updateStatus', 'View\RefundController::updateStatus', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/updatePayment', 'View\RefundController::updatePayment', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('refunds/recalculateOverpayments', 'View\RefundController::recalculateOverpayments', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('refunds/file/(:num)', 'View\RefundController::serveRefundFile/$1', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('refunds/file/(:num)/(:segment)', 'View\RefundController::serveRefundFile/$1/$2', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('refunds/list', 'View\RefundController::listRefunds');
|
||||
$routes->post('refunds/request', 'View\RefundController::requestRefund');
|
||||
$routes->post('refunds/approve/(:num)', 'View\RefundController::approveRefund/$1');
|
||||
$routes->post('refunds/pay/(:num)', 'View\RefundController::payRefund/$1');
|
||||
$routes->post('refunds/updateStatus/(:num)', 'View\RefundController::updateStatus/$1');
|
||||
$routes->post('refunds/processRefunds', 'View\RefundController::processRefunds');
|
||||
$routes->post('refunds/updateStatus', 'View\RefundController::updateStatus');
|
||||
$routes->post('refunds/updatePayment', 'View\RefundController::updatePayment');
|
||||
$routes->post('refunds/recalculateOverpayments', 'View\RefundController::recalculateOverpayments');
|
||||
|
||||
|
||||
|
||||
@@ -377,7 +359,6 @@ $routes->get('/teacher/teacher_contactus', 'View\TeacherController::contactusTea
|
||||
|
||||
$routes->get('/teacher/exam-drafts', 'View\ExamDraftController::teacherIndex', ['filter' => 'auth:teacher,teacher_assistant,teacher_dashboard,read']);
|
||||
$routes->post('/teacher/exam-drafts', 'View\ExamDraftController::teacherStore', ['filter' => 'auth:teacher,teacher_assistant,teacher_dashboard,read']);
|
||||
$routes->get('/teacher/exam-drafts/status', 'View\ExamDraftController::teacherStatusFeed', ['filter' => 'auth:teacher,teacher_assistant,teacher_dashboard,read']);
|
||||
|
||||
|
||||
|
||||
@@ -407,8 +388,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('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,administrator,principal']);
|
||||
$routes->get('exam-drafts/files/final/(:segment)', 'View\FilesController::examDraftFinal/$1', ['filter' => 'auth:teacher,teacher_assistant,admin,administrator,principal']);
|
||||
$routes->get('exam-drafts/files/teacher/(:segment)', 'View\FilesController::examDraftTeacher/$1', ['filter' => 'auth:teacher,teacher_assistant,admin']);
|
||||
$routes->get('exam-drafts/files/final/(:segment)', 'View\FilesController::examDraftFinal/$1', ['filter' => 'auth:teacher,teacher_assistant,admin']);
|
||||
|
||||
|
||||
|
||||
@@ -420,8 +401,6 @@ $routes->get('teacher/progress/submit', 'ClassProgressController::create', ['fil
|
||||
$routes->post('teacher/progress/store', 'ClassProgressController::store', ['filter' => 'auth:teacher,teacher_assistant']);
|
||||
$routes->get('teacher/progress/history', 'ClassProgressController::history', ['filter' => 'auth:teacher,teacher_assistant']);
|
||||
$routes->get('teacher/progress/view/(:num)', 'ClassProgressController::view/$1', ['filter' => 'auth:teacher,teacher_assistant']);
|
||||
$routes->get('teacher/progress/edit/(:num)', 'ClassProgressController::edit/$1', ['filter' => 'auth:teacher,teacher_assistant']);
|
||||
$routes->post('teacher/progress/update/(:num)', 'ClassProgressController::update/$1', ['filter' => 'auth:teacher,teacher_assistant']);
|
||||
$routes->get('teacher/progress/attachment/(:num)', 'ClassProgressController::attachment/$1', ['filter' => 'auth:teacher,teacher_assistant']);
|
||||
$routes->get('teacher/progress/attachment-file/(:num)', 'ClassProgressController::attachmentFile/$1', ['filter' => 'auth:teacher,teacher_assistant']);
|
||||
$routes->get('parent/progress', 'ParentProgressController::index', ['filter' => 'auth:parent']);
|
||||
@@ -520,36 +499,17 @@ $routes->get('grading/project/(:num)', 'View\ProjectController::showProjectMngt/
|
||||
$routes->post('grading/updateProject', 'View\ProjectController::updateProject');
|
||||
|
||||
$routes->get('grading/below-60', 'View\GradingController::belowSixty', ['filter' => 'auth:read']);
|
||||
$routes->get('grading/below-60/email/edit', 'View\GradingController::editBelowSixtyEmail', ['filter' => 'auth:read']);
|
||||
$routes->post('grading/below-60/email', 'View\GradingController::sendBelowSixtyEmail', ['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->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
|
||||
$routes->get('grading/(:segment)/(:num)/(:num)', 'View\GradingController::show/$1/$2/$3');
|
||||
$routes->post('grading/update', 'View\GradingController::update');
|
||||
$routes->get('grading', 'View\GradingController::grading');
|
||||
$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/release-scores', 'View\GradingController::toggleParentScoresRelease', ['filter' => 'auth:read']);
|
||||
$routes->post('grading/refresh-semester-scores', 'View\GradingController::refreshSemesterScores', ['filter' => 'auth:read']);
|
||||
@@ -567,13 +527,9 @@ $routes->post('payment/event_charges', 'View\EventController::eventUpdate');
|
||||
|
||||
// Parent event participation
|
||||
$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('parent/events', 'View\ParentController::parentEventPage', ['filter' => 'auth:parent']);
|
||||
$routes->get('parent/events', 'View\ParentController::parentEventPage');
|
||||
// parent event participation page
|
||||
$routes->post('parent/updateParticipation', 'View\ParentController::updateParticipation'); // handle parent participation updates
|
||||
|
||||
@@ -588,19 +544,19 @@ $routes->post('invoices/updateStatus/(:num)', 'View\InvoiceController::updateSta
|
||||
// app/Config/Routes.php
|
||||
$routes->group('payment', ['filter' => 'auth'], static function ($routes) {
|
||||
// Read
|
||||
$routes->get('manual_pay', 'View\PaymentController::manualPaySearch', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('manual_pay_suggest', 'View\PaymentController::manualPaySuggest', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('manual_pay', 'View\PaymentController::manualPaySearch', ['filter' => 'auth:read']);
|
||||
$routes->get('manual_pay_suggest', 'View\PaymentController::manualPaySuggest', ['filter' => 'auth:read']);
|
||||
|
||||
// Create
|
||||
$routes->post('manual_pay', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:create_payment|create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->post('manual_pay', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:create']);
|
||||
|
||||
// Update
|
||||
$routes->post('manual_pay_edit', 'View\PaymentController::manualPayEdit', ['filter' => 'auth:update_payment|update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('manual_pay_update', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:create_payment|create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->post('manual_pay_edit', 'View\PaymentController::manualPayEdit', ['filter' => 'auth:update']);
|
||||
$routes->post('manual_pay_update', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:update']);
|
||||
|
||||
// Read (serve files)
|
||||
$routes->get('file/(:num)/(:segment)', 'View\PaymentController::servePaymentFile/$1/$2', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('file/(:num)', 'View\PaymentController::servePaymentFile/$1', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('serveCheckFile/(:any)/(:any)', 'View\PaymentController::serveCheckFile/$1/$2', ['filter' => 'auth:read']);
|
||||
$routes->get('serveCheckFile/(:any)', 'View\PaymentController::serveCheckFile/$1', ['filter' => 'auth:read']);
|
||||
});
|
||||
|
||||
|
||||
@@ -643,12 +599,9 @@ $routes->group('admin', ['filter' => 'auth'], static function ($routes) {
|
||||
$routes->post('admin/broadcast-email/upload-image', 'View\BroadcastEmailController::uploadImage');
|
||||
|
||||
|
||||
$routes->get('payment/financial_report', 'View\FinancialController::financialReport', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('financial-report/financialReportSummary', 'View\FinancialController::financialReportSummary', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||
$routes->get('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('payment/financial_report', 'View\FinancialController::financialReport');
|
||||
$routes->get('financial-report/financialReportSummary', 'View\FinancialController::financialReportSummary');
|
||||
$routes->get('payment/download_csv', 'View\FinancialController::downloadCsv');
|
||||
$routes->get('reports/downloadFinancialReport', 'View\FinancialController::downloadFinancialReport');
|
||||
// Financial APIs (JSON)
|
||||
$routes->get('api/financial/report', 'View\FinancialController::financialReportData', ['filter' => 'auth']);
|
||||
@@ -659,27 +612,27 @@ $routes->get('payment/unpaid-parents', 'View\FinancialController::unpaidParents'
|
||||
$routes->get('api/financial/unpaid-parents', 'View\FinancialController::unpaidParents', ['filter' => 'auth:view_invoice']);
|
||||
|
||||
|
||||
$routes->get('expenses/index', 'View\ExpenseController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('expenses/create', 'View\ExpenseController::create', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('expenses/store', 'View\ExpenseController::store', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->post('expenses/updateStatus', 'View\ExpenseController::updateStatus', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('expenses/index', 'View\ExpenseController::index');
|
||||
$routes->get('expenses/create', 'View\ExpenseController::create');
|
||||
$routes->post('expenses/store', 'View\ExpenseController::store');
|
||||
$routes->post('expenses/updateStatus', 'View\ExpenseController::updateStatus');
|
||||
|
||||
$routes->get('reimbursements/index', 'View\ReimbursementController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('reimbursements/create', 'View\ReimbursementController::create', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('reimbursements/store', 'View\ReimbursementController::store', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->get('reimbursements/under-processing', 'View\ReimbursementController::underProcessing', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('reimbursements/mark-donation', 'View\ReimbursementController::markDonation', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('reimbursements/batch/create', 'View\ReimbursementController::createBatch', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->post('reimbursements/batch/update', 'View\ReimbursementController::updateBatchAssignment', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('reimbursements/batch/lock', 'View\ReimbursementController::lockBatch', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->post('reimbursements/batch/admin-file/upload', 'View\ReimbursementController::uploadBatchAdminFile', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('reimbursements/batch/admin-file/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('reimbursements/batch/admin-file/(:segment)/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1/$2', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('reimbursements/batch/send', 'View\ReimbursementController::sendBatchEmail', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('reimbursements/batch/export', 'View\ReimbursementController::exportBatch', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('reimbursements/process', 'View\ReimbursementController::process', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('reimbursements/export', 'View\ReimbursementController::export', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('reimbursements', 'View\ReimbursementController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->get('reimbursements/index', 'View\ReimbursementController::index');
|
||||
$routes->get('reimbursements/create', 'View\ReimbursementController::create');
|
||||
$routes->post('reimbursements/store', 'View\ReimbursementController::store');
|
||||
$routes->get('reimbursements/under-processing', 'View\ReimbursementController::underProcessing');
|
||||
$routes->post('reimbursements/mark-donation', 'View\ReimbursementController::markDonation');
|
||||
$routes->post('reimbursements/batch/create', 'View\ReimbursementController::createBatch');
|
||||
$routes->post('reimbursements/batch/update', 'View\ReimbursementController::updateBatchAssignment');
|
||||
$routes->post('reimbursements/batch/lock', 'View\ReimbursementController::lockBatch');
|
||||
$routes->post('reimbursements/batch/admin-file/upload', 'View\ReimbursementController::uploadBatchAdminFile');
|
||||
$routes->get('reimbursements/batch/admin-file/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1');
|
||||
$routes->get('reimbursements/batch/admin-file/(:segment)/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1/$2');
|
||||
$routes->post('reimbursements/batch/send', 'View\ReimbursementController::sendBatchEmail');
|
||||
$routes->get('reimbursements/batch/export', 'View\ReimbursementController::exportBatch');
|
||||
$routes->post('reimbursements/process', 'View\ReimbursementController::process');
|
||||
$routes->get('reimbursements/export', 'View\ReimbursementController::export');
|
||||
$routes->get('reimbursements', 'View\ReimbursementController::index');
|
||||
|
||||
// Health check (upload dirs + DB timezone columns)
|
||||
$routes->get('admin/health', 'View\HealthController::index');
|
||||
@@ -746,9 +699,14 @@ $routes->get('payment_transactions/getByPayment/(:num)', 'View\PaymentTransactio
|
||||
$routes->get('payment_transactions/create', 'View\PaymentTransactionController::create');
|
||||
$routes->post('payment_transactions/updateStatus/(:num)', 'View\PaymentTransactionController::updateStatus/$1');
|
||||
|
||||
// Routes for payment pages
|
||||
// Routes for PayPal integration
|
||||
$routes->get('payments/createPaypalPayment/(:num)', 'View\PaymentController::createPaypalPayment/$1');
|
||||
$routes->get('payments/executePaypalPayment', 'View\PaymentController::executePaypalPayment');
|
||||
$routes->get('payments/cancelPaypalPayment', 'View\PaymentController::cancelPaypalPayment');
|
||||
|
||||
$routes->get('payments/view/(:num)', 'View\PaymentController::viewPayment/$1');
|
||||
$routes->get('payment/get_enrolled_students/(:num)', 'View\PaymentController::getEnrolledStudents/$1', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('payments/createPaypalPayment/(:num)', 'View\PaymentController::createPaypalPayment/$1');
|
||||
$routes->get('payment/get_enrolled_students/(:num)', 'View\PaymentController::getEnrolledStudents/$1');
|
||||
|
||||
// Payment Notification Management
|
||||
$routes->get('payment/notification_management', 'View\PaymentNotificationController::index', ['filter' => 'auth:view_invoice']);
|
||||
@@ -776,9 +734,6 @@ $routes->post('/administrator/teacher-submissions/notify', 'View\AdministratorCo
|
||||
$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/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']);
|
||||
|
||||
/*
|
||||
* --------------------------------------------------------------------
|
||||
@@ -968,6 +923,15 @@ $routes->group('inventory', ['filter' => 'csrf'], static function ($routes) {
|
||||
$routes->get('admin/enrollment/new-students', 'View\AdministratorController::showNewStudents', ['filter' => 'auth:view_new_students']);
|
||||
|
||||
|
||||
//Paypal transactions
|
||||
$routes->post('api/paypal-webhook', 'Api\PaypalWebhook::handle');
|
||||
$routes->get('administrator/paypal_transactions', 'View\PaypalTransactionsController::index');
|
||||
$routes->get('administrator/paypal_transactions/export', 'View\PaypalTransactionsController::exportCsv');
|
||||
$routes->get('admin/paypal-transactions', 'View\PaypalTransactionsController::index');
|
||||
$routes->get('admin/paypal-transactions/export', 'View\PaypalTransactionsController::exportCsv');
|
||||
|
||||
|
||||
|
||||
//Emergency Contact
|
||||
$routes->get('administrator/emergency_contact', 'View\EmergencyContactController::index');
|
||||
$routes->get('administrator/emergency_contact/edit/(:num)', 'View\EmergencyContactController::edit/$1');
|
||||
@@ -1038,24 +1002,22 @@ $routes->group('family', static function ($routes) {
|
||||
$routes->get('index', 'View\FamilyAdminController::index');
|
||||
$routes->get('search', 'View\FamilyAdminController::search');
|
||||
$routes->get('card', 'View\FamilyAdminController::card');
|
||||
$routes->get('compose-email', 'View\FamilyAdminController::composeEmail');
|
||||
$routes->post('compose-email/send', 'View\FamilyAdminController::sendComposeEmail');
|
||||
});
|
||||
// Convenience alias
|
||||
$routes->get('family', 'View\FamilyAdminController::index');
|
||||
//////////////////////////////////////////////////////////
|
||||
|
||||
//upload files
|
||||
$routes->get('receipts/(:any)', 'View\FilesController::receipt/$1', ['filter' => 'auth']);
|
||||
$routes->get('reimbreceipts/(:any)', 'View\FilesController::reimb/$1', ['filter' => 'auth']); // serves from writable/uploads/reimbursements
|
||||
$routes->get('receipts/(:any)', 'View\FilesController::receipt/$1');
|
||||
$routes->get('reimbreceipts/(:any)', 'View\FilesController::reimb/$1'); // serves from writable/uploads/reimbursements
|
||||
$routes->get('early-dismissal-signatures/(:any)', 'View\FilesController::earlyDismissalSignature/$1');
|
||||
// Expenses
|
||||
$routes->get('expenses/edit/(:num)', 'View\ExpenseController::edit/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('expenses/update/(:num)', 'View\ExpenseController::update/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('expenses/edit/(:num)', 'View\ExpenseController::edit/$1');
|
||||
$routes->post('expenses/update/(:num)', 'View\ExpenseController::update/$1');
|
||||
|
||||
// Reimbursements
|
||||
$routes->get('reimbursements/edit/(:num)', 'View\ReimbursementController::edit/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->post('reimbursements/update/(:num)', 'View\ReimbursementController::update/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('reimbursements/edit/(:num)', 'View\ReimbursementController::edit/$1');
|
||||
$routes->post('reimbursements/update/(:num)', 'View\ReimbursementController::update/$1');
|
||||
|
||||
|
||||
|
||||
@@ -1200,15 +1162,16 @@ $routes->get('/terms_of_service', 'View\PageController::termsOfService');
|
||||
$routes->get('/help_center', 'View\PageController::helpCenter');
|
||||
|
||||
//payment
|
||||
$routes->get('/payment', 'View\PaymentController::redirectPage', ['filter' => 'auth:parent']);
|
||||
$routes->get('/payment', 'View\PaymentController::redirectPage');
|
||||
$routes->get('/payment/paypal', 'View\PaymentController::paypal');
|
||||
$routes->get('/payment/manual', 'View\PaymentController::manual');
|
||||
$routes->post('/payment/manual', 'View\PaymentController::manual');
|
||||
|
||||
// Voucher management
|
||||
$routes->get('discounts/list', 'View\DiscountController::listVouchers', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||
$routes->match(['get', 'post'], 'discount/create', 'View\DiscountController::createVoucher', ['filter' => 'auth:create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||
$routes->match(['get', 'post'], 'discount/editVoucher/(:num)', 'View\DiscountController::editVoucher/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->match(['get', 'post'], 'discount/apply', 'View\DiscountController::applyVoucher', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||
$routes->get('discounts/list', 'View\DiscountController::listVouchers');
|
||||
$routes->match(['get', 'post'], 'discount/create', 'View\DiscountController::createVoucher');
|
||||
$routes->match(['get', 'post'], 'discount/editVoucher/(:num)', 'View\DiscountController::editVoucher/$1');
|
||||
$routes->match(['get', 'post'], 'discount/apply', 'View\DiscountController::applyVoucher');
|
||||
|
||||
|
||||
|
||||
@@ -1552,6 +1515,11 @@ $routes->group('api/v1', ['filter' => 'apiAuth', 'namespace' => 'App\Controllers
|
||||
$routes->get('class-preparation/(:num)', 'View\SupportController::show/$1');
|
||||
$routes->post('class-preparation/(:num)/mark-printed', 'View\SupportController::markPrinted/$1');
|
||||
|
||||
// PayPal Transactions
|
||||
$routes->get('paypal-transactions', 'View\UserController::index');
|
||||
$routes->get('paypal-transactions/(:num)', 'View\SupportController::show/$1');
|
||||
$routes->get('paypal-transactions/transaction/(:segment)', 'View\SupportController::getByTransactionId/$1');
|
||||
|
||||
// Stats
|
||||
$routes->get('stats', 'View\UserController::index');
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ class Services extends BaseService
|
||||
/**
|
||||
* 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) {
|
||||
return static::getSharedInstance('email', $config);
|
||||
|
||||
@@ -111,23 +111,6 @@ class AdminProgressController extends BaseController
|
||||
);
|
||||
$sectionStats = $this->buildSectionSubmissionStats($rows, $activeDatesSet, $expectedDays);
|
||||
$sectionSubjectCounts = $this->buildSectionSubjectCounts($rows);
|
||||
$lowProgressSectionIds = [];
|
||||
if ($expectedDays > 0) {
|
||||
foreach ($filteredSections as $section) {
|
||||
$sectionId = (int) ($section['class_section_id'] ?? 0);
|
||||
if ($sectionId === 0) {
|
||||
continue;
|
||||
}
|
||||
$stat = $sectionStats[$sectionId] ?? null;
|
||||
$percent = $stat['percent'] ?? 0;
|
||||
if ($stat === null) {
|
||||
$percent = 0;
|
||||
}
|
||||
if ($percent < 50) {
|
||||
$lowProgressSectionIds[] = $sectionId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return view('admin/class_progress_list', [
|
||||
'reportGroupsBySection' => $reportGroupsBySection,
|
||||
@@ -138,7 +121,6 @@ class AdminProgressController extends BaseController
|
||||
'sectionStats' => $sectionStats,
|
||||
'sectionSubjectCounts' => $sectionSubjectCounts,
|
||||
'expectedDays' => $expectedDays,
|
||||
'lowProgressSectionIds' => $lowProgressSectionIds,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -432,11 +414,13 @@ class AdminProgressController extends BaseController
|
||||
$allowedSubjects = array_values(array_filter($allowedSubjects));
|
||||
|
||||
$counts = [];
|
||||
$latestWeekBySection = [];
|
||||
$sectionClassMap = [];
|
||||
foreach ($rows as $row) {
|
||||
$sectionId = (int) ($row['class_section_id'] ?? 0);
|
||||
$subject = (string) ($row['subject'] ?? '');
|
||||
if ($sectionId === 0 || $subject === '') {
|
||||
$weekStart = (string) ($row['week_start'] ?? '');
|
||||
if ($sectionId === 0 || $subject === '' || $weekStart === '') {
|
||||
continue;
|
||||
}
|
||||
if (! empty($allowedSubjects) && ! in_array($subject, $allowedSubjects, true)) {
|
||||
@@ -445,41 +429,45 @@ class AdminProgressController extends BaseController
|
||||
if (! isset($sectionClassMap[$sectionId])) {
|
||||
$sectionClassMap[$sectionId] = $this->classSectionModel->getClassId($sectionId);
|
||||
}
|
||||
if (
|
||||
! isset($latestWeekBySection[$sectionId])
|
||||
|| $weekStart > $latestWeekBySection[$sectionId]
|
||||
) {
|
||||
$latestWeekBySection[$sectionId] = $weekStart;
|
||||
}
|
||||
}
|
||||
|
||||
$curriculumUnits = $this->buildCurriculumUnitMap(array_values(array_filter($sectionClassMap)));
|
||||
$curriculumChapters = $this->buildCurriculumChapterMap(array_values(array_filter($sectionClassMap)));
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$sectionId = (int) ($row['class_section_id'] ?? 0);
|
||||
$subject = (string) ($row['subject'] ?? '');
|
||||
if ($sectionId === 0 || $subject === '') {
|
||||
$weekStart = (string) ($row['week_start'] ?? '');
|
||||
if ($sectionId === 0 || $subject === '' || $weekStart === '') {
|
||||
continue;
|
||||
}
|
||||
if (! empty($allowedSubjects) && ! in_array($subject, $allowedSubjects, true)) {
|
||||
continue;
|
||||
}
|
||||
if (empty($latestWeekBySection[$sectionId]) || $weekStart !== $latestWeekBySection[$sectionId]) {
|
||||
continue;
|
||||
}
|
||||
$subjectSlug = $this->resolveSubjectSlug($subject);
|
||||
$classId = $sectionClassMap[$sectionId] ?? null;
|
||||
$chapterToUnit = [];
|
||||
if ($classId && $subjectSlug && ! empty($curriculumUnits[$classId][$subjectSlug]['chapter_to_unit'])) {
|
||||
$chapterToUnit = $curriculumUnits[$classId][$subjectSlug]['chapter_to_unit'];
|
||||
}
|
||||
$unitKeys = $this->extractUnitKeys((string) ($row['unit_title'] ?? ''), $chapterToUnit);
|
||||
foreach ($unitKeys as $unitKey) {
|
||||
$key = $subjectSlug . '|' . $unitKey;
|
||||
$counts[$sectionId][$key] = true;
|
||||
$chapterSet = [];
|
||||
if ($classId && $subjectSlug && ! empty($curriculumChapters[$classId][$subjectSlug])) {
|
||||
$chapterSet = $curriculumChapters[$classId][$subjectSlug];
|
||||
}
|
||||
$counts[$sectionId] = ($counts[$sectionId] ?? 0) + $this->countChapterSegments(
|
||||
(string) ($row['unit_title'] ?? ''),
|
||||
$chapterSet
|
||||
);
|
||||
}
|
||||
|
||||
$totals = [];
|
||||
foreach ($counts as $sectionId => $unitSet) {
|
||||
$totals[$sectionId] = count($unitSet);
|
||||
}
|
||||
|
||||
return $totals;
|
||||
return $counts;
|
||||
}
|
||||
|
||||
protected function buildCurriculumUnitMap(array $classIds): array
|
||||
protected function buildCurriculumChapterMap(array $classIds): array
|
||||
{
|
||||
$classIds = array_values(array_filter(array_map('intval', $classIds)));
|
||||
if (empty($classIds)) {
|
||||
@@ -495,15 +483,10 @@ class AdminProgressController extends BaseController
|
||||
$classId = (int) ($row['class_id'] ?? 0);
|
||||
$subject = (string) ($row['subject'] ?? '');
|
||||
$chapter = trim((string) ($row['chapter_name'] ?? ''));
|
||||
$unitNumber = $row['unit_number'] ?? null;
|
||||
if ($classId === 0 || $subject === '' || $chapter === '') {
|
||||
continue;
|
||||
}
|
||||
if ($unitNumber === null || $unitNumber === '') {
|
||||
continue;
|
||||
}
|
||||
$unitKey = (string) $unitNumber;
|
||||
$map[$classId][$subject]['chapter_to_unit'][$chapter] = $unitKey;
|
||||
$map[$classId][$subject][$chapter] = true;
|
||||
}
|
||||
|
||||
return $map;
|
||||
@@ -521,93 +504,46 @@ class AdminProgressController extends BaseController
|
||||
return null;
|
||||
}
|
||||
|
||||
protected function countUnitSegments(string $unitTitle, array $chapterToUnit): int
|
||||
protected function countChapterSegments(string $unitTitle, array $chapterSet): int
|
||||
{
|
||||
$unitTitle = trim($unitTitle);
|
||||
if ($unitTitle === '') {
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
$parts = array_filter(array_map('trim', explode(';', $unitTitle)), static fn ($part) => $part !== '');
|
||||
if (! $parts) {
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
$count = 0;
|
||||
$seen = [];
|
||||
foreach ($parts as $part) {
|
||||
[$unitPart, $chapterPart] = $this->splitUnitChapterSegment($part);
|
||||
$key = $this->resolveUnitKey($unitPart, $chapterPart, $chapterToUnit);
|
||||
if ($key === '') {
|
||||
$chapter = $this->extractChapterFromSegment($part);
|
||||
$key = $chapter !== '' ? $chapter : $part;
|
||||
if (! empty($chapterSet) && $chapter !== '' && empty($chapterSet[$chapter])) {
|
||||
$key = $part;
|
||||
}
|
||||
if (isset($seen[$key])) {
|
||||
continue;
|
||||
}
|
||||
$seen[$key] = true;
|
||||
$count++;
|
||||
}
|
||||
|
||||
return count($seen);
|
||||
return $count > 0 ? $count : 1;
|
||||
}
|
||||
|
||||
protected function splitUnitChapterSegment(string $segment): array
|
||||
protected function extractChapterFromSegment(string $segment): string
|
||||
{
|
||||
$segment = trim($segment);
|
||||
if ($segment === '') {
|
||||
return ['', ''];
|
||||
return '';
|
||||
}
|
||||
$pos = strrpos($segment, '/');
|
||||
if ($pos === false) {
|
||||
return [$segment, ''];
|
||||
return $segment;
|
||||
}
|
||||
$unitPart = trim(substr($segment, 0, $pos));
|
||||
$chapterPart = trim(substr($segment, $pos + 1));
|
||||
return [$unitPart, $chapterPart];
|
||||
}
|
||||
|
||||
protected function extractUnitKeys(string $unitTitle, array $chapterToUnit): array
|
||||
{
|
||||
$unitTitle = trim($unitTitle);
|
||||
if ($unitTitle === '') {
|
||||
return [];
|
||||
}
|
||||
$parts = array_filter(array_map('trim', explode(';', $unitTitle)), static fn ($part) => $part !== '');
|
||||
if (! $parts) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$keys = [];
|
||||
foreach ($parts as $part) {
|
||||
[$unitPart, $chapterPart] = $this->splitUnitChapterSegment($part);
|
||||
$key = $this->resolveUnitKey($unitPart, $chapterPart, $chapterToUnit);
|
||||
if ($key === '') {
|
||||
continue;
|
||||
}
|
||||
$keys[$key] = true;
|
||||
}
|
||||
|
||||
return array_keys($keys);
|
||||
}
|
||||
|
||||
protected function resolveUnitKey(string $unitPart, string $chapterPart, array $chapterToUnit): string
|
||||
{
|
||||
if ($chapterPart !== '' && ! empty($chapterToUnit[$chapterPart])) {
|
||||
return (string) $chapterToUnit[$chapterPart];
|
||||
}
|
||||
if (empty($chapterToUnit)) {
|
||||
if (preg_match('/\bunit\s*(\d+)\b/i', $unitPart, $matches)) {
|
||||
return (string) $matches[1];
|
||||
}
|
||||
return '';
|
||||
}
|
||||
if (preg_match('/\bunit\s*(\d+)\b/i', $unitPart, $matches)) {
|
||||
return (string) $matches[1];
|
||||
}
|
||||
if ($unitPart !== '') {
|
||||
return $unitPart;
|
||||
}
|
||||
if ($chapterPart !== '') {
|
||||
return $chapterPart;
|
||||
}
|
||||
return '';
|
||||
return trim(substr($segment, $pos + 1));
|
||||
}
|
||||
|
||||
protected function buildSectionStat(int $submitted, int $expectedDays): array
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Controllers;
|
||||
use App\Models\LoginActivityModel;
|
||||
use App\Models\UserModel;
|
||||
use App\Models\UserRoleModel;
|
||||
use CodeIgniter\Controller;
|
||||
use CodeIgniter\Events\Events;
|
||||
use App\Models\IpAttemptModel;
|
||||
use App\Models\PasswordResetModel;
|
||||
@@ -18,7 +19,7 @@ require_once APPPATH . 'Helpers/pbkdf2_helper.php';
|
||||
require_once APPPATH . 'Helpers/jwt_helper.php';
|
||||
|
||||
|
||||
class AuthController extends BaseController
|
||||
class AuthController extends Controller
|
||||
{
|
||||
protected $configModel;
|
||||
protected $userModel;
|
||||
@@ -55,50 +56,17 @@ class AuthController extends BaseController
|
||||
|
||||
public function loginMask()
|
||||
{
|
||||
$redirectTo = $this->sanitizeRedirectTarget((string) ($this->request->getGet('redirect_to') ?? ''));
|
||||
|
||||
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 ?? '',
|
||||
]);
|
||||
// Serve the login view directly here
|
||||
return view('user/login'); // Adjust the view path as needed
|
||||
}
|
||||
|
||||
public function login()
|
||||
{
|
||||
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
|
||||
$email = strtolower((string) $requestData['email']);
|
||||
$password = (string) $requestData['password'];
|
||||
$email = $this->request->getPost('email');
|
||||
$password = $this->request->getPost('password');
|
||||
$ip = $this->request->getIPAddress();
|
||||
|
||||
log_message('info', 'Login attempt from IP: ' . $ip . ' for email: ' . $email);
|
||||
@@ -130,7 +98,7 @@ class AuthController extends BaseController
|
||||
$this->logLoginAttempt($user['id'], $user['email'], $ip, $this->request->getUserAgent());
|
||||
|
||||
// ✅ Step 7: Call loginUser() to set session and redirect
|
||||
return $this->loginUser($user, $redirectTo);
|
||||
return $this->loginUser($user);
|
||||
} else {
|
||||
// Step 8: Password mismatch — log failed attempt
|
||||
$this->handleFailedLogin($user['id'], $user['email'], $ip);
|
||||
@@ -152,29 +120,26 @@ class AuthController extends BaseController
|
||||
// JSON API: POST /api/login
|
||||
public function apiLogin()
|
||||
{
|
||||
$requestData = sanitize_request_value($this->request->getJSON(true) ?: [
|
||||
'email' => $this->request->getPost('email'),
|
||||
'password' => $this->request->getPost('password'),
|
||||
]);
|
||||
|
||||
$validation = \Config\Services::validation();
|
||||
$validation->setRules([
|
||||
'email' => 'required|valid_email|max_length[254]',
|
||||
'password' => 'required|max_length[255]',
|
||||
]);
|
||||
|
||||
if (! $validation->run($requestData)) {
|
||||
return $this->response->setStatusCode(422)->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Validation failed.',
|
||||
'errors' => $validation->getErrors(),
|
||||
]);
|
||||
$requestData = $this->request->getJSON(true);
|
||||
if (!$requestData) {
|
||||
// fallback to form vars
|
||||
$requestData = [
|
||||
'email' => $this->request->getPost('email'),
|
||||
'password' => $this->request->getPost('password'),
|
||||
];
|
||||
}
|
||||
|
||||
$email = strtolower((string) ($requestData['email'] ?? ''));
|
||||
$password = (string) ($requestData['password'] ?? '');
|
||||
$email = $requestData['email'] ?? '';
|
||||
$password = $requestData['password'] ?? '';
|
||||
$ip = $this->request->getIPAddress();
|
||||
|
||||
if (!$email || !$password) {
|
||||
return $this->response->setStatusCode(400)->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'Email and password are required.'
|
||||
]);
|
||||
}
|
||||
|
||||
if ($this->isIpBlocked($ip)) {
|
||||
return $this->response->setStatusCode(429)->setJSON([
|
||||
'status' => false,
|
||||
@@ -236,15 +201,7 @@ class AuthController extends BaseController
|
||||
'exp' => $exp,
|
||||
];
|
||||
|
||||
try {
|
||||
$secret = require_env('JWT_SECRET');
|
||||
} catch (\RuntimeException $e) {
|
||||
return $this->response->setStatusCode(500)->setJSON([
|
||||
'status' => false,
|
||||
'message' => 'JWT configuration is missing.',
|
||||
]);
|
||||
}
|
||||
|
||||
$secret = env('JWT_SECRET', 'change-me-in-env');
|
||||
$token = jwt_encode($payload, $secret, 'HS256');
|
||||
|
||||
return $this->response->setJSON([
|
||||
@@ -264,14 +221,18 @@ class AuthController extends BaseController
|
||||
*/
|
||||
public function apiRegister()
|
||||
{
|
||||
$requestData = sanitize_request_value($this->request->getJSON(true) ?: $this->request->getPost());
|
||||
$requestData = $this->request->getJSON(true);
|
||||
if (!$requestData) {
|
||||
// fallback to form vars
|
||||
$requestData = $this->request->getPost();
|
||||
}
|
||||
|
||||
// Basic validation
|
||||
$rules = [
|
||||
'firstname' => "required|regex_match[/^[\\p{L}\\s'\\-]+$/u]|min_length[2]|max_length[30]",
|
||||
'lastname' => "required|regex_match[/^[\\p{L}\\s'\\-]+$/u]|min_length[2]|max_length[30]",
|
||||
'email' => 'required|valid_email|max_length[254]|is_unique[users.email]',
|
||||
'password' => 'required|min_length[8]|max_length[255]',
|
||||
'firstname' => 'required|min_length[2]|max_length[30]',
|
||||
'lastname' => 'required|min_length[2]|max_length[30]',
|
||||
'email' => 'required|valid_email|is_unique[users.email]',
|
||||
'password' => 'required|min_length[8]',
|
||||
'cellphone' => 'required|min_length[10]|max_length[20]',
|
||||
];
|
||||
|
||||
@@ -352,7 +313,7 @@ class AuthController extends BaseController
|
||||
'exp' => $exp,
|
||||
];
|
||||
|
||||
$secret = require_env('JWT_SECRET');
|
||||
$secret = env('JWT_SECRET', 'change-me-in-env');
|
||||
$token = jwt_encode($payload, $secret, 'HS256');
|
||||
|
||||
return $this->response->setStatusCode(201)->setJSON([
|
||||
@@ -508,7 +469,6 @@ class AuthController extends BaseController
|
||||
// Generate a secure token for the password reset
|
||||
helper('text');
|
||||
$token = bin2hex(random_bytes(48));
|
||||
$tokenHash = hash('sha256', $token);
|
||||
|
||||
// Calculate the expiration time for the token (1 hour from now)
|
||||
$expires_at = Time::now()->addHours(1);
|
||||
@@ -517,7 +477,7 @@ class AuthController extends BaseController
|
||||
$passwordResetModel = new PasswordResetModel();
|
||||
$passwordResetModel->insert([
|
||||
'email' => $email,
|
||||
'token' => $tokenHash,
|
||||
'token' => $token,
|
||||
'created_at' => Time::now(),
|
||||
'expires_at' => $expires_at,
|
||||
]);
|
||||
@@ -530,7 +490,7 @@ class AuthController extends BaseController
|
||||
return true;
|
||||
}
|
||||
|
||||
private function loginUser($user, ?string $redirectTo = null)
|
||||
private function loginUser($user)
|
||||
{
|
||||
$userRoleModel = new UserRoleModel();
|
||||
$roles = $userRoleModel->select('roles.name')
|
||||
@@ -564,17 +524,9 @@ class AuthController extends BaseController
|
||||
if (count($roleNames) === 1) {
|
||||
// One role → set and redirect directly
|
||||
session()->set('role', $roleNames[0]);
|
||||
if ($redirectTo !== null) {
|
||||
return redirect()->to($redirectTo);
|
||||
}
|
||||
return $this->redirectToDashboard([$roleNames[0]]);
|
||||
} else {
|
||||
// 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');
|
||||
}
|
||||
|
||||
@@ -639,17 +591,12 @@ private function redirectToDashboard(array $roles)
|
||||
{
|
||||
$selectedRole = $this->request->getPost('selected_role');
|
||||
$availableRoles = session()->get('roles');
|
||||
$redirectTo = $this->sanitizeRedirectTarget((string) ($this->request->getPost('redirect_to') ?? session()->get('post_login_redirect') ?? ''));
|
||||
|
||||
if (!$selectedRole || !in_array($selectedRole, $availableRoles)) {
|
||||
return redirect()->to('/select-role')->with('error', 'Invalid role selected.');
|
||||
}
|
||||
|
||||
session()->set('role', $selectedRole);
|
||||
session()->remove('post_login_redirect');
|
||||
if ($redirectTo !== null) {
|
||||
return redirect()->to($redirectTo);
|
||||
}
|
||||
return $this->redirectToDashboard([$selectedRole]);
|
||||
}
|
||||
|
||||
@@ -661,44 +608,7 @@ private function redirectToDashboard(array $roles)
|
||||
return redirect()->to('/login')->with('error', 'No roles available.');
|
||||
}
|
||||
|
||||
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;
|
||||
return view('auth/select_role', ['roles' => $roles]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ abstract class BaseController extends Controller
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
protected $helpers = ['security'];
|
||||
protected $helpers = [];
|
||||
|
||||
/** @var ApiClient */
|
||||
protected ApiClient $api;
|
||||
@@ -73,21 +73,6 @@ abstract class BaseController extends Controller
|
||||
// Assuming the user role is stored in the session
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
?>
|
||||
@@ -28,10 +28,6 @@ class ClassProgressController extends BaseController
|
||||
'db_subject' => 'Quran/Arabic',
|
||||
],
|
||||
];
|
||||
|
||||
/** Unit column for teacher custom Islamic / Quran rows; must match teacher form JS. Segment: "Custom / {text}". */
|
||||
public const CUSTOM_UNIT_ROW_LABEL = 'Custom';
|
||||
|
||||
protected ClassProgressReportModel $reportModel;
|
||||
protected ClassProgressAttachmentModel $attachmentModel;
|
||||
protected TeacherClassModel $teacherClassModel;
|
||||
@@ -102,10 +98,6 @@ class ClassProgressController extends BaseController
|
||||
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
|
||||
}
|
||||
|
||||
if (! $this->hasIslamicUnitSelection()) {
|
||||
return redirect()->back()->withInput()->with('error', 'Please select at least one Islamic Studies unit.');
|
||||
}
|
||||
|
||||
$attachmentErrors = $this->validateAttachmentFiles($subjectSections);
|
||||
if (! empty($attachmentErrors)) {
|
||||
return redirect()->back()->withInput()->with('errors', $attachmentErrors);
|
||||
@@ -127,32 +119,6 @@ class ClassProgressController extends BaseController
|
||||
return redirect()->back()->withInput()->with('error', 'No class assignment found for this report.');
|
||||
}
|
||||
|
||||
$confirmOverwrite = (bool) $this->request->getPost('confirm_overwrite');
|
||||
$existingReports = $this->reportModel
|
||||
->select('id')
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('week_start', $weekStart)
|
||||
->where('teacher_id', $teacherId)
|
||||
->findAll();
|
||||
|
||||
if (! $confirmOverwrite && ! empty($existingReports)) {
|
||||
return redirect()->back()
|
||||
->withInput()
|
||||
->with('warning', 'A progress report already exists for this week, are you sure you want to override it?')
|
||||
->with('confirm_overwrite', true);
|
||||
}
|
||||
|
||||
if ($confirmOverwrite && ! empty($existingReports)) {
|
||||
$existingIds = array_values(array_filter(array_map(
|
||||
static fn (array $row): int => (int) ($row['id'] ?? 0),
|
||||
$existingReports
|
||||
)));
|
||||
if (! empty($existingIds)) {
|
||||
$this->attachmentModel->whereIn('report_id', $existingIds)->delete();
|
||||
$this->reportModel->whereIn('id', $existingIds)->delete();
|
||||
}
|
||||
}
|
||||
|
||||
$status = self::DEFAULT_STATUS;
|
||||
|
||||
$reportsCreated = 0;
|
||||
@@ -310,262 +276,6 @@ class ClassProgressController extends BaseController
|
||||
]);
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$teacherId = (int) session()->get('user_id');
|
||||
$row = $this->reportModel
|
||||
->select('class_progress_reports.*, cs.class_section_name')
|
||||
->join('classSection cs', 'cs.class_section_id = class_progress_reports.class_section_id', 'left')
|
||||
->where('class_progress_reports.id', (int) $id)
|
||||
->first();
|
||||
|
||||
if (! $row) {
|
||||
throw new PageNotFoundException('Progress report not found.');
|
||||
}
|
||||
|
||||
[$semester, $schoolYear] = $this->resolveCurrentTerm();
|
||||
$allowedTeacherIds = $this->resolveAssignedTeacherIds((int) $row['class_section_id'], $semester, $schoolYear);
|
||||
if (empty($allowedTeacherIds)) {
|
||||
if ($teacherId !== (int) $row['teacher_id']) {
|
||||
throw new PageNotFoundException('Progress report not found.');
|
||||
}
|
||||
$allowedTeacherIds = [(int) $row['teacher_id']];
|
||||
} elseif (! in_array($teacherId, $allowedTeacherIds, true)) {
|
||||
throw new PageNotFoundException('Progress report not found.');
|
||||
}
|
||||
|
||||
$weeklyReports = $this->reportModel
|
||||
->select('class_progress_reports.*')
|
||||
->whereIn('teacher_id', $allowedTeacherIds)
|
||||
->where('class_section_id', $row['class_section_id'])
|
||||
->where('week_start', $row['week_start'])
|
||||
->orderBy('subject', 'ASC')
|
||||
->findAll();
|
||||
|
||||
$reportMap = [];
|
||||
foreach ($weeklyReports as $report) {
|
||||
$subject = (string) ($report['subject'] ?? '');
|
||||
if ($subject === '') {
|
||||
continue;
|
||||
}
|
||||
$reportMap[$subject] = $report;
|
||||
}
|
||||
|
||||
$subjectReports = [];
|
||||
foreach (self::SUBJECT_SECTIONS as $slug => $section) {
|
||||
$subjectName = $section['db_subject'] ?? $section['label'] ?? $slug;
|
||||
$report = $reportMap[$subjectName] ?? null;
|
||||
if (! $report) {
|
||||
continue;
|
||||
}
|
||||
$parsed = $this->parseUnitChapterSummary((string) ($report['unit_title'] ?? ''));
|
||||
$subjectReports[$slug] = [
|
||||
'report_id' => (int) ($report['id'] ?? 0),
|
||||
'covered' => $report['covered'] ?? '',
|
||||
'homework' => $report['homework'] ?? '',
|
||||
'unit_title' => $report['unit_title'] ?? '',
|
||||
'unit_values' => $parsed['units'],
|
||||
'chapter_values' => $parsed['chapters'],
|
||||
];
|
||||
}
|
||||
|
||||
$assignments = $this->loadTeacherSections($teacherId);
|
||||
$classId = null;
|
||||
$classSectionName = $row['class_section_name'] ?? '';
|
||||
foreach ($assignments as $assignment) {
|
||||
if ((int) ($assignment['class_section_id'] ?? 0) === (int) $row['class_section_id']) {
|
||||
$classId = $assignment['class_id'] ?? null;
|
||||
$classSectionName = $assignment['class_section_name'] ?? $classSectionName;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$subjectCurriculum = [];
|
||||
if ($classId) {
|
||||
foreach (self::SUBJECT_SECTIONS as $slug => $section) {
|
||||
$subjectCurriculum[$slug] = $this->curriculumModel->getOptionsForClass((int) $classId, $slug);
|
||||
}
|
||||
}
|
||||
|
||||
$sundayOptions = $this->buildSundayOptions();
|
||||
if (!in_array($row['week_start'], $sundayOptions, true)) {
|
||||
array_unshift($sundayOptions, $row['week_start']);
|
||||
}
|
||||
|
||||
return view('teacher/class_progress_submit', [
|
||||
'subjectSections' => self::SUBJECT_SECTIONS,
|
||||
'subjectCurriculum' => $subjectCurriculum,
|
||||
'classSectionId' => $row['class_section_id'],
|
||||
'classSectionName' => $classSectionName,
|
||||
'classId' => $classId,
|
||||
'sundayOptions' => $sundayOptions,
|
||||
'defaultWeekStart' => $row['week_start'],
|
||||
'existingWeekEnd' => $row['week_end'],
|
||||
'existingReports' => $subjectReports,
|
||||
'isEdit' => true,
|
||||
'formAction' => base_url('teacher/progress/update/' . (int) $row['id']),
|
||||
'submitLabel' => 'Update Progress',
|
||||
]);
|
||||
}
|
||||
|
||||
public function update($id)
|
||||
{
|
||||
$teacherId = (int) session()->get('user_id');
|
||||
$row = $this->reportModel->find((int) $id);
|
||||
if (! $row) {
|
||||
throw new PageNotFoundException('Progress report not found.');
|
||||
}
|
||||
|
||||
[$semester, $schoolYear] = $this->resolveCurrentTerm();
|
||||
$allowedTeacherIds = $this->resolveAssignedTeacherIds((int) $row['class_section_id'], $semester, $schoolYear);
|
||||
if (empty($allowedTeacherIds)) {
|
||||
if ($teacherId !== (int) $row['teacher_id']) {
|
||||
throw new PageNotFoundException('Progress report not found.');
|
||||
}
|
||||
$allowedTeacherIds = [(int) $row['teacher_id']];
|
||||
} elseif (! in_array($teacherId, $allowedTeacherIds, true)) {
|
||||
throw new PageNotFoundException('Progress report not found.');
|
||||
}
|
||||
|
||||
$subjectSections = self::SUBJECT_SECTIONS;
|
||||
$rules = [
|
||||
'class_section_id' => 'required|integer',
|
||||
'week_start' => 'required|valid_date[Y-m-d]',
|
||||
'week_end' => 'required|valid_date[Y-m-d]',
|
||||
];
|
||||
foreach ($subjectSections as $slug => $section) {
|
||||
$rules["covered_$slug"] = 'required|string';
|
||||
$rules["homework_$slug"] = 'permit_empty|string';
|
||||
$rules["unit_{$slug}.*"] = 'permit_empty|string|max_length[120]';
|
||||
$rules["chapter_{$slug}.*"] = 'permit_empty|string|max_length[120]';
|
||||
}
|
||||
|
||||
if (! $this->validate($rules)) {
|
||||
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
|
||||
}
|
||||
|
||||
if (! $this->hasIslamicUnitSelection()) {
|
||||
return redirect()->back()->withInput()->with('error', 'Please select at least one Islamic Studies unit.');
|
||||
}
|
||||
|
||||
$attachmentErrors = $this->validateAttachmentFiles($subjectSections);
|
||||
if (! empty($attachmentErrors)) {
|
||||
return redirect()->back()->withInput()->with('errors', $attachmentErrors);
|
||||
}
|
||||
|
||||
$weekStart = (string) $this->request->getPost('week_start');
|
||||
$weekEnd = (string) $this->request->getPost('week_end');
|
||||
if ($weekStart && ! $weekEnd) {
|
||||
$weekEnd = $this->buildWeekEndFromStart($weekStart);
|
||||
}
|
||||
if ($weekStart && $weekEnd && strtotime($weekEnd) < strtotime($weekStart)) {
|
||||
return redirect()->back()->withInput()->with('error', 'Week end must be the same as or after the week start.');
|
||||
}
|
||||
|
||||
$classSectionId = (int) ($row['class_section_id'] ?? 0);
|
||||
if ($classSectionId === 0) {
|
||||
return redirect()->back()->withInput()->with('error', 'No class assignment found for this report.');
|
||||
}
|
||||
|
||||
$confirmOverwrite = (bool) $this->request->getPost('confirm_overwrite');
|
||||
if ($weekStart && $weekStart !== (string) ($row['week_start'] ?? '')) {
|
||||
$conflicts = $this->reportModel
|
||||
->select('id')
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('week_start', $weekStart)
|
||||
->where('teacher_id', $teacherId)
|
||||
->findAll();
|
||||
if (! $confirmOverwrite && ! empty($conflicts)) {
|
||||
return redirect()->back()
|
||||
->withInput()
|
||||
->with('warning', 'A progress report already exists for this week, are you sure you want to override it?')
|
||||
->with('confirm_overwrite', true);
|
||||
}
|
||||
if ($confirmOverwrite && ! empty($conflicts)) {
|
||||
$conflictIds = array_values(array_filter(array_map(
|
||||
static fn (array $row): int => (int) ($row['id'] ?? 0),
|
||||
$conflicts
|
||||
)));
|
||||
if (! empty($conflictIds)) {
|
||||
$this->attachmentModel->whereIn('report_id', $conflictIds)->delete();
|
||||
$this->reportModel->whereIn('id', $conflictIds)->delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$weeklyReports = $this->reportModel
|
||||
->select('class_progress_reports.*')
|
||||
->whereIn('teacher_id', $allowedTeacherIds)
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('week_start', $row['week_start'])
|
||||
->orderBy('subject', 'ASC')
|
||||
->findAll();
|
||||
|
||||
$reportMap = [];
|
||||
foreach ($weeklyReports as $report) {
|
||||
$subject = (string) ($report['subject'] ?? '');
|
||||
if ($subject === '') {
|
||||
continue;
|
||||
}
|
||||
$reportMap[$subject] = $report;
|
||||
}
|
||||
|
||||
$reportsUpdated = 0;
|
||||
$flagsInput = $this->request->getPost('flags');
|
||||
foreach ($subjectSections as $slug => $section) {
|
||||
$covered = trim((string) $this->request->getPost("covered_$slug"));
|
||||
if ($covered === '') {
|
||||
continue;
|
||||
}
|
||||
$homework = trim((string) $this->request->getPost("homework_$slug"));
|
||||
$unitTitle = $this->buildUnitChapterSummary($slug);
|
||||
$subjectName = $section['db_subject'] ?? $section['label'] ?? $slug;
|
||||
$existing = $reportMap[$subjectName] ?? null;
|
||||
if ($unitTitle === null && $existing) {
|
||||
$unitTitle = $existing['unit_title'] ?? null;
|
||||
}
|
||||
|
||||
$data = [
|
||||
'class_section_id' => $classSectionId,
|
||||
'week_start' => $weekStart,
|
||||
'week_end' => $weekEnd,
|
||||
'subject' => $subjectName,
|
||||
'unit_title' => $unitTitle,
|
||||
'covered' => $covered,
|
||||
'homework' => $homework ?: null,
|
||||
];
|
||||
if ($flagsInput !== null) {
|
||||
$data['flags_json'] = $this->normalizeFlags($flagsInput);
|
||||
}
|
||||
|
||||
if ($existing) {
|
||||
$this->reportModel->update((int) $existing['id'], $data);
|
||||
$reportId = (int) $existing['id'];
|
||||
} else {
|
||||
$data['teacher_id'] = $teacherId;
|
||||
$data['status'] = self::DEFAULT_STATUS;
|
||||
$reportId = (int) $this->reportModel->insert($data, true);
|
||||
}
|
||||
|
||||
$attachmentField = "attachment_$slug";
|
||||
$attachments = $this->request->getFileMultiple($attachmentField) ?? [];
|
||||
$storedAttachments = $this->storeAttachments($reportId, $attachments);
|
||||
if (! empty($storedAttachments)) {
|
||||
$this->attachmentModel->insertBatch($storedAttachments);
|
||||
if (empty($existing['attachment_path'] ?? '')) {
|
||||
$this->reportModel->update($reportId, ['attachment_path' => $storedAttachments[0]['file_path']]);
|
||||
}
|
||||
}
|
||||
$reportsUpdated++;
|
||||
}
|
||||
|
||||
if ($reportsUpdated === 0) {
|
||||
return redirect()->back()->withInput()->with('error', 'Please provide progress for at least one subject.');
|
||||
}
|
||||
|
||||
return redirect()->to('teacher/progress/history')->with('success', 'Progress reports updated.');
|
||||
}
|
||||
|
||||
public function attachment($id)
|
||||
{
|
||||
$row = $this->reportModel->find((int)$id);
|
||||
@@ -709,37 +419,6 @@ class ClassProgressController extends BaseController
|
||||
return $flags ? json_encode($flags) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split stored unit_title into curriculum lines vs custom teacher-typed subjects ("Custom / …").
|
||||
* Keep in sync with teacher form, {@see buildUnitChapterSummary()}, and admin views.
|
||||
*
|
||||
* @return array{curriculum: list<string>, custom: list<string>}
|
||||
*/
|
||||
public static function splitUnitTitleForDisplay(string $unitTitle): array
|
||||
{
|
||||
$unitTitle = trim($unitTitle);
|
||||
if ($unitTitle === '') {
|
||||
return ['curriculum' => [], 'custom' => []];
|
||||
}
|
||||
|
||||
$segments = preg_split('/\s*;\s*/', $unitTitle, -1, PREG_SPLIT_NO_EMPTY);
|
||||
$curriculum = [];
|
||||
$custom = [];
|
||||
foreach ($segments as $seg) {
|
||||
$seg = trim((string) $seg);
|
||||
if ($seg === '') {
|
||||
continue;
|
||||
}
|
||||
if (preg_match('/^Custom\s*\/\s*(.+)$/iu', $seg, $m)) {
|
||||
$custom[] = trim($m[1]);
|
||||
} else {
|
||||
$curriculum[] = $seg;
|
||||
}
|
||||
}
|
||||
|
||||
return ['curriculum' => $curriculum, 'custom' => $custom];
|
||||
}
|
||||
|
||||
protected function buildUnitChapterSummary(string $slug): ?string
|
||||
{
|
||||
$unitValues = array_map('trim', (array) $this->request->getPost("unit_$slug"));
|
||||
@@ -752,12 +431,9 @@ class ClassProgressController extends BaseController
|
||||
if ($unit === '' && $chapter === '') {
|
||||
continue;
|
||||
}
|
||||
if (strcasecmp($unit, self::CUSTOM_UNIT_ROW_LABEL) === 0 && $chapter !== '') {
|
||||
$unit = self::CUSTOM_UNIT_ROW_LABEL;
|
||||
}
|
||||
$segment = $unit;
|
||||
if ($chapter !== '') {
|
||||
$segment = $segment !== '' ? $unit . ' / ' . $chapter : $chapter;
|
||||
$segment = $segment !== '' ? $segment . ' / ' . $chapter : $chapter;
|
||||
}
|
||||
if ($segment === '') {
|
||||
continue;
|
||||
@@ -768,64 +444,9 @@ class ClassProgressController extends BaseController
|
||||
return null;
|
||||
}
|
||||
$summary = implode(' ; ', $parts);
|
||||
|
||||
return mb_strlen($summary) > 120 ? mb_substr($summary, 0, 120) : $summary;
|
||||
}
|
||||
|
||||
protected function hasIslamicUnitSelection(): bool
|
||||
{
|
||||
$unitValues = array_map('trim', (array) $this->request->getPost('unit_islamic'));
|
||||
$chapterValues = array_map('trim', (array) $this->request->getPost('chapter_islamic'));
|
||||
$count = max(count($unitValues), count($chapterValues));
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$unit = $unitValues[$i] ?? '';
|
||||
$chapter = $chapterValues[$i] ?? '';
|
||||
if ($unit !== '' || $chapter !== '') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function parseUnitChapterSummary(string $summary): array
|
||||
{
|
||||
$summary = trim($summary);
|
||||
if ($summary === '') {
|
||||
return ['units' => [], 'chapters' => []];
|
||||
}
|
||||
|
||||
$units = [];
|
||||
$chapters = [];
|
||||
$segments = preg_split('/\s*;\s*/', $summary, -1, PREG_SPLIT_NO_EMPTY);
|
||||
foreach ($segments as $segment) {
|
||||
$segment = trim($segment);
|
||||
if ($segment === '') {
|
||||
continue;
|
||||
}
|
||||
if (preg_match('/^Custom\s*\/\s*(.+)$/iu', $segment, $m)) {
|
||||
$units[] = self::CUSTOM_UNIT_ROW_LABEL;
|
||||
$chapters[] = trim($m[1]);
|
||||
|
||||
continue;
|
||||
}
|
||||
$parts = preg_split('/\s*\/\s*/', $segment, 2);
|
||||
if (count($parts) === 2) {
|
||||
$u = trim($parts[0]);
|
||||
if (strcasecmp($u, self::CUSTOM_UNIT_ROW_LABEL) === 0) {
|
||||
$u = self::CUSTOM_UNIT_ROW_LABEL;
|
||||
}
|
||||
$units[] = $u;
|
||||
$chapters[] = trim($parts[1]);
|
||||
} else {
|
||||
$units[] = $segment;
|
||||
$chapters[] = '';
|
||||
}
|
||||
}
|
||||
|
||||
return ['units' => $units, 'chapters' => $chapters];
|
||||
}
|
||||
|
||||
protected function buildSundayOptions(int $count = 12): array
|
||||
{
|
||||
$range = $this->resolveProgressDateRange();
|
||||
|
||||
@@ -29,12 +29,18 @@ class ParentProgressController extends BaseController
|
||||
|
||||
public function index()
|
||||
{
|
||||
$students = $this->getParentStudents();
|
||||
$sectionIds = array_values(array_unique(array_filter(array_map(
|
||||
static fn (array $student): int => (int) ($student['class_section_id'] ?? 0),
|
||||
$students
|
||||
))));
|
||||
$sectionIds = $this->getParentSectionIds();
|
||||
$sectionOptions = $this->buildSectionOptions($sectionIds);
|
||||
$subjectSections = ClassProgressController::SUBJECT_SECTIONS;
|
||||
$selectedSectionId = (int) $this->request->getGet('class_section_id');
|
||||
$validSectionIds = array_keys($sectionOptions);
|
||||
|
||||
if ($selectedSectionId === 0 && ! empty($validSectionIds)) {
|
||||
$selectedSectionId = $validSectionIds[0];
|
||||
}
|
||||
if ($selectedSectionId && ! in_array($selectedSectionId, $validSectionIds, true)) {
|
||||
$selectedSectionId = $validSectionIds[0] ?? null;
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
if (! empty($sectionIds)) {
|
||||
@@ -44,32 +50,23 @@ class ParentProgressController extends BaseController
|
||||
->join('users u', 'u.id = class_progress_reports.teacher_id', 'left')
|
||||
->whereIn('class_progress_reports.class_section_id', $sectionIds);
|
||||
|
||||
if ($selectedSectionId) {
|
||||
$builder->where('class_progress_reports.class_section_id', $selectedSectionId);
|
||||
}
|
||||
|
||||
$rows = $builder
|
||||
->orderBy('week_start', 'DESC')
|
||||
->findAll();
|
||||
}
|
||||
|
||||
$studentReportGroups = [];
|
||||
foreach ($students as $student) {
|
||||
$studentId = (int) ($student['student_id'] ?? 0);
|
||||
if ($studentId === 0) {
|
||||
continue;
|
||||
}
|
||||
$classSectionId = (int) ($student['class_section_id'] ?? 0);
|
||||
$studentRows = $classSectionId
|
||||
? array_values(array_filter(
|
||||
$rows,
|
||||
static fn (array $row): bool => (int) ($row['class_section_id'] ?? 0) === $classSectionId
|
||||
))
|
||||
: [];
|
||||
$studentReportGroups[$studentId] = $this->groupReportsByWeek($studentRows);
|
||||
}
|
||||
$reportGroups = $this->groupReportsByWeek($rows);
|
||||
|
||||
return view('parent/class_progress_list', [
|
||||
'students' => $students,
|
||||
'studentReportGroups' => $studentReportGroups,
|
||||
'reportGroups' => $reportGroups,
|
||||
'subjectSections' => $subjectSections,
|
||||
'hasStudents' => ! empty($students),
|
||||
'classSectionOptions' => $sectionOptions,
|
||||
'selectedSectionId' => $selectedSectionId,
|
||||
'hasSections' => ! empty($sectionIds),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -201,53 +198,20 @@ class ParentProgressController extends BaseController
|
||||
return $options;
|
||||
}
|
||||
|
||||
protected function getParentStudents(): array
|
||||
{
|
||||
$parentId = (int) session()->get('user_id');
|
||||
if ($parentId === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->db->table('enrollments e')
|
||||
->select('e.student_id, e.class_section_id, e.updated_at, e.created_at, s.firstname, s.lastname, cs.class_section_name')
|
||||
->join('students s', 's.id = e.student_id')
|
||||
->join('classSection cs', 'cs.class_section_id = e.class_section_id', 'left')
|
||||
->where('e.parent_id', $parentId)
|
||||
->where('e.is_withdrawn', 0)
|
||||
->orderBy('e.updated_at', 'DESC')
|
||||
->orderBy('e.created_at', 'DESC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$students = [];
|
||||
foreach ($rows as $row) {
|
||||
$studentId = (int) ($row['student_id'] ?? 0);
|
||||
if ($studentId === 0 || isset($students[$studentId])) {
|
||||
continue;
|
||||
}
|
||||
$students[$studentId] = $row;
|
||||
}
|
||||
|
||||
return array_values($students);
|
||||
}
|
||||
|
||||
protected function groupReportsByWeek(array $rows): array
|
||||
{
|
||||
$reportGroups = [];
|
||||
foreach ($rows as $row) {
|
||||
$row['status_label'] = ClassProgressController::STATUS_OPTIONS[$row['status']] ?? 'Unknown';
|
||||
$weekStart = $row['week_start'] ?? '';
|
||||
$sectionId = (int) ($row['class_section_id'] ?? 0);
|
||||
if ($weekStart === '' || $sectionId === 0) {
|
||||
$key = $row['week_start'] ?? '';
|
||||
if ($key === '') {
|
||||
continue;
|
||||
}
|
||||
$key = $weekStart . ':' . $sectionId;
|
||||
if (! isset($reportGroups[$key])) {
|
||||
$reportGroups[$key] = [
|
||||
'week_start' => $row['week_start'] ?? '',
|
||||
'week_end' => $row['week_end'] ?? '',
|
||||
'class_section_name' => $row['class_section_name'] ?? '',
|
||||
'class_section_id' => $sectionId,
|
||||
'reports' => [],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -10,13 +10,8 @@ class ProofreadController extends ResourceController
|
||||
{
|
||||
// Basic per-IP throttling: 10 requests per minute
|
||||
$throttler = service('throttler');
|
||||
|
||||
// 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)) {
|
||||
$key = 'proofread-' . $this->request->getIPAddress();
|
||||
if (!$throttler->check($key, 10, MINUTE)) {
|
||||
return $this->respond([
|
||||
'ok' => false,
|
||||
'error' => 'Too many requests. Try again in a minute.',
|
||||
@@ -25,51 +20,29 @@ class ProofreadController extends ResourceController
|
||||
}
|
||||
|
||||
// Accept form-urlencoded payload to play nicely with CSRF protection
|
||||
$payload = sanitize_request_value($this->request->getPost(['text']));
|
||||
|
||||
$validation = service('validation');
|
||||
$validation->setRules([
|
||||
'text' => 'required|min_length[1]|max_length[20000]',
|
||||
]);
|
||||
|
||||
if (! $validation->run($payload)) {
|
||||
$text = (string) ($this->request->getPost('text') ?? '');
|
||||
if ($text === '' || mb_strlen($text) > 20000) {
|
||||
return $this->respond([
|
||||
'ok' => false,
|
||||
'error' => 'Invalid text payload.',
|
||||
'error' => 'Invalid text (empty or too long).',
|
||||
'csrfHash' => csrf_hash(),
|
||||
], 422);
|
||||
}
|
||||
|
||||
$text = (string) $payload['text'];
|
||||
|
||||
$client = \Config\Services::curlrequest([
|
||||
'timeout' => 10,
|
||||
]);
|
||||
$client = \Config\Services::curlrequest(['timeout' => 10]);
|
||||
|
||||
try {
|
||||
$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' => [
|
||||
'text' => $text,
|
||||
'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([
|
||||
'ok' => true,
|
||||
'result' => $result,
|
||||
'result' => json_decode($resp->getBody(), true),
|
||||
'csrfHash' => csrf_hash(),
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
@@ -80,4 +53,4 @@ class ProofreadController extends ResourceController
|
||||
], 502);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,8 +28,6 @@ use App\Models\ScoreCommentModel;
|
||||
use App\Models\SemesterScoreModel;
|
||||
use App\Models\TeacherClassModel;
|
||||
use App\Models\TeacherSubmissionNotificationHistoryModel;
|
||||
use App\Models\ExamDraftModel;
|
||||
use App\Models\HomeworkModel;
|
||||
use App\Services\SemesterRangeService;
|
||||
|
||||
use CodeIgniter\Events\Events;
|
||||
@@ -698,26 +696,15 @@ class AdministratorController extends BaseController
|
||||
|
||||
public function teacherSubmissionsReport()
|
||||
{
|
||||
$semester = (string)($this->configModel->getConfig('semester') ?? $this->semester ?? '');
|
||||
$schoolYear = (string)($this->configModel->getConfig('school_year') ?? $this->schoolYear ?? '');
|
||||
$semesterResolver = new SemesterRangeService($this->configModel);
|
||||
$semesterNorm = $semesterResolver->normalizeSemester($semester);
|
||||
$semesterFilter = $semesterNorm !== '' ? $semesterNorm : $semester;
|
||||
$semesterCandidates = $this->buildSemesterCandidates($semesterFilter);
|
||||
$lowProgressRaw = (string) $this->request->getGet('low_progress_sections');
|
||||
$lowProgressSectionIds = array_values(array_unique(array_filter(array_map(
|
||||
'intval',
|
||||
preg_split('/\s*,\s*/', $lowProgressRaw, -1, PREG_SPLIT_NO_EMPTY)
|
||||
))));
|
||||
$semester = (string)($this->semester ?? '');
|
||||
$schoolYear = (string)($this->schoolYear ?? '');
|
||||
|
||||
$scoreComments = new ScoreCommentModel();
|
||||
$semesterScores = new SemesterScoreModel();
|
||||
$attendanceDays = new AttendanceDayModel();
|
||||
$examDrafts = new ExamDraftModel();
|
||||
$homeworkModel = new HomeworkModel();
|
||||
$historyModel = new TeacherSubmissionNotificationHistoryModel();
|
||||
|
||||
$assignmentQuery = $this->db->table('teacher_class tc')
|
||||
$assignmentRows = $this->db->table('teacher_class tc')
|
||||
->select([
|
||||
'tc.class_section_id',
|
||||
'cs.class_section_name',
|
||||
@@ -728,97 +715,11 @@ class AdministratorController extends BaseController
|
||||
])
|
||||
->join('classSection cs', 'cs.class_section_id = tc.class_section_id', 'left')
|
||||
->join('users u', 'u.id = tc.teacher_id', 'left')
|
||||
->orderBy('cs.class_section_name', 'ASC');
|
||||
|
||||
$filteredQuery = clone $assignmentQuery;
|
||||
if ($schoolYear !== '') {
|
||||
$filteredQuery = $filteredQuery->where('tc.school_year', $schoolYear);
|
||||
}
|
||||
if (!empty($semesterCandidates)) {
|
||||
$filteredQuery = $filteredQuery->whereIn('tc.semester', $semesterCandidates);
|
||||
}
|
||||
|
||||
$assignmentRows = $filteredQuery->get()->getResultArray();
|
||||
if (empty($assignmentRows) && ($schoolYear !== '' || $semester !== '')) {
|
||||
$assignmentRows = $assignmentQuery->get()->getResultArray();
|
||||
}
|
||||
|
||||
$studentCounts = $this->studentClassModel->getStudentCountsBySection($schoolYear !== '' ? $schoolYear : null);
|
||||
$sectionRows = $this->classSectionModel
|
||||
->select('class_section_id, class_section_name')
|
||||
->orderBy('class_section_name', 'ASC')
|
||||
->findAll();
|
||||
$sectionMap = [];
|
||||
foreach ($sectionRows as $sectionRow) {
|
||||
$sectionId = (int) ($sectionRow['class_section_id'] ?? 0);
|
||||
if ($sectionId <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (empty($studentCounts[$sectionId])) {
|
||||
continue;
|
||||
}
|
||||
$sectionMap[$sectionId] = $sectionRow['class_section_name'] ?? "Section {$sectionId}";
|
||||
}
|
||||
$sectionIds = array_keys($sectionMap);
|
||||
|
||||
[$progressExpectedWeeks, $progressSubmittedBySection] = $this->buildClassProgressStats($sectionIds);
|
||||
$examDraftCounts = [];
|
||||
$examDraftDeadline = $this->resolveTeacherDashboardExamDraftDeadline($semester, $schoolYear);
|
||||
$examDraftDeadlineConfig = trim((string) ($this->configModel->getConfig('exam_draft_deadline') ?? ''));
|
||||
$examDraftDeadlineFormatted = '';
|
||||
if ($examDraftDeadlineConfig !== '') {
|
||||
$parsedUi = $this->parseExamDraftDeadlineConfigValue();
|
||||
$examDraftDeadlineFormatted = $parsedUi !== null ? $parsedUi->format('M j, Y') : '';
|
||||
}
|
||||
$homeworkCounts = [];
|
||||
if (! empty($sectionIds)) {
|
||||
$draftBuilder = $examDrafts
|
||||
->select('class_section_id')
|
||||
->whereIn('class_section_id', $sectionIds);
|
||||
if ($schoolYear !== '') {
|
||||
$draftBuilder->where('school_year', $schoolYear);
|
||||
}
|
||||
if (!empty($semesterCandidates)) {
|
||||
$draftBuilder->whereIn('semester', $semesterCandidates);
|
||||
}
|
||||
if ($this->db->fieldExists('is_legacy', 'exam_drafts')) {
|
||||
$draftBuilder->where('is_legacy', 0);
|
||||
}
|
||||
$draftRows = $draftBuilder->findAll();
|
||||
foreach ($draftRows as $draft) {
|
||||
$sectionId = (int) ($draft['class_section_id'] ?? 0);
|
||||
if ($sectionId <= 0) {
|
||||
continue;
|
||||
}
|
||||
$examDraftCounts[$sectionId] = ($examDraftCounts[$sectionId] ?? 0) + 1;
|
||||
}
|
||||
|
||||
$homeworkBuilder = $homeworkModel
|
||||
->select('class_section_id, homework_index')
|
||||
->whereIn('class_section_id', $sectionIds);
|
||||
if ($schoolYear !== '') {
|
||||
$homeworkBuilder->where('school_year', $schoolYear);
|
||||
}
|
||||
if (!empty($semesterCandidates)) {
|
||||
$homeworkBuilder->whereIn('semester', $semesterCandidates);
|
||||
}
|
||||
$homeworkRows = $homeworkBuilder
|
||||
->where('score IS NOT NULL', null, false)
|
||||
->where('score !=', '')
|
||||
->groupBy('class_section_id, homework_index')
|
||||
->findAll();
|
||||
foreach ($homeworkRows as $row) {
|
||||
$sectionId = (int) ($row['class_section_id'] ?? 0);
|
||||
if ($sectionId <= 0) {
|
||||
continue;
|
||||
}
|
||||
$homeworkCounts[$sectionId] = ($homeworkCounts[$sectionId] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($lowProgressSectionIds)) {
|
||||
$lowProgressSectionIds = $this->resolveLowProgressSectionIds($sectionIds);
|
||||
}
|
||||
->where('tc.school_year', $schoolYear)
|
||||
->where('tc.semester', $semester)
|
||||
->orderBy('cs.class_section_name', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$teachersBySection = [];
|
||||
foreach ($assignmentRows as $assignment) {
|
||||
@@ -844,7 +745,7 @@ class AdministratorController extends BaseController
|
||||
$entry = &$teachersBySection[$sectionId];
|
||||
if (!isset($entry)) {
|
||||
$entry = [
|
||||
'class_section' => $assignment['class_section_name'] ?? ($sectionMap[$sectionId] ?? "Section {$sectionId}"),
|
||||
'class_section' => $assignment['class_section_name'] ?? "Section {$sectionId}",
|
||||
'teachers' => [],
|
||||
];
|
||||
}
|
||||
@@ -864,49 +765,35 @@ class AdministratorController extends BaseController
|
||||
$missingItemCount = 0;
|
||||
$allTeacherIds = [];
|
||||
$allClassSectionIds = [];
|
||||
$examTerm = $this->resolveExamTermLabel($semester);
|
||||
$examScoreField = $examTerm === 'final' ? 'final_exam_score' : 'midterm_exam_score';
|
||||
|
||||
foreach ($sectionMap as $classSectionId => $sectionName) {
|
||||
foreach ($teachersBySection as $classSectionId => $section) {
|
||||
$classSectionId = (int)$classSectionId;
|
||||
if ($classSectionId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$studentQuery = $this->studentClassModel
|
||||
$studentEntries = $this->studentClassModel
|
||||
->select('student_id')
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear);
|
||||
if (!empty($semesterCandidates)) {
|
||||
$studentQuery->whereIn('semester', $semesterCandidates);
|
||||
}
|
||||
$studentEntries = $studentQuery->findAll();
|
||||
if (empty($studentEntries)) {
|
||||
$studentEntries = $this->studentClassModel
|
||||
->select('student_id')
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
}
|
||||
->where('semester', $semester)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
$studentIds = array_filter(array_map(static fn($entry) => (int)($entry['student_id'] ?? 0), $studentEntries));
|
||||
$expected = count($studentIds);
|
||||
|
||||
$midtermStudents = [];
|
||||
$participationStudents = [];
|
||||
if ($classSectionId > 0) {
|
||||
$scoreQuery = $semesterScores
|
||||
$scoreRecords = $semesterScores
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear);
|
||||
if (!empty($semesterCandidates)) {
|
||||
$scoreQuery->whereIn('semester', $semesterCandidates);
|
||||
}
|
||||
$scoreRecords = $scoreQuery->findAll();
|
||||
->where('semester', $semester)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
foreach ($scoreRecords as $score) {
|
||||
$sid = (int)($score['student_id'] ?? 0);
|
||||
if ($sid <= 0 || ($expected > 0 && !in_array($sid, $studentIds, true))) {
|
||||
continue;
|
||||
}
|
||||
$midtermValue = trim((string)($score[$examScoreField] ?? ''));
|
||||
$midtermValue = trim((string)($score['midterm_exam_score'] ?? ''));
|
||||
if ($midtermValue !== '') {
|
||||
$midtermStudents[$sid] = true;
|
||||
}
|
||||
@@ -920,15 +807,13 @@ class AdministratorController extends BaseController
|
||||
$midtermCommentStudents = [];
|
||||
$ptapCommentStudents = [];
|
||||
if (!empty($studentIds)) {
|
||||
$commentQuery = $scoreComments
|
||||
$comments = $scoreComments
|
||||
->select('student_id, score_type, comment')
|
||||
->whereIn('student_id', $studentIds)
|
||||
->where('semester', $semester)
|
||||
->where('school_year', $schoolYear)
|
||||
->whereIn('score_type', [$examTerm, 'ptap']);
|
||||
if (!empty($semesterCandidates)) {
|
||||
$commentQuery->whereIn('semester', $semesterCandidates);
|
||||
}
|
||||
$comments = $commentQuery->findAll();
|
||||
->whereIn('score_type', ['midterm', 'ptap'])
|
||||
->findAll();
|
||||
foreach ($comments as $comment) {
|
||||
$sid = (int)($comment['student_id'] ?? 0);
|
||||
if ($sid <= 0) {
|
||||
@@ -939,7 +824,7 @@ class AdministratorController extends BaseController
|
||||
continue;
|
||||
}
|
||||
$type = strtolower(trim((string)($comment['score_type'] ?? '')));
|
||||
if ($type === $examTerm) {
|
||||
if ($type === 'midterm') {
|
||||
$midtermCommentStudents[$sid] = true;
|
||||
}
|
||||
if ($type === 'ptap') {
|
||||
@@ -948,17 +833,14 @@ class AdministratorController extends BaseController
|
||||
}
|
||||
}
|
||||
|
||||
$attendanceQuery = $attendanceDays
|
||||
$attendanceRow = $attendanceDays
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('semester', $semester)
|
||||
->where('school_year', $schoolYear)
|
||||
->where('date', $today);
|
||||
if (!empty($semesterCandidates)) {
|
||||
$attendanceQuery->whereIn('semester', $semesterCandidates);
|
||||
}
|
||||
$attendanceRow = $attendanceQuery->first();
|
||||
->where('date', $today)
|
||||
->first();
|
||||
$attendanceSubmitted = $attendanceRow && in_array(strtolower((string)($attendanceRow['status'] ?? '')), ['submitted', 'published', 'finalized'], true);
|
||||
|
||||
$section = $teachersBySection[$classSectionId] ?? ['teachers' => []];
|
||||
$teacherList = $section['teachers'] ?? [];
|
||||
if (!empty($teacherList)) {
|
||||
usort($teacherList, function ($a, $b) {
|
||||
@@ -979,27 +861,18 @@ class AdministratorController extends BaseController
|
||||
$participationStatus = $this->submissionStatus(count($participationStudents), $expected);
|
||||
$ptapCommentStatus = $this->submissionStatus(count($ptapCommentStudents), $expected);
|
||||
$attendanceStatus = $this->attendanceStatus($attendanceSubmitted);
|
||||
$progressSubmitted = (int) ($progressSubmittedBySection[$classSectionId] ?? 0);
|
||||
$classProgressStatus = $this->progressStatus($progressSubmitted, $progressExpectedWeeks);
|
||||
$draftSubmitted = (int) ($examDraftCounts[$classSectionId] ?? 0);
|
||||
$examDraftStatus = $this->draftStatus($draftSubmitted, $examDraftDeadline);
|
||||
$homeworkSubmitted = (int) ($homeworkCounts[$classSectionId] ?? 0);
|
||||
$homeworkStatus = $this->homeworkStatus($homeworkSubmitted);
|
||||
$statusDetails = [
|
||||
'midterm_score_status' => $midtermScoreStatus,
|
||||
'midterm_comment_status' => $midtermCommentStatus,
|
||||
'participation_status' => $participationStatus,
|
||||
'ptap_comment_status' => $ptapCommentStatus,
|
||||
'class_progress_status' => $classProgressStatus,
|
||||
'exam_draft_status' => $examDraftStatus,
|
||||
'homework_status' => $homeworkStatus,
|
||||
];
|
||||
$missingItemsForSection = $this->buildMissingItems($statusDetails, $semester);
|
||||
$missingItemsForSection = $this->buildMissingItems($statusDetails);
|
||||
$missingItemCount += count($missingItemsForSection);
|
||||
$totalStatuses += count($statusDetails);
|
||||
|
||||
$rows[] = [
|
||||
'class_section' => $sectionMap[$classSectionId] ?? ($section['class_section'] ?? "Section {$classSectionId}"),
|
||||
'class_section' => $section['class_section'] ?? "Section {$classSectionId}",
|
||||
'class_section_id' => $classSectionId,
|
||||
'teachers' => $teacherList,
|
||||
'midterm_score_status' => $midtermScoreStatus,
|
||||
@@ -1007,9 +880,6 @@ class AdministratorController extends BaseController
|
||||
'participation_status' => $participationStatus,
|
||||
'ptap_comment_status' => $ptapCommentStatus,
|
||||
'attendance_status' => $attendanceStatus,
|
||||
'class_progress_status' => $classProgressStatus,
|
||||
'exam_draft_status' => $examDraftStatus,
|
||||
'homework_status' => $homeworkStatus,
|
||||
'missing_items' => $missingItemsForSection,
|
||||
'student_count' => $expected,
|
||||
];
|
||||
@@ -1071,183 +941,15 @@ class AdministratorController extends BaseController
|
||||
'schoolYear' => $schoolYear,
|
||||
'notificationHistory' => $historyMap,
|
||||
'summary' => $summary,
|
||||
'lowProgressSectionIds' => $lowProgressSectionIds,
|
||||
'examDraftDeadlineConfig' => $examDraftDeadlineConfig,
|
||||
'examDraftDeadlineFormatted' => $examDraftDeadlineFormatted,
|
||||
]);
|
||||
}
|
||||
|
||||
private function resolveLowProgressSectionIds(array $sectionIds): array
|
||||
{
|
||||
[$expectedWeeks, $submittedBySection] = $this->buildClassProgressStats($sectionIds);
|
||||
if ($expectedWeeks <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$lowProgressSectionIds = [];
|
||||
foreach ($sectionIds as $sectionId) {
|
||||
$submitted = (int) ($submittedBySection[$sectionId] ?? 0);
|
||||
$percent = ($submitted / $expectedWeeks) * 100;
|
||||
if ($percent < 50) {
|
||||
$lowProgressSectionIds[] = $sectionId;
|
||||
}
|
||||
}
|
||||
|
||||
return $lowProgressSectionIds;
|
||||
}
|
||||
|
||||
private function buildClassProgressStats(array $sectionIds): array
|
||||
{
|
||||
$sectionIds = array_values(array_unique(array_filter(array_map('intval', $sectionIds))));
|
||||
if (empty($sectionIds)) {
|
||||
return [0, []];
|
||||
}
|
||||
|
||||
$semesterResolver = new SemesterRangeService($this->configModel);
|
||||
$schoolYear = (string)($this->configModel->getConfig('school_year') ?? '');
|
||||
$semester = (string)($this->configModel->getConfig('semester') ?? '');
|
||||
$schoolYearForRange = $schoolYear !== '' ? $schoolYear : (string)($this->configModel->getConfig('school_year') ?? '');
|
||||
[$rangeStart, $rangeEnd] = $semesterResolver->getSchoolYearRange($schoolYearForRange);
|
||||
$semesterNorm = $semesterResolver->normalizeSemester($semester);
|
||||
if ($semesterNorm !== '' && $schoolYearForRange !== '') {
|
||||
$semRange = $semesterResolver->getSemesterRange($schoolYearForRange, $semesterNorm);
|
||||
if ($semRange) {
|
||||
[$rangeStart, $rangeEnd] = $semRange;
|
||||
}
|
||||
}
|
||||
|
||||
$dateList = [];
|
||||
try {
|
||||
$start = new \DateTimeImmutable($rangeStart);
|
||||
$end = new \DateTimeImmutable($rangeEnd);
|
||||
$cursor = $start;
|
||||
$w = (int) $cursor->format('w');
|
||||
if ($w !== 0) {
|
||||
$cursor = $cursor->modify('next sunday');
|
||||
}
|
||||
while ($cursor <= $end) {
|
||||
$dateList[] = $cursor->format('Y-m-d');
|
||||
$cursor = $cursor->modify('+7 days');
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$dateList = [];
|
||||
}
|
||||
|
||||
$noSchoolDays = [];
|
||||
$events = [];
|
||||
try {
|
||||
$calendarModel = new \App\Models\CalendarModel();
|
||||
$events = $calendarModel->getEvents();
|
||||
} catch (\Throwable $e) {
|
||||
$events = [];
|
||||
}
|
||||
foreach ($events as $event) {
|
||||
$d = substr((string) ($event['date'] ?? ''), 0, 10);
|
||||
if ($d === '' || empty($event['no_school'])) {
|
||||
continue;
|
||||
}
|
||||
if ($d < $rangeStart || $d > $rangeEnd) {
|
||||
continue;
|
||||
}
|
||||
$eventYear = trim((string) ($event['school_year'] ?? ''));
|
||||
if ($schoolYearForRange !== '' && $eventYear !== '' && $eventYear !== $schoolYearForRange) {
|
||||
continue;
|
||||
}
|
||||
$noSchoolDays[$d] = true;
|
||||
}
|
||||
|
||||
$anchorSundayYmd = '';
|
||||
try {
|
||||
$tzName = (string) (config('School')->attendance['timezone'] ?? user_timezone());
|
||||
$tzObj = new \DateTimeZone($tzName ?: 'UTC');
|
||||
} catch (\Throwable $e) {
|
||||
try {
|
||||
$tzObj = new \DateTimeZone(user_timezone() ?: 'UTC');
|
||||
} catch (\Throwable $e2) {
|
||||
$tzObj = new \DateTimeZone('UTC');
|
||||
}
|
||||
}
|
||||
try {
|
||||
$nowDate = new \DateTime('now', $tzObj);
|
||||
} catch (\Throwable $e) {
|
||||
$nowDate = new \DateTime('now');
|
||||
}
|
||||
$weekday = (int) $nowDate->format('w');
|
||||
$anchorSundayYmd = $weekday === 0
|
||||
? $nowDate->format('Y-m-d')
|
||||
: $nowDate->modify('next sunday')->format('Y-m-d');
|
||||
|
||||
$activeDatesSet = [];
|
||||
if (! empty($dateList) && $anchorSundayYmd !== '') {
|
||||
foreach ($dateList as $d) {
|
||||
if ($d <= $anchorSundayYmd && empty($noSchoolDays[$d])) {
|
||||
$activeDatesSet[$d] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
$expectedWeeks = count($activeDatesSet);
|
||||
if ($expectedWeeks === 0) {
|
||||
return [0, []];
|
||||
}
|
||||
|
||||
$builder = $this->db->table('class_progress_reports')
|
||||
->select('class_section_id, week_start')
|
||||
->whereIn('class_section_id', $sectionIds);
|
||||
if (! empty($activeDatesSet)) {
|
||||
$builder->whereIn('week_start', array_keys($activeDatesSet));
|
||||
}
|
||||
$rows = $builder->get()->getResultArray();
|
||||
|
||||
$submittedBySection = [];
|
||||
foreach ($rows as $row) {
|
||||
$sectionId = (int) ($row['class_section_id'] ?? 0);
|
||||
$weekStart = (string) ($row['week_start'] ?? '');
|
||||
if ($sectionId === 0 || $weekStart === '' || empty($activeDatesSet[$weekStart])) {
|
||||
continue;
|
||||
}
|
||||
$submittedBySection[$sectionId][$weekStart] = true;
|
||||
}
|
||||
|
||||
$counts = [];
|
||||
foreach ($sectionIds as $sectionId) {
|
||||
$counts[$sectionId] = isset($submittedBySection[$sectionId])
|
||||
? count($submittedBySection[$sectionId])
|
||||
: 0;
|
||||
}
|
||||
|
||||
return [$expectedWeeks, $counts];
|
||||
}
|
||||
|
||||
public function sendTeacherSubmissionNotifications()
|
||||
{$notify = $this->request->getPost('notify');
|
||||
if (!is_array($notify)) {
|
||||
return redirect()->back()->with('info', 'Select at least one teacher to notify.');
|
||||
}
|
||||
$semester = (string)($this->configModel->getConfig('semester') ?? $this->semester ?? '');
|
||||
$missingItemsPayload = $this->request->getPost('missing_items') ?? [];
|
||||
$homeworkNotifyAll = (bool) $this->request->getPost('homework_notify_all');
|
||||
$examTerm = $this->resolveExamTermLabel($semester);
|
||||
$examScoreLabel = $examTerm === 'final' ? 'final scores' : 'midterm scores';
|
||||
$examCommentLabel = $examTerm === 'final' ? 'final comments' : 'midterm comments';
|
||||
$forcedItems = [];
|
||||
if ($this->request->getPost('notify_midterm_score')) {
|
||||
$forcedItems[] = $examScoreLabel;
|
||||
}
|
||||
if ($this->request->getPost('notify_midterm_comment')) {
|
||||
$forcedItems[] = $examCommentLabel;
|
||||
}
|
||||
if ($this->request->getPost('notify_participation')) {
|
||||
$forcedItems[] = 'participation';
|
||||
}
|
||||
if ($this->request->getPost('notify_ptap_comment')) {
|
||||
$forcedItems[] = 'PTAP comments';
|
||||
}
|
||||
if ($this->request->getPost('notify_class_progress')) {
|
||||
$forcedItems[] = 'class progress';
|
||||
}
|
||||
if ($this->request->getPost('notify_exam_draft')) {
|
||||
$forcedItems[] = 'exam draft';
|
||||
}
|
||||
|
||||
$targets = [];
|
||||
foreach ($notify as $sectionIdRaw => $teachers) {
|
||||
@@ -1304,10 +1006,6 @@ class AdministratorController extends BaseController
|
||||
|
||||
$historyModel = new TeacherSubmissionNotificationHistoryModel();
|
||||
$scoreUrl = site_url('/');
|
||||
$progressUrl = site_url('teacher/progress/history');
|
||||
$examDraftUrl = site_url('teacher/exam-drafts');
|
||||
$homeworkUrl = site_url('teacher/addHomework');
|
||||
$examDraftDeadlineEmailHtml = $this->buildExamDraftDeadlineEmailHtml();
|
||||
$sentCount = 0;
|
||||
$failCount = 0;
|
||||
|
||||
@@ -1323,13 +1021,6 @@ class AdministratorController extends BaseController
|
||||
$subject = "Reminder: Complete submissions for {$sectionName}";
|
||||
$missingPayload = $missingItemsPayload[$classSectionId][$teacherId] ?? '';
|
||||
$missingItems = $this->parseMissingItemsPayload((string)$missingPayload);
|
||||
$selectedItems = $forcedItems;
|
||||
if ($homeworkNotifyAll && !in_array('homework', $selectedItems, true)) {
|
||||
$selectedItems[] = 'homework';
|
||||
}
|
||||
if (!empty($selectedItems)) {
|
||||
$missingItems = array_values(array_unique($selectedItems));
|
||||
}
|
||||
if (!empty($missingItems)) {
|
||||
$missingText = htmlspecialchars(
|
||||
$this->formatMissingItemsText($missingItems),
|
||||
@@ -1342,46 +1033,10 @@ class AdministratorController extends BaseController
|
||||
}
|
||||
|
||||
$subject = "Reminder: Complete submissions for {$sectionName}";
|
||||
$progressNote = '';
|
||||
if (in_array('class progress', $missingItems, true)) {
|
||||
$progressNote = "<p>Class progress submissions can be updated at <a href=\"{$progressUrl}\">Teacher Progress History</a>.</p>";
|
||||
}
|
||||
$examDraftNote = '';
|
||||
if (in_array('exam draft', $missingItems, true)) {
|
||||
$semesterLabel = strtolower(trim((string) $semester));
|
||||
if ($semesterLabel === 'fall') {
|
||||
$draftLabel = 'midterm exam draft';
|
||||
} elseif ($semesterLabel === 'spring') {
|
||||
$draftLabel = 'final exam draft';
|
||||
} else {
|
||||
$draftLabel = 'exam draft';
|
||||
}
|
||||
$examDraftNote = "<p>" . ucfirst($draftLabel) . " submissions can be updated at <a href=\"{$examDraftUrl}\">Teacher Exam Drafts</a>.</p>"
|
||||
. $examDraftDeadlineEmailHtml;
|
||||
}
|
||||
$homeworkNote = '';
|
||||
if (in_array('homework', $missingItems, true)) {
|
||||
$homeworkNote = "<p>Homework scores can be submitted at <a href=\"{$homeworkUrl}\">Teacher Homework</a>.</p>";
|
||||
}
|
||||
$hasScoreItems = (bool) array_intersect($missingItems, [
|
||||
'midterm scores',
|
||||
'midterm comments',
|
||||
'final scores',
|
||||
'final comments',
|
||||
'participation',
|
||||
'PTAP comments',
|
||||
'homework',
|
||||
]);
|
||||
$nonScoreOnly = ! empty($missingItems) && ! $hasScoreItems;
|
||||
$body = "<p>Dear {$teacherName},</p>"
|
||||
. "<p>Administration is gently reminding you to wrap up any remaining "
|
||||
. ($nonScoreOnly ? "submissions for {$sectionName}." : "score submissions, comments, and related items for {$sectionName}.")
|
||||
. "</p>"
|
||||
. "<p>Administration is gently reminding you to wrap up any remaining score submissions and/or comments for {$sectionName}.</p>"
|
||||
. $missingNote
|
||||
. $progressNote
|
||||
. $examDraftNote
|
||||
. $homeworkNote
|
||||
. ($nonScoreOnly ? '' : "<p>Visit <a href=\"{$scoreUrl}\">Teacher Score Submission</a> to address any remaining items.</p>")
|
||||
. "<p>Visit <a href=\"{$scoreUrl}\">Teacher Score Submission</a> to address any remaining items.</p>"
|
||||
. "<p>Thank you,<br>Al Rahma Administration</p>";
|
||||
|
||||
$email = $teacher['email'] ?? '';
|
||||
@@ -1443,170 +1098,6 @@ class AdministratorController extends BaseController
|
||||
];
|
||||
}
|
||||
|
||||
private function progressStatus(int $submitted, int $expected): array
|
||||
{
|
||||
if ($expected <= 0) {
|
||||
return [
|
||||
'label' => 'N/A',
|
||||
'badge' => 'bg-secondary',
|
||||
'detail' => '',
|
||||
'completed' => true,
|
||||
];
|
||||
}
|
||||
$completed = $submitted >= $expected;
|
||||
return [
|
||||
'label' => $completed ? 'Submitted' : 'Missing',
|
||||
'badge' => $completed ? 'bg-success' : 'bg-danger',
|
||||
'detail' => "{$submitted}/{$expected}",
|
||||
'completed' => $completed,
|
||||
];
|
||||
}
|
||||
|
||||
private function homeworkStatus(int $submitted): array
|
||||
{
|
||||
$completed = $submitted > 0;
|
||||
return [
|
||||
'label' => $completed ? 'Submitted' : 'Missing',
|
||||
'badge' => $completed ? 'bg-success' : 'bg-danger',
|
||||
'detail' => $completed ? (string) $submitted : '0',
|
||||
'completed' => $completed,
|
||||
];
|
||||
}
|
||||
|
||||
private function draftStatus(int $submitted, ?\DateTimeImmutable $deadline): array
|
||||
{
|
||||
if ($deadline !== null) {
|
||||
$today = new \DateTimeImmutable('today');
|
||||
if ($today < $deadline) {
|
||||
return [
|
||||
'label' => 'Pending',
|
||||
'badge' => 'bg-secondary',
|
||||
'detail' => 'Not due',
|
||||
'completed' => true,
|
||||
];
|
||||
}
|
||||
}
|
||||
$completed = $submitted > 0;
|
||||
return [
|
||||
'label' => $completed ? 'Submitted' : 'Missing',
|
||||
'badge' => $completed ? 'bg-success' : 'bg-danger',
|
||||
'detail' => $completed ? (string) $submitted : '0',
|
||||
'completed' => $completed,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Exam draft due date for the teacher submissions dashboard: prefers the configuration key
|
||||
* `exam_draft_deadline` (same as automated reminders); otherwise fall/spring exam deadlines.
|
||||
*/
|
||||
private function resolveTeacherDashboardExamDraftDeadline(string $semester, string $schoolYear): ?\DateTimeImmutable
|
||||
{
|
||||
$fromExamDraftKey = $this->parseExamDraftDeadlineConfigValue();
|
||||
if ($fromExamDraftKey !== null) {
|
||||
return $fromExamDraftKey;
|
||||
}
|
||||
|
||||
return $this->resolveExamDraftDeadline($semester, $schoolYear);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the `exam_draft_deadline` configuration value using the application timezone (midnight that calendar day).
|
||||
*/
|
||||
private function parseExamDraftDeadlineConfigValue(): ?\DateTimeImmutable
|
||||
{
|
||||
$raw = trim((string) ($this->configModel->getConfig('exam_draft_deadline') ?? ''));
|
||||
if ($raw === '') {
|
||||
return null;
|
||||
}
|
||||
$tz = new \DateTimeZone(config('App')->appTimezone ?? 'UTC');
|
||||
try {
|
||||
$deadline = new \DateTimeImmutable($raw, $tz);
|
||||
} catch (\Throwable $e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $deadline->setTime(0, 0, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML snippet for reminder emails when exam draft is included (deadline from exam_draft_deadline config).
|
||||
*/
|
||||
private function buildExamDraftDeadlineEmailHtml(): string
|
||||
{
|
||||
$raw = trim((string) ($this->configModel->getConfig('exam_draft_deadline') ?? ''));
|
||||
if ($raw === '') {
|
||||
return '';
|
||||
}
|
||||
$parsed = $this->parseExamDraftDeadlineConfigValue();
|
||||
$display = $parsed !== null
|
||||
? htmlspecialchars($parsed->format('l, F j, Y'), ENT_QUOTES, 'UTF-8')
|
||||
: htmlspecialchars($raw, ENT_QUOTES, 'UTF-8');
|
||||
$rawEsc = htmlspecialchars($raw, ENT_QUOTES, 'UTF-8');
|
||||
|
||||
return '<p><strong>Exam draft submission deadline</strong> (<code>exam_draft_deadline</code>): '
|
||||
. "<strong>{$display}</strong>"
|
||||
. ($parsed !== null && $rawEsc !== $display ? " <span style=\"color:#555;\">(configured value: {$rawEsc})</span>" : '')
|
||||
. '.</p>';
|
||||
}
|
||||
|
||||
private function resolveExamDraftDeadline(string $semester, string $schoolYear): ?\DateTimeImmutable
|
||||
{
|
||||
$semesterKey = strtolower(trim($semester));
|
||||
if ($semesterKey === 'fall') {
|
||||
$deadlineValue = (string)($this->configModel->getConfig('fall_exam_deadline') ?? '');
|
||||
} elseif ($semesterKey === 'spring') {
|
||||
$deadlineValue = (string)($this->configModel->getConfig('spring_exam_deadline') ?? '');
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
$deadlineValue = trim($deadlineValue);
|
||||
if ($deadlineValue === '') {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$deadline = new \DateTimeImmutable($deadlineValue);
|
||||
} catch (\Throwable $e) {
|
||||
return null;
|
||||
}
|
||||
if ($schoolYear !== '' && preg_match('/^\d{4}-\d{4}$/', $schoolYear)) {
|
||||
$deadlineYear = $deadline->format('Y');
|
||||
if ($deadlineYear === '1970') {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return $deadline->setTime(0, 0, 0);
|
||||
}
|
||||
|
||||
private function resolveExamTermLabel(string $semester): string
|
||||
{
|
||||
$semesterKey = strtolower(trim($semester));
|
||||
if ($semesterKey === '') {
|
||||
return 'midterm';
|
||||
}
|
||||
if (str_contains($semesterKey, 'spring')) {
|
||||
return 'final';
|
||||
}
|
||||
if (str_contains($semesterKey, 'fall')) {
|
||||
return 'midterm';
|
||||
}
|
||||
return 'midterm';
|
||||
}
|
||||
|
||||
private function buildSemesterCandidates(string $semester): array
|
||||
{
|
||||
$semester = trim((string) $semester);
|
||||
if ($semester === '') {
|
||||
return [];
|
||||
}
|
||||
$candidates = [
|
||||
$semester,
|
||||
strtolower($semester),
|
||||
strtoupper($semester),
|
||||
ucfirst(strtolower($semester)),
|
||||
];
|
||||
$candidates = array_values(array_unique(array_filter($candidates, static fn ($v) => $v !== '')));
|
||||
return $candidates;
|
||||
}
|
||||
private function attendanceStatus(bool $submitted): array
|
||||
{
|
||||
return [
|
||||
@@ -1616,20 +1107,14 @@ class AdministratorController extends BaseController
|
||||
];
|
||||
}
|
||||
|
||||
private function buildMissingItems(array $statusMap, string $semester): array
|
||||
private function buildMissingItems(array $statusMap): array
|
||||
{
|
||||
$examTerm = $this->resolveExamTermLabel($semester);
|
||||
$examScoreLabel = $examTerm === 'final' ? 'final scores' : 'midterm scores';
|
||||
$examCommentLabel = $examTerm === 'final' ? 'final comments' : 'midterm comments';
|
||||
$labels = [
|
||||
'midterm_score_status' => $examScoreLabel,
|
||||
'midterm_comment_status' => $examCommentLabel,
|
||||
'midterm_score_status' => 'midterm scores',
|
||||
'midterm_comment_status' => 'midterm comments',
|
||||
'participation_status' => 'participation',
|
||||
'ptap_comment_status' => 'PTAP comments',
|
||||
'attendance_status' => 'attendance',
|
||||
'class_progress_status' => 'class progress',
|
||||
'exam_draft_status' => 'exam draft',
|
||||
'homework_status' => 'homework',
|
||||
];
|
||||
|
||||
$items = [];
|
||||
|
||||
@@ -119,12 +119,7 @@ class AssignmentController extends BaseController
|
||||
}
|
||||
|
||||
$students = [];
|
||||
$seenStudentIds = [];
|
||||
foreach ($studentClasses as $studentClass) {
|
||||
$sid = (int)($studentClass['student_id'] ?? 0);
|
||||
if ($sid <= 0 || isset($seenStudentIds[$sid])) {
|
||||
continue;
|
||||
}
|
||||
if ($sectionSemester === '' && !empty($studentClass['semester'])) {
|
||||
$sectionSemester = (string)$studentClass['semester'];
|
||||
}
|
||||
@@ -154,7 +149,6 @@ class AssignmentController extends BaseController
|
||||
'tuition_paid' => esc($student['tuition_paid'] ? 'Yes' : 'No'),
|
||||
'school_id' => esc($student['school_id']),
|
||||
];
|
||||
$seenStudentIds[$sid] = true;
|
||||
}
|
||||
|
||||
$sectionSemesterDisplay = $sectionSemester !== '' ? $sectionSemester : ((string)($this->semester ?? ''));
|
||||
|
||||
@@ -1004,13 +1004,9 @@ public function showUpdateAttendanceForm()
|
||||
}
|
||||
|
||||
$hasRoster = false;
|
||||
$seenStudents = [];
|
||||
|
||||
foreach ($students as $sc) {
|
||||
$studentId = (int)$sc['student_id'];
|
||||
if ($studentId <= 0 || isset($seenStudents[$studentId])) {
|
||||
continue;
|
||||
}
|
||||
$student = $this->studentModel
|
||||
->select('id, firstname, lastname, school_id')
|
||||
->find($studentId);
|
||||
@@ -1018,7 +1014,6 @@ public function showUpdateAttendanceForm()
|
||||
|
||||
$studentsBySection[$secCode][] = $student;
|
||||
$hasRoster = true;
|
||||
$seenStudents[$studentId] = true;
|
||||
|
||||
// Attendance history
|
||||
$qb = $this->attendanceDataModel
|
||||
|
||||
@@ -2003,58 +2003,6 @@ class AttendanceTrackingController extends BaseController
|
||||
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()
|
||||
{
|
||||
@@ -2085,8 +2033,8 @@ class AttendanceTrackingController extends BaseController
|
||||
$rendered = $this->renderTemplate($code, $variant, $ctx);
|
||||
|
||||
if (!$rendered) {
|
||||
log_message('warning', 'Attendance email template missing; using fallback compose body. code=' . $code . ' variant=' . $variant);
|
||||
$rendered = $this->buildFallbackTemplate($code, $variant, $ctx);
|
||||
return redirect()->to(site_url('attendance/violations'))
|
||||
->with('error', 'Template not found for ' . $code . ' (' . $variant . ').');
|
||||
}
|
||||
|
||||
[$subject, $body] = $rendered;
|
||||
|
||||
@@ -10,8 +10,6 @@ use CodeIgniter\I18n\Time;
|
||||
|
||||
class AuthorizedUsersController extends ResourceController
|
||||
{
|
||||
private const TOKEN_TTL_HOURS = 24;
|
||||
|
||||
protected $userModel;
|
||||
protected $authorizedUserModel;
|
||||
|
||||
@@ -20,30 +18,6 @@ class AuthorizedUsersController extends ResourceController
|
||||
$this->userModel = new UserModel();
|
||||
$this->authorizedUserModel = new AuthorizedUserModel();
|
||||
}
|
||||
|
||||
private function requireLogin()
|
||||
{
|
||||
if (!session()->get('is_logged_in')) {
|
||||
return $this->failUnauthorized('Authentication required.');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function requireOwnership(array $authorizedUser)
|
||||
{
|
||||
$userId = (int) session()->get('user_id');
|
||||
if ($userId <= 0 || (int) ($authorizedUser['user_id'] ?? 0) !== $userId) {
|
||||
return $this->failForbidden('You do not have access to this resource.');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function hashToken(string $token): string
|
||||
{
|
||||
return hash('sha256', $token);
|
||||
}
|
||||
/**
|
||||
* Return a list of authorized users for the logged-in main user.
|
||||
*
|
||||
@@ -51,10 +25,7 @@ class AuthorizedUsersController extends ResourceController
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
if ($resp = $this->requireLogin()) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
|
||||
$userId = session()->get('user_id');
|
||||
$authorizedUsers = $this->authorizedUserModel->where('user_id', $userId)->findAll();
|
||||
|
||||
@@ -69,20 +40,12 @@ class AuthorizedUsersController extends ResourceController
|
||||
*/
|
||||
public function show($id = null)
|
||||
{
|
||||
if ($resp = $this->requireLogin()) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
$authorizedUser = $this->authorizedUserModel->find($id);
|
||||
|
||||
if (!$authorizedUser) {
|
||||
return $this->failNotFound('Authorized user not found.');
|
||||
}
|
||||
|
||||
if ($resp = $this->requireOwnership($authorizedUser)) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
return $this->respond($authorizedUser);
|
||||
}
|
||||
|
||||
@@ -93,10 +56,6 @@ class AuthorizedUsersController extends ResourceController
|
||||
*/
|
||||
public function create()
|
||||
{
|
||||
if ($resp = $this->requireLogin()) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
$email = strtolower($this->request->getPost('email'));
|
||||
|
||||
// Validate email
|
||||
@@ -107,20 +66,19 @@ class AuthorizedUsersController extends ResourceController
|
||||
$user = $this->userModel->where('email', $email)->first();
|
||||
|
||||
if (!$user) {
|
||||
return $this->respondCreated(['message' => 'Authorized user added. A confirmation email has been sent.']);
|
||||
return $this->failNotFound('No user found with this email.');
|
||||
}
|
||||
|
||||
// Generate a token for confirmation
|
||||
helper('text');
|
||||
$token = bin2hex(random_bytes(48));
|
||||
$tokenHash = $this->hashToken($token);
|
||||
|
||||
// Add entry to the authorized_users table
|
||||
$this->authorizedUserModel->insert([
|
||||
'user_id' => session()->get('user_id'), // Main user ID
|
||||
'authorized_user_id' => $user['id'],
|
||||
'email' => $email,
|
||||
'token' => $tokenHash,
|
||||
'token' => $token,
|
||||
'status' => 'Pending'
|
||||
]);
|
||||
|
||||
@@ -138,10 +96,6 @@ class AuthorizedUsersController extends ResourceController
|
||||
*/
|
||||
public function update($id = null)
|
||||
{
|
||||
if ($resp = $this->requireLogin()) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
// Fetch the authorized user
|
||||
$authorizedUser = $this->authorizedUserModel->find($id);
|
||||
|
||||
@@ -149,10 +103,6 @@ class AuthorizedUsersController extends ResourceController
|
||||
return $this->failNotFound('Authorized user not found.');
|
||||
}
|
||||
|
||||
if ($resp = $this->requireOwnership($authorizedUser)) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
// Update the authorized user’s information (e.g., email)
|
||||
$email = strtolower($this->request->getPost('email'));
|
||||
if ($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
@@ -172,20 +122,12 @@ class AuthorizedUsersController extends ResourceController
|
||||
*/
|
||||
public function delete($id = null)
|
||||
{
|
||||
if ($resp = $this->requireLogin()) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
$authorizedUser = $this->authorizedUserModel->find($id);
|
||||
|
||||
if (!$authorizedUser) {
|
||||
return $this->failNotFound('Authorized user not found.');
|
||||
}
|
||||
|
||||
if ($resp = $this->requireOwnership($authorizedUser)) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
// Delete the authorized user record
|
||||
$this->authorizedUserModel->delete($id);
|
||||
|
||||
@@ -205,28 +147,16 @@ class AuthorizedUsersController extends ResourceController
|
||||
return $this->fail('Invalid confirmation link.');
|
||||
}
|
||||
|
||||
$tokenHash = $this->hashToken($token);
|
||||
$authorizedUser = $this->authorizedUserModel
|
||||
->groupStart()
|
||||
->where('token', $tokenHash)
|
||||
->orWhere('token', $token)
|
||||
->groupEnd()
|
||||
->where('created_at >=', Time::now()->subHours(self::TOKEN_TTL_HOURS)->toDateTimeString())
|
||||
->first();
|
||||
$authorizedUser = $this->authorizedUserModel->where('token', $token)->first();
|
||||
|
||||
if (!$authorizedUser) {
|
||||
return $this->fail('Invalid or expired confirmation link.');
|
||||
}
|
||||
|
||||
// Mark the authorized user as active and rotate token for password setup
|
||||
$nextToken = bin2hex(random_bytes(48));
|
||||
$nextTokenHash = $this->hashToken($nextToken);
|
||||
$this->authorizedUserModel->update($authorizedUser['id'], [
|
||||
'status' => 'Active',
|
||||
'token' => $nextTokenHash,
|
||||
]);
|
||||
// Mark the authorized user as active
|
||||
$this->authorizedUserModel->update($authorizedUser['id'], ['status' => 'Active', 'token' => null]);
|
||||
|
||||
return redirect()->to('/set_authorized_user_password/' . $authorizedUser['authorized_user_id'] . '?token=' . $nextToken);
|
||||
return redirect()->to('/set_authorized_user_password/' . $authorizedUser['authorized_user_id']);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -237,36 +167,13 @@ class AuthorizedUsersController extends ResourceController
|
||||
*/
|
||||
public function setPassword($authorizedUserId)
|
||||
{
|
||||
$token = (string) $this->request->getGet('token');
|
||||
if ($token === '') {
|
||||
return $this->fail('Invalid confirmation link.');
|
||||
}
|
||||
|
||||
$tokenHash = $this->hashToken($token);
|
||||
$authorizedUser = $this->authorizedUserModel
|
||||
->groupStart()
|
||||
->where('token', $tokenHash)
|
||||
->orWhere('token', $token)
|
||||
->groupEnd()
|
||||
->where('authorized_user_id', $authorizedUserId)
|
||||
->where('status', 'Active')
|
||||
->where('updated_at >=', Time::now()->subHours(self::TOKEN_TTL_HOURS)->toDateTimeString())
|
||||
->first();
|
||||
|
||||
if (!$authorizedUser) {
|
||||
return $this->fail('Invalid or expired confirmation link.');
|
||||
}
|
||||
|
||||
$user = $this->userModel->find($authorizedUserId);
|
||||
|
||||
if (!$user) {
|
||||
return $this->failNotFound('User not found.');
|
||||
}
|
||||
|
||||
return view('user/set_authorized_user_password', [
|
||||
'userId' => $authorizedUserId,
|
||||
'token' => $token,
|
||||
]);
|
||||
return view('user/set_authorized_user_password', ['userId' => $authorizedUserId]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,59 +181,38 @@ class AuthorizedUsersController extends ResourceController
|
||||
*
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function savePassword($authorizedUserId = null)
|
||||
/*
|
||||
public function savePassword()
|
||||
{
|
||||
// Validate the request
|
||||
$validation = \Config\Services::validation();
|
||||
$validation->setRules([
|
||||
'password' => [
|
||||
'label' => 'Password',
|
||||
'rules' => 'required|min_length[8]|regex_match[/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@\\-=\\+*#$%&!?])[A-Za-z\\d@\\-=\\+*#$%&!?]{8,}$/]',
|
||||
],
|
||||
'password' => 'required|min_length[6]',
|
||||
'password_confirm' => 'required|matches[password]',
|
||||
'user_id' => 'required|integer',
|
||||
'token' => 'required',
|
||||
'user_id' => 'required|integer'
|
||||
]);
|
||||
|
||||
if (!$this->validate($validation->getRules())) {
|
||||
return $this->failValidationErrors($validation->getErrors());
|
||||
}
|
||||
|
||||
$userId = (int) $this->request->getPost('user_id');
|
||||
$token = (string) $this->request->getPost('token');
|
||||
$authorizedUserId = $authorizedUserId !== null ? (int) $authorizedUserId : $userId;
|
||||
// Get the validated input
|
||||
$userId = $this->request->getPost('user_id');
|
||||
$password = $this->request->getPost('password');
|
||||
|
||||
if ($userId <= 0 || $authorizedUserId <= 0 || $userId !== $authorizedUserId) {
|
||||
return $this->fail('Invalid request.');
|
||||
}
|
||||
$model = new UserModel();
|
||||
$user = $model->find($userId);
|
||||
|
||||
$tokenHash = $this->hashToken($token);
|
||||
$authorizedUser = $this->authorizedUserModel
|
||||
->groupStart()
|
||||
->where('token', $tokenHash)
|
||||
->orWhere('token', $token)
|
||||
->groupEnd()
|
||||
->where('authorized_user_id', $authorizedUserId)
|
||||
->where('status', 'Active')
|
||||
->where('updated_at >=', Time::now()->subHours(self::TOKEN_TTL_HOURS)->toDateTimeString())
|
||||
->first();
|
||||
|
||||
if (!$authorizedUser) {
|
||||
return $this->fail('Invalid or expired confirmation link.');
|
||||
}
|
||||
|
||||
$user = $this->userModel->find($authorizedUserId);
|
||||
if (!$user) {
|
||||
return $this->failNotFound('User not found.');
|
||||
}
|
||||
|
||||
$password = (string) $this->request->getPost('password');
|
||||
$hashedPassword = pbkdf2_hash($password);
|
||||
|
||||
$this->userModel->update($authorizedUserId, ['password' => $hashedPassword]);
|
||||
$this->authorizedUserModel->update($authorizedUser['id'], ['token' => null]);
|
||||
// Save the password
|
||||
$model->update($userId, ['password' => password_hash($password, PASSWORD_DEFAULT)]);
|
||||
|
||||
return $this->respond(['message' => 'Password has been successfully set.']);
|
||||
}
|
||||
*/
|
||||
/**
|
||||
* Sends a confirmation email to the authorized user.
|
||||
*
|
||||
@@ -356,4 +242,4 @@ class AuthorizedUsersController extends ResourceController
|
||||
log_message('error', 'Failed to send authorized user confirmation email to ' . $email);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,664 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
@@ -24,10 +24,10 @@ class ContactController extends BaseController
|
||||
|
||||
// Define validation rules
|
||||
$validation->setRules([
|
||||
'name' => "required|regex_match[/^[\\p{L}\\s'\\-]+$/u]|min_length[3]|max_length[100]",
|
||||
'email' => 'required|valid_email|max_length[254]',
|
||||
'subject' => 'required|min_length[3]|max_length[150]',
|
||||
'message' => 'required|min_length[10]|max_length[5000]'
|
||||
'name' => 'required|min_length[3]',
|
||||
'email' => 'required|valid_email',
|
||||
'subject' => 'required|min_length[3]',
|
||||
'message' => 'required|min_length[10]'
|
||||
]);
|
||||
|
||||
if (!$validation->withRequest($this->request)->run()) {
|
||||
@@ -37,10 +37,10 @@ class ContactController extends BaseController
|
||||
}
|
||||
|
||||
// Process form data
|
||||
$name = esc((string) $this->request->getPost('name'));
|
||||
$email = esc(strtolower((string) $this->request->getPost('email')));
|
||||
$subject = esc((string) $this->request->getPost('subject'));
|
||||
$message = nl2br(esc((string) $this->request->getPost('message')));
|
||||
$name = $this->request->getPost('name');
|
||||
$email = strtolower($this->request->getPost('email'));
|
||||
$subject = $this->request->getPost('subject');
|
||||
$message = $this->request->getPost('message');
|
||||
|
||||
// Initialize the EmailController
|
||||
$emailController = new \App\Controllers\View\EmailController();
|
||||
@@ -63,4 +63,4 @@ class ContactController extends BaseController
|
||||
|
||||
return redirect()->to('/parent/contact');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
namespace App\Controllers\View;
|
||||
use App\Controllers\BaseController;
|
||||
use App\Libraries\InvoiceLedgerService;
|
||||
use App\Models\DiscountVoucherModel;
|
||||
use App\Models\DiscountUsageModel;
|
||||
use App\Models\InvoiceModel;
|
||||
@@ -29,7 +28,6 @@ class DiscountController extends BaseController
|
||||
protected $eventChargesModel;
|
||||
protected $additionalChargeModel;
|
||||
protected $classSectionModel;
|
||||
protected $invoiceLedgerService;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
@@ -43,7 +41,6 @@ class DiscountController extends BaseController
|
||||
$this->eventChargesModel = new EventChargesModel();
|
||||
$this->additionalChargeModel = new AdditionalChargeModel();
|
||||
$this->classSectionModel = new ClassSectionModel();
|
||||
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||
|
||||
$this->schoolYear = $this->configModel->getConfig('school_year');
|
||||
$this->semester = $this->configModel->getConfig('semester');
|
||||
@@ -124,8 +121,6 @@ class DiscountController extends BaseController
|
||||
foreach ($invoices as $invoice) {
|
||||
if ($remainingUses <= 0) break 2; // out of parentIds loop too
|
||||
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $invoice['id']]);
|
||||
|
||||
// Snapshot current balance BEFORE applying
|
||||
$initialPreBalance = (float) $this->getCurrentInvoiceBalance($invoice['id'], $this->schoolYear);
|
||||
if ($initialPreBalance <= 0) {
|
||||
@@ -206,9 +201,22 @@ class DiscountController extends BaseController
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
$ledger = $this->invoiceLedgerService->recalculateInvoice((int) $invoice['id']);
|
||||
$postBalance = (float) ($ledger['balance'] ?? 0.0);
|
||||
$currentBalance = $postBalance;
|
||||
// Update invoice balance based on pre-discount snapshot (supports multiple discounts)
|
||||
$newBalance = max(0.0, round($initialPreBalance - $discount, 2));
|
||||
$this->db->table('invoices')
|
||||
->where('id', $invoice['id'])
|
||||
->update([
|
||||
'balance' => $newBalance,
|
||||
'has_discount' => 1,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
|
||||
// Compute post-balance based on pre-snapshot (more stable than $invoice['balance'])
|
||||
$postBalance = round($initialPreBalance - $discount, 2);
|
||||
if ($postBalance < 0) $postBalance = 0.0;
|
||||
|
||||
// (Optional) current balance re-check (in case of concurrent writes)
|
||||
$currentBalance = (float) $this->getCurrentInvoiceBalance($invoice['id'], $this->schoolYear);
|
||||
|
||||
// Increment voucher usage
|
||||
$this->db->table('discount_vouchers')
|
||||
@@ -588,11 +596,53 @@ class DiscountController extends BaseController
|
||||
*/
|
||||
private function getCurrentInvoiceBalance($invoiceId, $schoolYear)
|
||||
{
|
||||
try {
|
||||
return (float) ($this->invoiceLedgerService->calculateInvoice((int) $invoiceId)['balance'] ?? 0.0);
|
||||
} catch (\Throwable $e) {
|
||||
return 0.0;
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) return 0.0;
|
||||
|
||||
// Payments (exclude void/refund/failed, honor year)
|
||||
$qb = $this->paymentModel
|
||||
->select('COALESCE(SUM(paid_amount),0) AS total_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('school_year', $schoolYear);
|
||||
|
||||
$table = $this->paymentModel->table;
|
||||
$hasStatus = $this->db->fieldExists('status', $table);
|
||||
$hasVoid = $this->db->fieldExists('is_void', $table);
|
||||
if ($hasStatus) {
|
||||
$qb->groupStart()
|
||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -600,7 +650,166 @@ class DiscountController extends BaseController
|
||||
*/
|
||||
private function recalculateInvoice($invoiceId, $schoolYear): void
|
||||
{
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $invoiceId);
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) return;
|
||||
|
||||
$parentId = (int)($invoice['parent_id'] ?? 0);
|
||||
if ($parentId <= 0) return;
|
||||
|
||||
// ---- Tuition (recompute from enrollments) ----
|
||||
$enrollments = $this->enrollmentModel
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
|
||||
$registered = [];
|
||||
$withdrawn = [];
|
||||
foreach ($enrollments as $e) {
|
||||
$row = [
|
||||
'student_id' => (int)($e['student_id'] ?? 0),
|
||||
'class_section_id' => $e['class_section_id'] ?? null,
|
||||
'enrollment_status'=> (string)($e['enrollment_status'] ?? ''),
|
||||
];
|
||||
if (in_array($row['enrollment_status'], ['enrolled','payment pending'], true)) {
|
||||
$registered[] = $row;
|
||||
} elseif (in_array($row['enrollment_status'], ['withdrawn','refund pending','withdraw under review'], true)) {
|
||||
$withdrawn[] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
// Refund window check – if after deadline, withdrawn still billed
|
||||
$refundDeadline = (string)($this->configModel->getConfig('refund_deadline') ?? '');
|
||||
$refundAllowed = true;
|
||||
try {
|
||||
$tzName = (string) (config('School')->attendance['timezone'] ?? user_timezone());
|
||||
$tz = new \DateTimeZone($tzName);
|
||||
$today = new \DateTimeImmutable('today', $tz);
|
||||
$deadline = new \DateTimeImmutable($refundDeadline, $tz);
|
||||
$refundAllowed = $today <= $deadline;
|
||||
} catch (\Throwable $e) {
|
||||
$refundAllowed = true;
|
||||
}
|
||||
|
||||
$tuitionStudents = $registered;
|
||||
if (!$refundAllowed) {
|
||||
$tuitionStudents = array_merge($tuitionStudents, $withdrawn);
|
||||
}
|
||||
|
||||
// Grade threshold and fees
|
||||
$gradeFee = (int)($this->configModel->getConfig('grade_fee') ?? 9);
|
||||
$firstStudentFee = (float)($this->configModel->getConfig('first_student_fee') ?? 350);
|
||||
$secondStudentFee = (float)($this->configModel->getConfig('second_student_fee') ?? 200);
|
||||
$youthFee = (float)($this->configModel->getConfig('youth_fee') ?? 180);
|
||||
|
||||
// Normalize grades for tuition students
|
||||
foreach ($tuitionStudents as &$s) {
|
||||
$name = null;
|
||||
if (!empty($s['class_section_id'])) {
|
||||
$name = $this->classSectionModel->getClassSectionNameBySectionId($s['class_section_id']);
|
||||
}
|
||||
$s['grade_name'] = is_string($name) ? strtoupper(trim($name)) : 'N/A';
|
||||
}
|
||||
unset($s);
|
||||
|
||||
// Count regular vs youth and compute tuition
|
||||
$regularCount = 0;
|
||||
$youthCount = 0;
|
||||
foreach ($tuitionStudents as $s) {
|
||||
$lvl = $this->parseGradeLevel($s['grade_name']);
|
||||
if ($lvl > $gradeFee) $youthCount++; else $regularCount++;
|
||||
}
|
||||
|
||||
$tuitionSubtotal = 0.0;
|
||||
$tuitionSubtotal += $youthCount * $youthFee;
|
||||
if ($regularCount >= 2) {
|
||||
$tuitionSubtotal += $firstStudentFee + ($regularCount - 1) * $secondStudentFee;
|
||||
} elseif ($regularCount === 1) {
|
||||
$tuitionSubtotal += $firstStudentFee;
|
||||
}
|
||||
|
||||
// ---- Event charges (parent-year) ----
|
||||
$eventSubtotal = 0.0;
|
||||
try {
|
||||
$events = $this->eventChargesModel->getChargesWithEventInfo($parentId, $schoolYear) ?? [];
|
||||
foreach ($events as $ev) { $eventSubtotal += (float)($ev['charged'] ?? 0.0); }
|
||||
} catch (\Throwable $e) {}
|
||||
|
||||
// ---- Additional charges (per-invoice) ----
|
||||
$additionalSubtotal = 0.0;
|
||||
try {
|
||||
$rows = $this->additionalChargeModel
|
||||
->select('charge_type, amount')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('status', 'applied')
|
||||
->findAll();
|
||||
foreach ($rows as $r) {
|
||||
$amt = (float)($r['amount'] ?? 0);
|
||||
$typ = strtolower((string)($r['charge_type'] ?? 'add'));
|
||||
if ($typ === 'deduct') $amt = -abs($amt); else $amt = abs($amt);
|
||||
$additionalSubtotal += $amt;
|
||||
}
|
||||
} catch (\Throwable $e) {}
|
||||
|
||||
$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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -170,163 +170,6 @@ 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. */
|
||||
private function resolveProfile(?string $profile): string
|
||||
{
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -3,8 +3,6 @@
|
||||
namespace App\Controllers\View;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Libraries\FinancialStatus;
|
||||
use App\Libraries\InvoiceLedgerService;
|
||||
use App\Models\AdditionalChargeModel;
|
||||
use CodeIgniter\Controller;
|
||||
use App\Models\UserModel;
|
||||
@@ -30,7 +28,6 @@ class ExtraChargesController extends BaseController
|
||||
protected $studentClassModel;
|
||||
protected $enableAttendance;
|
||||
protected $attendanceDayModel;
|
||||
protected $invoiceLedgerService;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
@@ -42,7 +39,6 @@ class ExtraChargesController extends BaseController
|
||||
$this->invoiceModel = new InvoiceModel();
|
||||
$this->semester = $this->configModel->getConfig('semester');
|
||||
$this->schoolYear = $this->configModel->getConfig('school_year');
|
||||
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||
}
|
||||
|
||||
public function index()
|
||||
@@ -251,9 +247,13 @@ class ExtraChargesController extends BaseController
|
||||
// keep status as-is
|
||||
]);
|
||||
|
||||
if (($row['status'] ?? '') === FinancialStatus::ADDITIONAL_CHARGE_APPLIED && !empty($row['invoice_id'])) {
|
||||
$db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $row['invoice_id']]);
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $row['invoice_id']);
|
||||
// If it’s already applied on an invoice and the amount changed, reflect the delta
|
||||
if ($row['status'] === 'applied' && !empty($row['invoice_id']) && abs($delta) > 0.00001) {
|
||||
if ($delta > 0) {
|
||||
$this->invoiceModel->applyAdditionalCharge((int)$row['invoice_id'], $delta);
|
||||
} else {
|
||||
$this->invoiceModel->reverseAdditionalCharge((int)$row['invoice_id'], -$delta);
|
||||
}
|
||||
}
|
||||
|
||||
$db->transComplete();
|
||||
@@ -343,7 +343,7 @@ class ExtraChargesController extends BaseController
|
||||
'description' => trim($data['description'] ?? ''),
|
||||
'amount' => $signedAmount,
|
||||
'due_date' => !empty($data['due_date']) ? $data['due_date'] : null,
|
||||
'status' => $invoiceId ? FinancialStatus::ADDITIONAL_CHARGE_APPLIED : FinancialStatus::ADDITIONAL_CHARGE_PENDING,
|
||||
'status' => $invoiceId ? 'applied' : 'pending',
|
||||
'created_by' => (int)(session()->get('user_id') ?? 0),
|
||||
'created_at' => \CodeIgniter\I18n\Time::now('UTC')->toDateTimeString(), // store UTC
|
||||
];
|
||||
@@ -357,9 +357,17 @@ class ExtraChargesController extends BaseController
|
||||
$this->additionalChargeModel->insert($payload);
|
||||
$chargeId = (int)$this->additionalChargeModel->getInsertID();
|
||||
|
||||
// Apply to invoice if present
|
||||
if ($invoiceId) {
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$invoiceId]);
|
||||
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||
try {
|
||||
if ($chargeType === 'add') {
|
||||
$this->invoiceModel->applyAdditionalCharge($invoiceId, $amountAbs);
|
||||
} else {
|
||||
$this->invoiceModel->deductAdditionalCharge($invoiceId, $amountAbs);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'apply/deductAdditionalCharge failed: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// AFTER
|
||||
@@ -462,15 +470,23 @@ class ExtraChargesController extends BaseController
|
||||
|
||||
$this->db->transStart();
|
||||
|
||||
$this->additionalChargeModel->update((int)$id, [
|
||||
'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);
|
||||
if ($status === 'applied' && $invoiceId > 0 && $amountAbs > 0) {
|
||||
try {
|
||||
if ($chargeType === 'add') {
|
||||
$this->invoiceModel->reverseAdditionalCharge($invoiceId, $amountAbs);
|
||||
} else {
|
||||
// voiding a deduction -> add back
|
||||
$this->invoiceModel->applyAdditionalCharge($invoiceId, $amountAbs);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'void(): invoice adjust failed: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
$this->additionalChargeModel->update((int)$id, [
|
||||
'status' => 'void',
|
||||
]);
|
||||
|
||||
$this->db->transComplete();
|
||||
|
||||
if (!$this->db->transStatus()) {
|
||||
@@ -498,19 +514,26 @@ class ExtraChargesController extends BaseController
|
||||
$chargeType = (string)($row['charge_type'] ?? 'add');
|
||||
$status = (string)($row['status'] ?? 'pending');
|
||||
|
||||
if ($status !== FinancialStatus::ADDITIONAL_CHARGE_APPLIED || $invoiceId <= 0 || $amountAbs <= 0) {
|
||||
if ($status !== 'applied' || $invoiceId <= 0 || $amountAbs <= 0) {
|
||||
if ($this->wantsJson()) return $this->response->setJSON(['ok' => false, 'error' => 'Nothing to reverse']);
|
||||
return redirect()->back()->with('error', 'Nothing to reverse.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$invoiceId]);
|
||||
try {
|
||||
if ($chargeType === 'add') {
|
||||
$this->invoiceModel->reverseAdditionalCharge($invoiceId, $amountAbs);
|
||||
} else {
|
||||
$this->invoiceModel->applyAdditionalCharge($invoiceId, $amountAbs);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'reverse(): invoice adjust failed: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$this->additionalChargeModel->update((int)$id, [
|
||||
'status' => FinancialStatus::ADDITIONAL_CHARGE_PENDING,
|
||||
'status' => 'pending',
|
||||
'invoice_id' => null,
|
||||
]);
|
||||
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||
|
||||
$this->db->transComplete();
|
||||
|
||||
|
||||
@@ -406,82 +406,4 @@ class FamilyAdminController extends BaseController
|
||||
|
||||
return service('response')->setBody(view('family/card', ['f' => $family]));
|
||||
}
|
||||
|
||||
public function composeEmail()
|
||||
{
|
||||
$to = trim((string)$this->request->getGet('to'));
|
||||
$name = trim((string)$this->request->getGet('name'));
|
||||
$returnUrl = trim((string)$this->request->getGet('return_url'));
|
||||
if ($returnUrl === '') {
|
||||
$returnUrl = trim((string)$this->request->getServer('HTTP_REFERER'));
|
||||
}
|
||||
if ($returnUrl === '') {
|
||||
$returnUrl = site_url('family');
|
||||
}
|
||||
|
||||
return view('family/compose_email', [
|
||||
'to' => $to,
|
||||
'name' => $name,
|
||||
'return_url' => $returnUrl,
|
||||
]);
|
||||
}
|
||||
|
||||
public function sendComposeEmail()
|
||||
{
|
||||
if (!$this->request->is('post')) {
|
||||
return redirect()->to(site_url('family'));
|
||||
}
|
||||
|
||||
$to = trim((string)$this->request->getPost('to'));
|
||||
$subject = trim((string)$this->request->getPost('subject'));
|
||||
$html = (string)($this->request->getPost('html') ?? '');
|
||||
$returnUrl = trim((string)$this->request->getPost('return_url'));
|
||||
|
||||
if ($returnUrl === '' || !$this->isLocalReturnUrl($returnUrl)) {
|
||||
$returnUrl = site_url('family');
|
||||
}
|
||||
|
||||
if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
|
||||
return redirect()->back()->withInput()->with('error', 'Please enter a valid email address.');
|
||||
}
|
||||
if ($subject === '') {
|
||||
return redirect()->back()->withInput()->with('error', 'Subject is required.');
|
||||
}
|
||||
if (trim($html) === '') {
|
||||
return redirect()->back()->withInput()->with('error', 'Email body is required.');
|
||||
}
|
||||
|
||||
$wrapped = view('emails/custom_html', [
|
||||
'subject' => $subject,
|
||||
'body_html' => $html,
|
||||
]);
|
||||
|
||||
$mailer = new \App\Controllers\View\EmailController();
|
||||
$ok = $mailer->sendEmail($to, $subject, $wrapped, 'communication');
|
||||
|
||||
if ($ok) {
|
||||
return redirect()->to($returnUrl)->with('status', 'Email sent.');
|
||||
}
|
||||
|
||||
return redirect()->to($returnUrl)->with('error', 'Unable to send email.');
|
||||
}
|
||||
|
||||
private function isLocalReturnUrl(string $url): bool
|
||||
{
|
||||
$url = trim($url);
|
||||
if ($url === '') return false;
|
||||
|
||||
$parts = parse_url($url);
|
||||
if ($parts === false) return false;
|
||||
|
||||
if (!empty($parts['scheme']) || !empty($parts['host'])) {
|
||||
$base = parse_url(site_url('/'));
|
||||
if (!$base || empty($base['host'])) return false;
|
||||
$hostMatch = strcasecmp((string)($parts['host'] ?? ''), (string)$base['host']) === 0;
|
||||
return $hostMatch;
|
||||
}
|
||||
|
||||
// Relative URL (e.g., /family?x=1 or family?x=1)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Controllers\View;
|
||||
|
||||
use CodeIgniter\Controller;
|
||||
use CodeIgniter\Exceptions\PageNotFoundException;
|
||||
use Config\Database;
|
||||
|
||||
class FilesController extends Controller
|
||||
{
|
||||
@@ -21,11 +22,7 @@ class FilesController extends Controller
|
||||
throw PageNotFoundException::forPageNotFound();
|
||||
}
|
||||
|
||||
$expense = $this->expenseRecordForFile($name);
|
||||
if ($expense === null || !$this->canViewExpenseFile($expense)) {
|
||||
return $this->response->setStatusCode(403, 'You are not allowed to access this file.');
|
||||
}
|
||||
|
||||
// 3) Build path under writable
|
||||
$path = WRITEPATH . 'uploads/receipts/' . $name;
|
||||
if (!is_file($path)) {
|
||||
throw PageNotFoundException::forPageNotFound();
|
||||
@@ -82,11 +79,7 @@ class FilesController extends Controller
|
||||
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
|
||||
}
|
||||
|
||||
$reimbursement = $this->reimbursementRecordForFile($name);
|
||||
if ($reimbursement === null || !$this->canViewReimbursementFile($reimbursement)) {
|
||||
return $this->response->setStatusCode(403, 'You are not allowed to access this file.');
|
||||
}
|
||||
|
||||
// 3) Build path under writable (REIMBURSEMENTS)
|
||||
$path = WRITEPATH . 'uploads/reimbursements/' . $name;
|
||||
if (!is_file($path)) {
|
||||
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
|
||||
@@ -231,10 +224,6 @@ class FilesController extends Controller
|
||||
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';
|
||||
if (function_exists('finfo_open')) {
|
||||
$fi = finfo_open(FILEINFO_MIME_TYPE);
|
||||
@@ -282,8 +271,8 @@ class FilesController extends Controller
|
||||
|
||||
private function buildDraftDownloadName(string $filename, string $subdir): string
|
||||
{
|
||||
$column = $subdir === 'finals' ? 'final_file' : 'teacher_file';
|
||||
$db = Database::connect();
|
||||
$column = $subdir === 'finals' ? 'final_file' : $this->resolveExamDraftFileColumn($db);
|
||||
$row = $db->table('exam_drafts ed')
|
||||
->select('ed.version, ed.exam_type, ed.class_section_id, cs.class_section_name')
|
||||
->join('classSection cs', 'cs.class_section_id = ed.class_section_id', 'left')
|
||||
@@ -312,189 +301,4 @@ class FilesController extends Controller
|
||||
$value = trim($value, '_');
|
||||
return $value === '' ? 'Exam' : mb_strtolower($value);
|
||||
}
|
||||
|
||||
private function resolveExamDraftFileColumn($db): string
|
||||
{
|
||||
try {
|
||||
$fields = $db->getFieldNames('exam_drafts');
|
||||
if (in_array('teacher_file', $fields, true)) {
|
||||
return 'teacher_file';
|
||||
}
|
||||
if (in_array('author_file', $fields, true)) {
|
||||
return 'author_file';
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'FilesController::resolveExamDraftFileColumn error: ' . $e->getMessage());
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,45 +68,17 @@ public function financialReport()
|
||||
}
|
||||
|
||||
// === Invoices ===
|
||||
// Business rule: one active invoice per parent per school year.
|
||||
// If legacy data has multiple invoices, show only the latest one to avoid reporting older invoices as "Unpaid"
|
||||
// after new charges/payments update the current invoice.
|
||||
$db = \Config\Database::connect();
|
||||
if (!empty($schoolYear)) {
|
||||
$latestSub = $db->table('invoices')
|
||||
->select('parent_id, MAX(id) AS max_id')
|
||||
->where('school_year', $schoolYear)
|
||||
->groupBy('parent_id')
|
||||
->getCompiledSelect();
|
||||
|
||||
$invBuilder = $db->table('invoices')
|
||||
->select("invoices.*, CONCAT(users.firstname, ' ', users.lastname) AS parent_name", false)
|
||||
->join("($latestSub) latest", 'latest.max_id = invoices.id', 'inner', false)
|
||||
->join('users', 'users.id = invoices.parent_id', 'left');
|
||||
|
||||
if ($hasFrom) {
|
||||
$invBuilder->where('DATE(COALESCE(invoices.issue_date, invoices.created_at)) >=', $dateFrom);
|
||||
}
|
||||
if ($hasTo) {
|
||||
$invBuilder->where('DATE(COALESCE(invoices.issue_date, invoices.created_at)) <=', $dateTo);
|
||||
}
|
||||
|
||||
$invoices = $invBuilder->get()->getResultArray();
|
||||
} else {
|
||||
$invoices = $invoiceModel
|
||||
->select("invoices.*, CONCAT(users.firstname, ' ', users.lastname) AS parent_name")
|
||||
->join('users', 'users.id = invoices.parent_id')
|
||||
->findAll();
|
||||
}
|
||||
|
||||
$invoiceIds = array_values(array_unique(array_filter(array_map(static function ($inv) {
|
||||
$id = (int)($inv['id'] ?? 0);
|
||||
return $id > 0 ? $id : null;
|
||||
}, $invoices))));
|
||||
$invoices = $invoiceModel
|
||||
->select("invoices.*, CONCAT(users.firstname, ' ', users.lastname) AS parent_name")
|
||||
->join('users', 'users.id = invoices.parent_id')
|
||||
->findAll();
|
||||
|
||||
// Helper to build a fresh, filtered PaymentModel each time (so filters don't get lost between queries)
|
||||
$buildPaymentModel = function () use ($schoolYear, $dateFrom, $dateTo) {
|
||||
$pm = new PaymentModel();
|
||||
if ($schoolYear) {
|
||||
$pm->where('school_year', $schoolYear);
|
||||
}
|
||||
if (!empty($dateFrom)) {
|
||||
$pm->where('DATE(payment_date) >=', $dateFrom);
|
||||
}
|
||||
@@ -142,13 +114,7 @@ public function financialReport()
|
||||
};
|
||||
|
||||
// === Payments aggregated by invoice_id (for the "Paid" column) ===
|
||||
$paymentsQuery = $applyPaymentFilters($buildPaymentModel());
|
||||
if (!empty($invoiceIds)) {
|
||||
$paymentsQuery->whereIn('invoice_id', $invoiceIds);
|
||||
} else {
|
||||
$paymentsQuery->where('invoice_id', -1);
|
||||
}
|
||||
$payments = $paymentsQuery
|
||||
$payments = $applyPaymentFilters($buildPaymentModel())
|
||||
->select('invoice_id, SUM(paid_amount) AS paid_amount')
|
||||
->where('invoice_id IS NOT NULL')
|
||||
->groupBy('invoice_id')
|
||||
@@ -172,7 +138,6 @@ public function financialReport()
|
||||
SUM(paid_amount) AS amount
|
||||
")
|
||||
->where('invoice_id IS NOT NULL')
|
||||
->whereIn('invoice_id', $invoiceIds ?: [-1])
|
||||
->groupBy('invoice_id, method')
|
||||
->findAll();
|
||||
|
||||
@@ -196,7 +161,6 @@ public function financialReport()
|
||||
SUM(CASE WHEN LOWER(TRIM(payment_method)) IN ('credit','card','credit card','debit','debit card','visa','mastercard') THEN paid_amount ELSE 0 END) AS total_credit
|
||||
")
|
||||
->where('invoice_id IS NOT NULL')
|
||||
->whereIn('invoice_id', $invoiceIds ?: [-1])
|
||||
->first() ?? [];
|
||||
|
||||
$paymentTotals = [
|
||||
@@ -252,28 +216,25 @@ public function financialReport()
|
||||
$schoolYears[] = (string)$schoolYear;
|
||||
}
|
||||
|
||||
$eventFeesTotal = $this->getEventFeesTotal($schoolYear, $dateFrom, $dateTo);
|
||||
|
||||
// JSON API support
|
||||
if ($this->wantsJson() || strtolower((string)($this->request->getGet('format') ?? '')) === 'json') {
|
||||
return $this->response->setJSON([
|
||||
'ok' => true,
|
||||
'selectedYear' => $schoolYear,
|
||||
'dateFrom' => $dateFrom,
|
||||
'dateTo' => $dateTo,
|
||||
return $this->response->setJSON([
|
||||
'ok' => true,
|
||||
'selectedYear' => $schoolYear,
|
||||
'dateFrom' => $dateFrom,
|
||||
'dateTo' => $dateTo,
|
||||
'schoolYears' => $schoolYears,
|
||||
'invoices' => $invoices,
|
||||
'payments' => $payments,
|
||||
'paymentBreakdown' => $paymentBreakdown,
|
||||
'paymentTotals' => $paymentTotals,
|
||||
'refunds' => $refunds,
|
||||
'expenses' => $expenses,
|
||||
'reimbursements' => $reimbursements,
|
||||
'discounts' => $discounts,
|
||||
'eventFeesTotal' => $eventFeesTotal,
|
||||
'csrf_token' => csrf_token(),
|
||||
'csrf_hash' => csrf_hash(),
|
||||
]);
|
||||
'refunds' => $refunds,
|
||||
'expenses' => $expenses,
|
||||
'reimbursements' => $reimbursements,
|
||||
'discounts' => $discounts,
|
||||
'csrf_token' => csrf_token(),
|
||||
'csrf_hash' => csrf_hash(),
|
||||
]);
|
||||
}
|
||||
|
||||
return view('payment/financial_report', [
|
||||
@@ -285,7 +246,6 @@ public function financialReport()
|
||||
'expenses' => $expenses,
|
||||
'reimbursements' => $reimbursements,
|
||||
'discounts' => $discounts,
|
||||
'eventFeesTotal' => $eventFeesTotal,
|
||||
'selectedYear' => $schoolYear,
|
||||
'schoolYears' => $schoolYears,
|
||||
'dateFrom' => $dateFrom,
|
||||
@@ -701,7 +661,8 @@ public function financialReport()
|
||||
]
|
||||
];
|
||||
|
||||
$this->writeChartImage('bar_chart.png', $chartData);
|
||||
$url = 'https://quickchart.io/chart?c=' . urlencode(json_encode($chartData));
|
||||
file_put_contents(WRITEPATH . 'reports/bar_chart.png', file_get_contents($url));
|
||||
}
|
||||
|
||||
private function generatePieChart(array $data)
|
||||
@@ -720,28 +681,8 @@ public function financialReport()
|
||||
]
|
||||
];
|
||||
|
||||
$this->writeChartImage('pie_chart.png', $chartData);
|
||||
}
|
||||
|
||||
private function writeChartImage(string $filename, array $chartData): void
|
||||
{
|
||||
$reportDir = WRITEPATH . 'reports';
|
||||
if (!is_dir($reportDir) && !mkdir($reportDir, 0775, true) && !is_dir($reportDir)) {
|
||||
log_message('error', 'Unable to create financial report chart directory: {dir}', ['dir' => $reportDir]);
|
||||
return;
|
||||
}
|
||||
|
||||
$url = 'https://quickchart.io/chart?c=' . urlencode(json_encode($chartData));
|
||||
$image = @file_get_contents($url);
|
||||
if ($image === false || $image === '') {
|
||||
log_message('warning', 'Unable to download financial report chart from QuickChart.');
|
||||
return;
|
||||
}
|
||||
|
||||
$path = $reportDir . DIRECTORY_SEPARATOR . $filename;
|
||||
if (@file_put_contents($path, $image) === false) {
|
||||
log_message('error', 'Unable to write financial report chart image: {path}', ['path' => $path]);
|
||||
}
|
||||
file_put_contents(WRITEPATH . 'reports/pie_chart.png', file_get_contents($url));
|
||||
}
|
||||
|
||||
private function getFinancialSummary(?string $dateFrom = null, ?string $dateTo = null, ?string $schoolYear = null): array
|
||||
@@ -1117,7 +1058,6 @@ public function financialReport()
|
||||
$amountCollected = $totalPaid;
|
||||
$netAmount = ($totalCharges - $totalDiscounts - $totalRefunds);
|
||||
|
||||
$totalEventFees = $this->getEventFeesTotal($schoolYear, $invoiceDateFrom, $invoiceDateTo);
|
||||
return [
|
||||
'schoolYear' => $schoolYear,
|
||||
'dateFrom' => $dateFrom,
|
||||
@@ -1133,28 +1073,9 @@ public function financialReport()
|
||||
'amountCollected' => $amountCollected,
|
||||
'totalUnpaid' => $totalUnpaid,
|
||||
'netAmount' => $netAmount,
|
||||
'totalEventFees' => $totalEventFees,
|
||||
];
|
||||
}
|
||||
|
||||
private function getEventFeesTotal(?string $schoolYear, ?string $dateFrom, ?string $dateTo): float
|
||||
{
|
||||
$db = \Config\Database::connect();
|
||||
$builder = $db->table('event_charges ec')
|
||||
->select('COALESCE(SUM(ec.charged),0) AS amount', false);
|
||||
if (!empty($schoolYear)) {
|
||||
$builder->where('ec.school_year', $schoolYear);
|
||||
}
|
||||
if (!empty($dateFrom)) {
|
||||
$builder->where('DATE(ec.created_at) >=', $dateFrom);
|
||||
}
|
||||
if (!empty($dateTo)) {
|
||||
$builder->where('DATE(ec.created_at) <=', $dateTo);
|
||||
}
|
||||
$row = $builder->get()->getRowArray();
|
||||
return $row ? (float)($row['amount'] ?? 0) : 0.0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Management page: list parents with outstanding balances (> 0) for a school year.
|
||||
@@ -1305,23 +1226,6 @@ public function financialReport()
|
||||
$byParent[$pid]['total_balance'] += $extra;
|
||||
}
|
||||
|
||||
$eventFeesPerParent = [];
|
||||
try {
|
||||
$eventFeesRows = $db->table('event_charges ec')
|
||||
->select('ec.parent_id, COALESCE(SUM(ec.charged),0) AS event_fees', false)
|
||||
->where('ec.school_year', $schoolYear)
|
||||
->groupBy('ec.parent_id')
|
||||
->get()
|
||||
->getResultArray();
|
||||
foreach ($eventFeesRows as $row) {
|
||||
$pid = (int)($row['parent_id'] ?? 0);
|
||||
if ($pid <= 0) continue;
|
||||
$eventFeesPerParent[$pid] = (float)($row['event_fees'] ?? 0);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// ignore, fallback to no event fees data
|
||||
}
|
||||
|
||||
// Reduce into rows list; only parents with positive balance
|
||||
// Also compute remaining installments and suggested monthly amount
|
||||
$rows = [];
|
||||
@@ -1379,11 +1283,10 @@ public function financialReport()
|
||||
$parentIds = array_values(array_unique(array_map(static fn($r) => (int)($r['parent_id'] ?? 0), $rows)));
|
||||
$hasPayments = [];
|
||||
$paidTotals = [];
|
||||
$paymentCounts = [];
|
||||
if (!empty($parentIds)) {
|
||||
try {
|
||||
$pRows = $db->table('payments')
|
||||
->select('parent_id, SUM(paid_amount) AS total_paid, COUNT(*) AS payment_count')
|
||||
->select('parent_id, SUM(paid_amount) AS total_paid')
|
||||
->whereIn('parent_id', $parentIds)
|
||||
->where('school_year', $schoolYear)
|
||||
->groupBy('parent_id')
|
||||
@@ -1393,7 +1296,6 @@ public function financialReport()
|
||||
if ($pid > 0) {
|
||||
$hasPayments[$pid] = true;
|
||||
$paidTotals[$pid] = (float)($pr['total_paid'] ?? 0);
|
||||
$paymentCounts[$pid] = (int)($pr['payment_count'] ?? 0);
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
@@ -1401,7 +1303,7 @@ public function financialReport()
|
||||
}
|
||||
}
|
||||
|
||||
$dataRows = array_map(function(array $r) use ($hasPayments, $paidTotals, $paymentCounts, $nextInstallmentYmd, $eventFeesPerParent) {
|
||||
$dataRows = array_map(function(array $r) use ($hasPayments, $paidTotals, $nextInstallmentYmd) {
|
||||
$pid = (int)($r['parent_id'] ?? 0);
|
||||
$name = trim((string)($r['firstname'] ?? '') . ' ' . (string)($r['lastname'] ?? ''));
|
||||
return [
|
||||
@@ -1415,10 +1317,8 @@ public function financialReport()
|
||||
'installment_amount' => (float)($r['installment_amount'] ?? 0),
|
||||
'type' => isset($hasPayments[$pid]) ? 'installment' : 'no_payment',
|
||||
'total_paid' => isset($paidTotals[$pid]) ? (float)$paidTotals[$pid] : 0.0,
|
||||
'payment_count' => isset($paymentCounts[$pid]) ? (int)$paymentCounts[$pid] : 0,
|
||||
'has_installment'=> isset($hasPayments[$pid]) ? 1 : 0,
|
||||
'next_installment' => $nextInstallmentYmd,
|
||||
'event_fees' => (float)($eventFeesPerParent[$pid] ?? 0),
|
||||
];
|
||||
}, $rows);
|
||||
|
||||
|
||||
@@ -421,45 +421,17 @@ class FlagController extends Controller
|
||||
log_message('debug', 'Flag state: ' . $this->request->getPost('flag_state'));
|
||||
|
||||
$currentFlagModel = new CurrentFlagModel();
|
||||
$userId = session()->get('user_id');
|
||||
|
||||
// Get the new flag state from the form
|
||||
$newState = $this->request->getPost('flag_state');
|
||||
$stateDescription = (string) ($this->request->getPost('state_description') ?? '');
|
||||
$actionTaken = (string) ($this->request->getPost('action_taken') ?? '');
|
||||
|
||||
if (!$newState) {
|
||||
session()->setFlashdata('error', 'incident state not provided.');
|
||||
return $this->index();
|
||||
}
|
||||
|
||||
$update = ['flag_state' => $newState];
|
||||
if ($newState === 'Closed') {
|
||||
$update['updated_by_closed'] = $userId;
|
||||
if ($stateDescription !== '') {
|
||||
$update['close_description'] = $stateDescription;
|
||||
}
|
||||
if ($actionTaken !== '') {
|
||||
$update['action_taken'] = $actionTaken;
|
||||
}
|
||||
} elseif ($newState === 'Canceled') {
|
||||
$update['updated_by_canceled'] = $userId;
|
||||
if ($stateDescription !== '') {
|
||||
$update['cancel_description'] = $stateDescription;
|
||||
}
|
||||
if ($actionTaken !== '') {
|
||||
$update['action_taken'] = $actionTaken;
|
||||
}
|
||||
}
|
||||
|
||||
// Update the flag state in the database
|
||||
if ($currentFlagModel->update($id, $update)) {
|
||||
if ($newState === 'Closed' || $newState === 'Canceled') {
|
||||
$flagData = $currentFlagModel->find($id);
|
||||
if ($flagData) {
|
||||
return $this->moveToHistory($flagData);
|
||||
}
|
||||
}
|
||||
if ($currentFlagModel->update($id, ['flag_state' => $newState])) {
|
||||
session()->setFlashdata('success', 'Incident state updated successfully!');
|
||||
} else {
|
||||
$errors = $currentFlagModel->errors();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -482,7 +482,6 @@ class HomeworkController extends Controller
|
||||
// Step 1: Get student IDs from student_class table
|
||||
$studentClassRows = $this->studentClassModel
|
||||
->select('student_id')
|
||||
->distinct()
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
@@ -535,7 +534,10 @@ class HomeworkController extends Controller
|
||||
private function getStudentsWithHomeworkScores($classSectionId, $homeworkHeaders, $semester, $schoolYear)
|
||||
{
|
||||
$semVariants = $this->getSemesterVariants($semester);
|
||||
$studentClasses = $this->studentClassModel->getClassStudents($classSectionId, $schoolYear, null);
|
||||
$studentClasses = $this->studentClassModel
|
||||
->active()
|
||||
->where('student_class.class_section_id', $classSectionId)
|
||||
->findAll();
|
||||
$students = [];
|
||||
|
||||
foreach ($studentClasses as $sc) {
|
||||
|
||||
@@ -86,7 +86,6 @@ class HomeworkTrackingController extends BaseController
|
||||
|
||||
$hasHomework = [];
|
||||
$hwEnteredAt = [];
|
||||
$homeworkSubmissionCounts = [];
|
||||
foreach ($rows as $r) {
|
||||
$csid = (int)($r['class_section_id'] ?? 0);
|
||||
$hi = (int)($r['homework_index'] ?? 0);
|
||||
@@ -95,7 +94,6 @@ class HomeworkTrackingController extends BaseController
|
||||
$hasHomework[$csid][$hi] = true;
|
||||
$dateStr = substr((string)($r['first_created'] ?? ''), 0, 10);
|
||||
$hwEnteredAt[$csid][$hi] = $dateStr ?: null;
|
||||
$homeworkSubmissionCounts[$csid] = ($homeworkSubmissionCounts[$csid] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,7 +217,6 @@ class HomeworkTrackingController extends BaseController
|
||||
'teachers' => $teachersPage,
|
||||
'hasHomework' => $hasHomework,
|
||||
'hwEnteredAt' => $hwEnteredAt,
|
||||
'homeworkSubmissionCounts' => $homeworkSubmissionCounts,
|
||||
'hasHomeworkByDate' => $hasHomeworkByDate,
|
||||
'hwEnteredAtByDate' => $hwEnteredAtByDate,
|
||||
'page' => $page,
|
||||
|
||||
@@ -381,24 +381,18 @@ class InvoiceController extends ResourceController
|
||||
return false;
|
||||
}
|
||||
|
||||
public function generateInvoice(
|
||||
string $parentId = null,
|
||||
?string $schoolYearOverride = null,
|
||||
?string $semesterOverride = null,
|
||||
bool $recalculateDiscounts = true
|
||||
)
|
||||
public function generateInvoice(string $parentId = null)
|
||||
{
|
||||
$isAjax = $this->request->isAJAX() || str_contains(strtolower($this->request->getHeaderLine('Accept')), 'application/json');
|
||||
if ($parentId == null) {
|
||||
$parentId = (int)$this->request->getPost('parent_id');
|
||||
}
|
||||
$schoolYear = (string) ($schoolYearOverride ?: $this->schoolYear);
|
||||
$semester = (string) ($semesterOverride ?: $this->semester);
|
||||
$schoolYear = (string) $this->schoolYear;
|
||||
|
||||
// Fetch enrolled + withdrawn students
|
||||
$enrollments = $this->enrollmentModel
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->where('school_year', $this->schoolYear)
|
||||
->findAll();
|
||||
|
||||
if (empty($enrollments)) {
|
||||
@@ -450,23 +444,21 @@ class InvoiceController extends ResourceController
|
||||
$tuitionFee = $fees['tuition_fee'];
|
||||
|
||||
// ✅ Fetch event charges
|
||||
$eventsList = $this->chargesModel->getChargesWithEventInfo($parentId, $schoolYear);
|
||||
$eventsList = $this->chargesModel->getChargesWithEventInfo($parentId, $this->schoolYear);
|
||||
$eventchargeTotal = array_sum(array_column($eventsList, 'charged'));
|
||||
|
||||
$totalDiscount = 0.0;
|
||||
if ($recalculateDiscounts) {
|
||||
$totalDiscount = $this->recalculateAndUpdateDiscount(
|
||||
$parentId,
|
||||
$schoolYear,
|
||||
$tuitionFee,
|
||||
$enrollments
|
||||
);
|
||||
}
|
||||
$totalDiscount = $this->recalculateAndUpdateDiscount(
|
||||
$parentId,
|
||||
$this->schoolYear,
|
||||
$tuitionFee,
|
||||
$enrollments
|
||||
);
|
||||
|
||||
$semester = $this->semester;
|
||||
// ✅ Refunds PAID to the parent for this year (Partial/Paid)
|
||||
$refundPaid = (float) $this->refundModel->getTotalApprovedRefundByParentIdAndSchoolYear($parentId, $schoolYear);
|
||||
$refundPaid = (float) $this->refundModel->getTotalApprovedRefundByParentIdAndSchoolYear($parentId, $this->schoolYear);
|
||||
|
||||
$totalPaid = $this->paymentModel->getTotalPaidByParentId($parentId, $schoolYear);
|
||||
$totalPaid = $this->paymentModel->getTotalPaidByParentId($parentId, $this->schoolYear);
|
||||
|
||||
$discountedTuition = max(0, $tuitionFee);
|
||||
$totalAmount = $discountedTuition + $eventchargeTotal;
|
||||
@@ -477,22 +469,17 @@ class InvoiceController extends ResourceController
|
||||
- $refundPaid // approved refunds paid to parent
|
||||
- $totalPaid; // payments received
|
||||
|
||||
// Business rule: single invoice per parent per school year.
|
||||
// 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);
|
||||
// Your invoice fetch
|
||||
$existingInvoices = $this->invoiceModel->getInvoicesByParentId($parentId, $this->schoolYear);
|
||||
|
||||
$updated = false;
|
||||
|
||||
$updatedIds = [];
|
||||
if (!empty($invoice) && isset($invoice['id'])) {
|
||||
$paymentExclude = ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'];
|
||||
$paymentsHasStatus = false;
|
||||
$paymentsHasVoid = false;
|
||||
try {
|
||||
$paymentsHasStatus = $this->db->fieldExists('status', 'payments');
|
||||
$paymentsHasVoid = $this->db->fieldExists('is_void', 'payments');
|
||||
} catch (\Throwable $e) {
|
||||
}
|
||||
if (!empty($existingInvoices)) {
|
||||
foreach ($existingInvoices as $invoice) {
|
||||
if (!isset($invoice['id'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Preserve applied additional charges and recalc this invoice only
|
||||
$extrasSum = 0.0;
|
||||
@@ -500,7 +487,7 @@ class InvoiceController extends ResourceController
|
||||
$rows = $this->db->table('additional_charges')
|
||||
->select('charge_type, amount')
|
||||
->where('invoice_id', (int)$invoice['id'])
|
||||
->where('school_year', $schoolYear)
|
||||
->where('school_year', $this->schoolYear)
|
||||
->where('status', 'applied')
|
||||
->get()->getResultArray();
|
||||
foreach ($rows as $r) {
|
||||
@@ -533,7 +520,7 @@ class InvoiceController extends ResourceController
|
||||
$r = $this->db->table('refunds')
|
||||
->select('COALESCE(SUM(refund_paid_amount),0) AS tot')
|
||||
->where('invoice_id', (int)$invoice['id'])
|
||||
->where('school_year', $schoolYear)
|
||||
->where('school_year', $this->schoolYear)
|
||||
->whereIn('status', ['Partial','Paid'])
|
||||
->get()->getRowArray();
|
||||
$invRefunds = (float)($r['tot'] ?? 0.0);
|
||||
@@ -541,33 +528,8 @@ class InvoiceController extends ResourceController
|
||||
log_message('error', 'refund sum failed for invoice ' . (int)$invoice['id'] . ': ' . $e->getMessage());
|
||||
}
|
||||
|
||||
// Payments recorded on this invoice (sum payments to avoid stale invoice.paid_amount)
|
||||
$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);
|
||||
}
|
||||
// Payments recorded on this invoice (denormalized field kept in sync by PaymentController)
|
||||
$paidOnInv = (float)($invoice['paid_amount'] ?? 0.0);
|
||||
|
||||
$newBalance = $newTotal - $invDiscount - $invRefunds - $paidOnInv;
|
||||
$newStatus = ($newBalance <= 0.00001)
|
||||
@@ -585,6 +547,7 @@ class InvoiceController extends ResourceController
|
||||
$updatedIds[] = (int)$invoice['id'];
|
||||
log_message('info', "Updated invoice ID {$invoice['id']} for parent ID {$parentId}.");
|
||||
$updated = true;
|
||||
}
|
||||
} else {
|
||||
// Generate invoice number
|
||||
$schoolId = $this->userModel->getSchoolIdByUserId($parentId);
|
||||
@@ -615,7 +578,7 @@ class InvoiceController extends ResourceController
|
||||
// Initial balance equals the created total; discounts/refunds/payments will adjust later
|
||||
'balance' => $totalAmount,
|
||||
'status' => 'Unpaid',
|
||||
'school_year' => $schoolYear,
|
||||
'school_year' => $this->schoolYear,
|
||||
'semester' => $semester,
|
||||
'issue_date' => $issueUtc,
|
||||
'due_date' => $dueUtc,
|
||||
@@ -652,47 +615,6 @@ class InvoiceController extends ResourceController
|
||||
->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(
|
||||
int $parentId,
|
||||
string $schoolYear,
|
||||
@@ -756,7 +678,7 @@ class InvoiceController extends ResourceController
|
||||
log_message('error', 'additional_charges sum failed for discount recalculation invoice ' . (int)$invoice['id'] . ': ' . $e->getMessage());
|
||||
}
|
||||
|
||||
$baseTotal = round($tuitionFee + $extrasSum, 2);
|
||||
$baseTotal = round($tuitionFee + $eventchargeTotal + $extrasSum, 2);
|
||||
|
||||
// Recalculate discount
|
||||
if ($discountUsage['discount_type'] === 'percent') {
|
||||
@@ -1344,12 +1266,6 @@ 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);
|
||||
$amount = (float)($event['charged'] ?? 0.0);
|
||||
@@ -1696,24 +1612,12 @@ private function getGradeLevel($grade): array
|
||||
$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', [
|
||||
'invoices' => $invoices,
|
||||
'schoolYears' => $schoolYears,
|
||||
'selectedYear' => $selectedYear,
|
||||
'currentSchoolYear' => $currentSchoolYear,
|
||||
'dueDate' => $this->dueDate,
|
||||
'invoiceEventCharges' => $invoiceEventCharges,
|
||||
'dueDate' => $this->dueDate
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -95,11 +95,6 @@ class LandingPageController extends BaseController
|
||||
return null;
|
||||
}
|
||||
|
||||
// Teacher class sections only apply to the teacher role; other roles have no teacher_class rows.
|
||||
if (strtolower(trim((string) $this->getUserRole())) !== 'teacher') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get all class assignments for this teacher in the current term
|
||||
$assignments = $this->teacherClassModel->getClassAssignmentsByUserId(
|
||||
(int)$user_id,
|
||||
@@ -111,7 +106,7 @@ class LandingPageController extends BaseController
|
||||
$ids = array_values(array_filter(array_unique($ids)));
|
||||
|
||||
if (empty($ids)) {
|
||||
log_message('warning', "No class section found for user ID: $user_id");
|
||||
log_message('error', "No class section found for user ID: $user_id");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -873,12 +868,8 @@ class LandingPageController extends BaseController
|
||||
|
||||
protected function getUserRole()
|
||||
{
|
||||
$active = session()->get('active_role');
|
||||
if ($active !== null && $active !== '') {
|
||||
return (string) $active;
|
||||
}
|
||||
|
||||
return (string) (session()->get('role') ?? 'guest');
|
||||
// Assuming you have a session variable storing the user role
|
||||
return session()->get('user_role', 'guest'); // Default to guest if not set
|
||||
}
|
||||
|
||||
protected function getUserRoleFromDatabase($user_id)
|
||||
|
||||
@@ -717,7 +717,6 @@ class ParentController extends BaseController
|
||||
|
||||
// Step 1: Generate a secure token for email verification
|
||||
$token = bin2hex(random_bytes(48));
|
||||
$tokenHash = hash('sha256', $token);
|
||||
|
||||
// Step 2: Determine user type based on relationship
|
||||
$userType = in_array(strtolower($relationToStudent), ['wife', 'husband']) ? 'Secondary' : 'Tertiary';
|
||||
@@ -777,7 +776,7 @@ class ParentController extends BaseController
|
||||
'state' => strtoupper($userData['state']),
|
||||
'zip' => $userData['zip'],
|
||||
'accept_school_policy' => $userData['accept_school_policy'] ?? 0,
|
||||
'token' => $tokenHash,
|
||||
'token' => $token,
|
||||
'is_verified' => 0,
|
||||
'status' => 'Inactive',
|
||||
'user_type' => $userType,
|
||||
@@ -1797,34 +1796,16 @@ $existing = $this->studentModel
|
||||
$activeEventCount = is_array($activeEvents) ? count($activeEvents) : 0;
|
||||
|
||||
// Get charges (participation info)
|
||||
$chargesList = $this->chargesModel->getChargesWithEventInfo($parentId, $schoolYear, $semester);
|
||||
$chargesList = $this->chargesModel->getChargesWithEventInfo($parentId, $schoolYear);
|
||||
|
||||
// Build a map: "studentId:eventId" => [ 'participation' => ..., 'date' => ... ]
|
||||
$charges = [];
|
||||
$externalParticipantsByEvent = [];
|
||||
foreach ($chargesList as $charge) {
|
||||
$studentId = $charge['student_id'] ?? null;
|
||||
$eventId = (int) ($charge['event_id'] ?? 0);
|
||||
|
||||
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)),
|
||||
];
|
||||
}
|
||||
$key = $charge['student_id'] . ':' . $charge['event_id'];
|
||||
$charges[$key] = [
|
||||
'participation' => $charge['participation'],
|
||||
'date' => $charge['updated_at'] ?? $charge['created_at'] // Use updated_at if available
|
||||
];
|
||||
}
|
||||
|
||||
// Get enrolled students
|
||||
@@ -1833,7 +1814,6 @@ $existing = $this->studentModel
|
||||
return view('parent/event_participation', [
|
||||
'activeEvents' => $activeEvents,
|
||||
'charges' => $charges,
|
||||
'externalParticipantsByEvent' => $externalParticipantsByEvent,
|
||||
'yourStudents' => $students,
|
||||
'activeEventCount' => $activeEventCount,
|
||||
]);
|
||||
|
||||
@@ -2,9 +2,6 @@
|
||||
|
||||
namespace App\Controllers\View;
|
||||
|
||||
use App\Libraries\FinancialAttachmentService;
|
||||
use App\Libraries\FinancialStatus;
|
||||
use App\Libraries\InvoiceLedgerService;
|
||||
use App\Models\PaymentModel;
|
||||
use App\Models\AdditionalChargeModel;
|
||||
use App\Models\ClassSectionModel;
|
||||
@@ -19,14 +16,23 @@ use App\Models\PaymentErrorModel;
|
||||
use App\Models\InvoiceModel;
|
||||
use App\Models\TeacherClassModel;
|
||||
use App\Models\DiscountUsageModel;
|
||||
use Config\PaypalConfig;
|
||||
use PayPal\Api\Amount;
|
||||
use PayPal\Api\Payment;
|
||||
use PayPal\Api\PaymentExecution;
|
||||
use PayPal\Api\Payer;
|
||||
use PayPal\Api\Transaction;
|
||||
use PayPal\Rest\ApiContext;
|
||||
use PayPal\Auth\OAuthTokenCredential;
|
||||
|
||||
use CodeIgniter\RESTful\ResourceController;
|
||||
use CodeIgniter\Events\Events;
|
||||
use CodeIgniter\Exceptions\PageNotFoundException;
|
||||
|
||||
class PaymentController extends ResourceController
|
||||
{
|
||||
protected $paymentModel;
|
||||
protected $paypalConfig;
|
||||
protected $apiContext;
|
||||
protected $request;
|
||||
protected $db;
|
||||
protected $invoiceModel;
|
||||
@@ -45,8 +51,6 @@ class PaymentController extends ResourceController
|
||||
protected $discountUsageModel;
|
||||
protected $additionalChargeModel;
|
||||
protected $classSectionModel;
|
||||
protected $invoiceLedgerService;
|
||||
protected $financialAttachmentService;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
@@ -56,6 +60,7 @@ class PaymentController extends ResourceController
|
||||
$this->eventChargesModel = new EventChargesModel();
|
||||
$this->manualPaymentModel = new ManualPaymentModel();
|
||||
$this->paymentModel = new PaymentModel();
|
||||
$this->paypalConfig = new PaypalConfig();
|
||||
$this->request = \Config\Services::request();
|
||||
$this->db = \Config\Database::connect();
|
||||
$this->invoiceModel = new InvoiceModel();
|
||||
@@ -68,9 +73,20 @@ class PaymentController extends ResourceController
|
||||
$this->installmentDate = $this->configModel->getConfig('installment_date');
|
||||
$this->discountUsageModel = new DiscountUsageModel();
|
||||
$this->additionalChargeModel = new AdditionalChargeModel();
|
||||
$this->classSectionModel = new ClassSectionModel();
|
||||
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||
$this->financialAttachmentService = new FinancialAttachmentService();
|
||||
$this->classSectionModel = new ClassSectionModel();
|
||||
|
||||
// Set up PayPal API context
|
||||
$this->apiContext = new ApiContext(
|
||||
new OAuthTokenCredential(
|
||||
$this->paypalConfig->paypalClientId,
|
||||
$this->paypalConfig->paypalSecret
|
||||
)
|
||||
);
|
||||
|
||||
$this->apiContext->setConfig([
|
||||
'mode' => $this->paypalConfig->paypalMode, // 'sandbox' or 'live'
|
||||
'http.headers' => ['Connection' => 'Close']
|
||||
]);
|
||||
}
|
||||
|
||||
// API: Create a new payment plan
|
||||
@@ -169,11 +185,135 @@ 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()
|
||||
{
|
||||
return redirect()
|
||||
->to(site_url('parent/invoice_payment'))
|
||||
->with('info', 'Online payment is currently unavailable. Please contact the school office to complete payment.');
|
||||
$modeCheck = $this->configModel->getConfig('paypal_mode');
|
||||
|
||||
$parentId = session()->get('user_id'); // assuming this is the logged-in parent
|
||||
|
||||
// Get parent name and school ID
|
||||
$parent = $this->db->table('users')
|
||||
->select('firstname, lastname, school_id')
|
||||
->where('id', $parentId)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
$parentName = isset($parent['firstname'], $parent['lastname'])
|
||||
? $parent['firstname'] . ' ' . $parent['lastname']
|
||||
: 'Parent';
|
||||
|
||||
$schoolId = $parent['school_id'] ?? null;
|
||||
|
||||
// Get latest invoice total_amount
|
||||
$latestInvoice = $this->invoiceModel->where('parent_id', $parentId)
|
||||
->orderBy('created_at', 'DESC')
|
||||
->select('total_amount')
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
$totalAmount = $latestInvoice['total_amount'] ?? 0;
|
||||
|
||||
return view('payment/payment_redirect', [
|
||||
'parentName' => $parentName,
|
||||
'totalAmount' => $totalAmount,
|
||||
'schoolId' => $schoolId,
|
||||
'modeCheck' => $modeCheck,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
public function paypal()
|
||||
{
|
||||
// Redirect to PayPal API or show instructions
|
||||
return redirect()->to('https://www.paypal.com/ncp/payment/87FJL3EV8C7NE');
|
||||
}
|
||||
|
||||
public function manual()
|
||||
@@ -189,7 +329,11 @@ class PaymentController extends ResourceController
|
||||
|
||||
// Handle file upload if present
|
||||
$proof = $this->request->getFile('proof');
|
||||
$data['proof_path'] = $this->financialAttachmentService->saveUploadedFile($proof, 'payments');
|
||||
if ($proof && $proof->isValid() && !$proof->hasMoved()) {
|
||||
$filename = $proof->getRandomName();
|
||||
$proof->move(WRITEPATH . 'uploads/payments/', $filename);
|
||||
$data['proof_path'] = $filename;
|
||||
}
|
||||
|
||||
$this->manualPaymentModel->insert($data);
|
||||
|
||||
@@ -913,13 +1057,26 @@ class PaymentController extends ResourceController
|
||||
// Optional receipt upload
|
||||
$checkFile = null;
|
||||
$paymentFile = $this->request->getFile('payment_file');
|
||||
try {
|
||||
$checkFile = $this->financialAttachmentService->saveUploadedFile(
|
||||
$paymentFile,
|
||||
$paymentMethod === 'check' ? 'checks' : ($paymentMethod === 'card' ? 'cards' : 'misc')
|
||||
);
|
||||
} catch (\RuntimeException $e) {
|
||||
return redirect()->back()->withInput()->with('error', $e->getMessage());
|
||||
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) {
|
||||
$okTypes = ['image/jpeg', 'image/png', 'application/pdf'];
|
||||
$okExts = ['jpg', 'jpeg', 'png', 'pdf'];
|
||||
|
||||
$mime = $paymentFile->getMimeType();
|
||||
$ext = strtolower($paymentFile->getClientExtension());
|
||||
|
||||
if (!in_array($mime, $okTypes, true) || !in_array($ext, $okExts, true)) {
|
||||
return redirect()->back()->withInput()->with('error', 'Unsupported file type. Use JPG, PNG, or PDF.');
|
||||
}
|
||||
if ($paymentFile->getSize() > 5 * 1024 * 1024) {
|
||||
return redirect()->back()->withInput()->with('error', 'File too large. Max 5MB.');
|
||||
}
|
||||
|
||||
$fileName = $paymentFile->getRandomName();
|
||||
$subdir = ($paymentMethod === 'check') ? 'checks' : (($paymentMethod === 'card') ? 'cards' : 'misc');
|
||||
$targetDir = WRITEPATH . 'uploads/' . $subdir . '/';
|
||||
if (!is_dir($targetDir)) @mkdir($targetDir, 0775, true);
|
||||
$paymentFile->move($targetDir, $fileName);
|
||||
$checkFile = $fileName;
|
||||
}
|
||||
$this->db->transBegin();
|
||||
|
||||
@@ -939,7 +1096,10 @@ class PaymentController extends ResourceController
|
||||
$invYear = (string)($row['school_year'] ?? $this->schoolYear);
|
||||
|
||||
// Recompute invoice totals from tuition + events + additional charges
|
||||
$currentBalance = (float) $this->invoiceLedgerService->recalculateInvoice($invoiceId)['balance'];
|
||||
$this->recalculateInvoice($invoiceId, $invYear);
|
||||
|
||||
// Authoritative balance
|
||||
$currentBalance = $this->getCurrentInvoiceBalance($invoiceId);
|
||||
|
||||
if ($amount > $currentBalance + 0.00001) {
|
||||
$this->db->transRollback();
|
||||
@@ -975,9 +1135,7 @@ class PaymentController extends ResourceController
|
||||
$this->schoolYear,
|
||||
$this->semester,
|
||||
$checkNumber,
|
||||
$installmentSeq,
|
||||
(array) $this->invoiceModel->find($invoiceId),
|
||||
$currentBalance
|
||||
$installmentSeq
|
||||
);
|
||||
|
||||
if (!$ok) {
|
||||
@@ -986,10 +1144,11 @@ class PaymentController extends ResourceController
|
||||
}
|
||||
|
||||
// Ensure invoice totals/balance reflect discounts and this payment
|
||||
$ledger = $this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||
$this->recalculateInvoice($invoiceId, $this->schoolYear);
|
||||
|
||||
// Post-payment balance from snapshot
|
||||
$postBalance = (float) ($ledger['balance'] ?? max(0.0, round($initialPreBalance - $amount, 2)));
|
||||
$postBalance = (float)round($initialPreBalance - $amount, 2);
|
||||
if ($postBalance < 0) $postBalance = 0.0;
|
||||
|
||||
// Optional enrollment update
|
||||
$enrollmentupdated = $this->updateEnrollmentStatusIfPaid($invoiceId);
|
||||
@@ -1076,21 +1235,20 @@ class PaymentController extends ResourceController
|
||||
$checkFile = $payment['check_file']; // default keep old file
|
||||
|
||||
// Handle optional check or card payment receipt upload
|
||||
try {
|
||||
$paymentFile = $this->request->getFile('payment_file');
|
||||
if (strtolower($paymentMethod) === 'check') {
|
||||
$uploaded = $this->financialAttachmentService->saveUploadedFile($paymentFile, 'checks');
|
||||
if ($uploaded !== null) {
|
||||
$checkFile = $uploaded;
|
||||
}
|
||||
} elseif (strtolower($paymentMethod) === 'card') {
|
||||
$uploaded = $this->financialAttachmentService->saveUploadedFile($paymentFile, 'cards');
|
||||
if ($uploaded !== null) {
|
||||
$checkFile = $uploaded;
|
||||
}
|
||||
if (strtolower($paymentMethod) === 'check') {
|
||||
$paymentFile = $this->request->getFile('payment_file'); // ✅ Updated to payment_file
|
||||
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) {
|
||||
$fileName = $paymentFile->getRandomName();
|
||||
$paymentFile->move(WRITEPATH . 'uploads/checks/', $fileName);
|
||||
$checkFile = $fileName;
|
||||
}
|
||||
} elseif (strtolower($paymentMethod) === 'card') {
|
||||
$paymentFile = $this->request->getFile('payment_file'); // ✅ Updated to payment_file
|
||||
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) {
|
||||
$fileName = $paymentFile->getRandomName();
|
||||
$paymentFile->move(WRITEPATH . 'uploads/cards/', $fileName);
|
||||
$checkFile = $fileName; // reuse for compatibility
|
||||
}
|
||||
} catch (\RuntimeException $e) {
|
||||
return redirect()->back()->withInput()->with('error', $e->getMessage());
|
||||
}
|
||||
|
||||
// ❌ Validate amount - negative or zero
|
||||
@@ -1101,51 +1259,41 @@ class PaymentController extends ResourceController
|
||||
);
|
||||
}
|
||||
|
||||
$this->db->transBegin();
|
||||
// 🔄 Recalculate invoice first to ensure totals reflect tuition + events + additional
|
||||
$this->recalculateInvoice($payment['invoice_id'], $this->schoolYear);
|
||||
|
||||
try {
|
||||
$invoiceId = (int) ($payment['invoice_id'] ?? 0);
|
||||
$lockedInvoice = $this->db->query(
|
||||
'SELECT id FROM invoices WHERE id = ? FOR UPDATE',
|
||||
[$invoiceId]
|
||||
)->getRowArray();
|
||||
// 🔄 Get current balance based on actual payments (with school_year filter)
|
||||
// We need to calculate what the balance would be WITHOUT the current payment being edited
|
||||
$currentBalance = $this->getCurrentInvoiceBalanceExcludingPayment($payment['invoice_id'], $paymentId);
|
||||
|
||||
if (!$lockedInvoice) {
|
||||
$this->db->transRollback();
|
||||
return redirect()->back()->with('error', 'Linked invoice not found.');
|
||||
}
|
||||
|
||||
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||
$currentBalance = $this->getCurrentInvoiceBalanceExcludingPayment($invoiceId, $paymentId);
|
||||
|
||||
if ($paidAmount > $currentBalance + 0.00001) {
|
||||
$this->db->transRollback();
|
||||
return redirect()->back()->with(
|
||||
'error',
|
||||
'Entered amount (' . number_format($paidAmount, 2) . ') exceeds remaining balance (' . number_format($currentBalance, 2) . ').'
|
||||
);
|
||||
}
|
||||
|
||||
$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.');
|
||||
if ($paidAmount > $currentBalance) {
|
||||
return redirect()->back()->with(
|
||||
'error',
|
||||
'Entered amount (' . number_format($paidAmount, 2) . ') exceeds remaining balance (' . number_format($currentBalance, 2) . ').'
|
||||
);
|
||||
}
|
||||
|
||||
// ✅ Update edited payment with check_number
|
||||
$updateData = [
|
||||
'paid_amount' => $paidAmount,
|
||||
'payment_method' => strtolower($paymentMethod),
|
||||
'check_file' => $checkFile,
|
||||
'updated_by' => session()->get('user_id')
|
||||
];
|
||||
|
||||
// ✅ 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.');
|
||||
}
|
||||
|
||||
|
||||
@@ -1154,7 +1302,164 @@ class PaymentController extends ResourceController
|
||||
*/
|
||||
private function recalculateInvoice($invoiceId, $schoolYear)
|
||||
{
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $invoiceId);
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) return;
|
||||
|
||||
$parentId = (int)($invoice['parent_id'] ?? 0);
|
||||
if ($parentId <= 0) return;
|
||||
|
||||
// ---- Tuition (recompute from enrollments) ----
|
||||
$enrollments = $this->enrollmentModel
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
|
||||
$registered = [];
|
||||
$withdrawn = [];
|
||||
foreach ($enrollments as $e) {
|
||||
$row = [
|
||||
'student_id' => (int)($e['student_id'] ?? 0),
|
||||
'class_section_id' => $e['class_section_id'] ?? null,
|
||||
'enrollment_status'=> (string)($e['enrollment_status'] ?? ''),
|
||||
];
|
||||
if (in_array($row['enrollment_status'], ['enrolled','payment pending'], true)) {
|
||||
$registered[] = $row;
|
||||
} elseif (in_array($row['enrollment_status'], ['withdrawn','refund pending','withdraw under review'], true)) {
|
||||
$withdrawn[] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
// Refund window check – if after deadline, withdrawn still billed
|
||||
$refundDeadline = (string)($this->configModel->getConfig('refund_deadline') ?? '');
|
||||
$refundAllowed = true;
|
||||
try {
|
||||
$tzName = (string) (config('School')->attendance['timezone'] ?? user_timezone());
|
||||
$tz = new \DateTimeZone($tzName);
|
||||
$today = new \DateTimeImmutable('today', $tz);
|
||||
$deadline = new \DateTimeImmutable($refundDeadline, $tz);
|
||||
$refundAllowed = $today <= $deadline;
|
||||
} catch (\Throwable $e) {
|
||||
$refundAllowed = true;
|
||||
}
|
||||
|
||||
$tuitionStudents = $registered;
|
||||
if (!$refundAllowed) {
|
||||
$tuitionStudents = array_merge($tuitionStudents, $withdrawn);
|
||||
}
|
||||
|
||||
$tuitionStudents = array_values(array_filter($tuitionStudents, function ($student) use ($schoolYear) {
|
||||
$sid = (int)($student['student_id'] ?? 0);
|
||||
return $sid > 0 && $this->studentClassModel->hasNonEventAssignment($sid, $schoolYear);
|
||||
}));
|
||||
|
||||
// Grade threshold and fees
|
||||
$gradeFee = (int)($this->configModel->getConfig('grade_fee') ?? 9);
|
||||
$firstStudentFee = (float)($this->configModel->getConfig('first_student_fee') ?? 350);
|
||||
$secondStudentFee = (float)($this->configModel->getConfig('second_student_fee') ?? 200);
|
||||
$youthFee = (float)($this->configModel->getConfig('youth_fee') ?? 180);
|
||||
|
||||
// Normalize grades for tuition students
|
||||
foreach ($tuitionStudents as &$s) {
|
||||
$name = null;
|
||||
if (!empty($s['class_section_id'])) {
|
||||
$name = $this->classSectionModel->getClassSectionNameBySectionId($s['class_section_id']);
|
||||
}
|
||||
$s['grade_name'] = is_string($name) ? strtoupper(trim($name)) : 'N/A';
|
||||
}
|
||||
unset($s);
|
||||
|
||||
// Count regular vs youth and compute tuition
|
||||
$regularCount = 0;
|
||||
$youthCount = 0;
|
||||
foreach ($tuitionStudents as $s) {
|
||||
$lvl = $this->parseGradeLevel($s['grade_name']);
|
||||
if ($lvl > $gradeFee) $youthCount++; else $regularCount++;
|
||||
}
|
||||
|
||||
$tuitionSubtotal = 0.0;
|
||||
$tuitionSubtotal += $youthCount * $youthFee;
|
||||
if ($regularCount >= 2) {
|
||||
$tuitionSubtotal += $firstStudentFee + ($regularCount - 1) * $secondStudentFee;
|
||||
} elseif ($regularCount === 1) {
|
||||
$tuitionSubtotal += $firstStudentFee;
|
||||
}
|
||||
|
||||
// ---- Event charges (parent-year) ----
|
||||
$eventSubtotal = 0.0;
|
||||
try {
|
||||
$events = $this->eventChargesModel->getChargesWithEventInfo($parentId, $schoolYear) ?? [];
|
||||
foreach ($events as $ev) { $eventSubtotal += (float)($ev['charged'] ?? 0.0); }
|
||||
} catch (\Throwable $e) {}
|
||||
|
||||
// ---- Additional charges (per-invoice) ----
|
||||
$additionalSubtotal = 0.0;
|
||||
try {
|
||||
$rows = $this->additionalChargeModel
|
||||
->select('charge_type, amount')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('status', 'applied')
|
||||
->findAll();
|
||||
foreach ($rows as $r) {
|
||||
$amt = (float)($r['amount'] ?? 0);
|
||||
$typ = strtolower((string)($r['charge_type'] ?? 'add'));
|
||||
if ($typ === 'deduct') $amt = -abs($amt); else $amt = abs($amt);
|
||||
$additionalSubtotal += $amt;
|
||||
}
|
||||
} catch (\Throwable $e) {}
|
||||
|
||||
$newTotal = round($tuitionSubtotal + $eventSubtotal + $additionalSubtotal, 2);
|
||||
|
||||
// ---- Payments / Discounts / Refunds ----
|
||||
$db = $this->db;
|
||||
$table = $this->paymentModel->table;
|
||||
$hasStatus = $db->fieldExists('status', $table);
|
||||
$hasVoid = $db->fieldExists('is_void', $table);
|
||||
$exclude = ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'];
|
||||
|
||||
$qb = $this->paymentModel
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('school_year', $schoolYear);
|
||||
|
||||
if ($hasStatus) {
|
||||
$qb->groupStart()
|
||||
->whereNotIn('status', $exclude)
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
if ($hasVoid) {
|
||||
$qb->groupStart()
|
||||
->where('is_void', 0)
|
||||
->orWhere('is_void IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
$payments = $qb->findAll();
|
||||
$totalPaid = 0.0;
|
||||
foreach ($payments as $p) { $totalPaid += (float)($p['paid_amount'] ?? 0); }
|
||||
|
||||
$discRow = $this->db->table('discount_usages')
|
||||
->select('COALESCE(SUM(discount_amount),0) AS total_disc')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->get()->getRowArray();
|
||||
$totalDisc = (float)($discRow['total_disc'] ?? 0);
|
||||
|
||||
$refundRow = $this->db->table('refunds')
|
||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->whereIn('status', ['Partial','Paid'])
|
||||
->get()->getRowArray();
|
||||
$totalRefundPaid = (float)($refundRow['total_refund_paid'] ?? 0);
|
||||
|
||||
$newBalance = max(0.0, $newTotal - $totalDisc - $totalPaid - $totalRefundPaid);
|
||||
$newStatus = ($newBalance <= 0.00001) ? 'Paid' : (($totalPaid > 0) ? 'Partially Paid' : 'Unpaid');
|
||||
|
||||
$this->invoiceModel->update($invoiceId, [
|
||||
'total_amount' => $newTotal,
|
||||
'paid_amount' => $totalPaid,
|
||||
'balance' => $newBalance,
|
||||
'status' => $newStatus,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1216,28 +1521,106 @@ class PaymentController extends ResourceController
|
||||
/** Get current invoice balance = total - payments - discounts - refundsPaid (no school_year filter). */
|
||||
private function getCurrentInvoiceBalance(int $invoiceId): float
|
||||
{
|
||||
try {
|
||||
return (float) ($this->invoiceLedgerService->calculateInvoice($invoiceId)['balance'] ?? 0.0);
|
||||
} catch (\Throwable $e) {
|
||||
return 0.0;
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) return 0.0;
|
||||
|
||||
$db = $this->db;
|
||||
$table = $this->paymentModel->table; // usually 'payments'
|
||||
$hasStatus = $db->fieldExists('status', $table);
|
||||
$hasVoid = $db->fieldExists('is_void', $table);
|
||||
|
||||
$qb = $this->paymentModel
|
||||
->select('COALESCE(SUM(paid_amount),0) AS total_paid')
|
||||
->where('invoice_id', $invoiceId);
|
||||
|
||||
if ($hasStatus) {
|
||||
$qb->groupStart()
|
||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
if ($hasVoid) {
|
||||
$qb->groupStart()
|
||||
->where('is_void', 0)
|
||||
->orWhere('is_void IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
$row = $qb->first();
|
||||
$totalPaid = (float)($row['total_paid'] ?? 0);
|
||||
|
||||
// Discount sum on this invoice
|
||||
$discRow = $this->db->table('discount_usages')
|
||||
->select('COALESCE(SUM(discount_amount),0) AS total_disc')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->get()->getRowArray();
|
||||
$totalDisc = (float)($discRow['total_disc'] ?? 0);
|
||||
|
||||
// Refunds paid
|
||||
$refundRow = $this->db->table('refunds')
|
||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->whereIn('status', ['Partial','Paid'])
|
||||
->get()->getRowArray();
|
||||
$totalRefundPaid = (float)($refundRow['total_refund_paid'] ?? 0);
|
||||
|
||||
$total = (float)($invoice['total_amount'] ?? 0);
|
||||
|
||||
return max(0.0, round($total - $totalPaid - $totalDisc - $totalRefundPaid, 2));
|
||||
}
|
||||
|
||||
/** Balance excluding a specific payment (for edit scenarios) and subtracting discounts/refunds. */
|
||||
private function getCurrentInvoiceBalanceExcludingPayment(int $invoiceId, int $excludePaymentId): float
|
||||
{
|
||||
$payment = $this->paymentModel->find($excludePaymentId);
|
||||
if (!$payment) {
|
||||
return $this->getCurrentInvoiceBalance($invoiceId);
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) return 0.0;
|
||||
|
||||
$db = $this->db;
|
||||
$table = $this->paymentModel->table;
|
||||
$hasStatus = $db->fieldExists('status', $table);
|
||||
$hasVoid = $db->fieldExists('is_void', $table);
|
||||
|
||||
$qb = $this->paymentModel
|
||||
->select('COALESCE(SUM(paid_amount),0) AS total_paid')
|
||||
->where('invoice_id', $invoiceId)
|
||||
->where('id !=', $excludePaymentId);
|
||||
|
||||
if ($hasStatus) {
|
||||
$qb->groupStart()
|
||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
||||
->orWhere('status IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
$currentBalance = $this->getCurrentInvoiceBalance($invoiceId);
|
||||
$status = FinancialStatus::normalizePaymentStatus($payment['status'] ?? null);
|
||||
if (in_array($status, FinancialStatus::EXCLUDED_PAYMENT_STATUSES, true)) {
|
||||
return $currentBalance;
|
||||
if ($hasVoid) {
|
||||
$qb->groupStart()
|
||||
->where('is_void', 0)
|
||||
->orWhere('is_void IS NULL', null, false)
|
||||
->groupEnd();
|
||||
}
|
||||
|
||||
return max(0.0, round($currentBalance + (float) ($payment['paid_amount'] ?? 0), 2));
|
||||
$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));
|
||||
}
|
||||
|
||||
|
||||
@@ -1272,11 +1655,9 @@ class PaymentController extends ResourceController
|
||||
$schoolYear = null,
|
||||
$semester = null,
|
||||
$checkNumber = null,
|
||||
?int $installmentSeq = null,
|
||||
?array $invoice = null,
|
||||
?float $currentBalance = null
|
||||
?int $installmentSeq = null // <-- NOW: the installment sequence (1,2,3,...) for this invoice
|
||||
) {
|
||||
$invoice = $invoice ?? $this->invoiceModel->find($invoiceId);
|
||||
$invoice = $this->invoiceModel->find($invoiceId);
|
||||
if (!$invoice) {
|
||||
return false;
|
||||
}
|
||||
@@ -1297,26 +1678,49 @@ class PaymentController extends ResourceController
|
||||
}
|
||||
|
||||
|
||||
$preBalance = $currentBalance ?? $this->getCurrentInvoiceBalance((int) $invoiceId);
|
||||
$newBalance = max(0.0, round($preBalance - (float) $amount, 2));
|
||||
// Compute new totals
|
||||
$newPaid = (float) $invoice['paid_amount'] + (float) $amount;
|
||||
$newBalance = (float) $invoice['balance'] - (float) $amount;
|
||||
if ($newBalance == $invoice['total_amount']) {
|
||||
$paymentStatus = 'Unpaid';
|
||||
} elseif ($newBalance > 0 && $newBalance < $invoice['total_amount']) {
|
||||
$paymentStatus = 'Partially Paid';
|
||||
} elseif ($newBalance <= 0.00001) {
|
||||
$paymentStatus = 'Paid';
|
||||
} else {
|
||||
$paymentStatus = $invoice['status']; // fallback
|
||||
}
|
||||
|
||||
// Update invoice
|
||||
$invoiceUpdateData = [
|
||||
'paid_amount' => $newPaid,
|
||||
'balance' => $newBalance,
|
||||
'status' => $paymentStatus,
|
||||
'updated_by' => session()->get('user_id'),
|
||||
];
|
||||
if (!$this->invoiceModel->update($invoiceId, $invoiceUpdateData)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Store the *sequence* in number_of_installments (kept for schema compatibility)
|
||||
// Consider renaming the column to `installment_seq` in a future migration.
|
||||
$paymentData = [
|
||||
'parent_id' => $invoice['parent_id'],
|
||||
'invoice_id' => $invoiceId,
|
||||
'total_amount' => $invoice['total_amount'],
|
||||
'paid_amount' => $amount,
|
||||
'balance' => $newBalance,
|
||||
'parent_id' => $invoice['parent_id'],
|
||||
'invoice_id' => $invoiceId,
|
||||
'total_amount' => $invoice['total_amount'],
|
||||
'paid_amount' => $amount,
|
||||
'balance' => $newBalance,
|
||||
'number_of_installments' => $installmentSeq, // <-- installment sequence (1,2,3,...)
|
||||
'installment_seq' => $installmentSeq,
|
||||
'transaction_id' => $transactionId,
|
||||
'payment_method' => strtolower($paymentMethod),
|
||||
'payment_date' => $paymentDate,
|
||||
'status' => FinancialStatus::PAYMENT_RECORDED,
|
||||
'check_file' => $checkFile,
|
||||
'check_number' => (strtolower($paymentMethod) === 'check') ? $checkNumber : null,
|
||||
'updated_by' => session()->get('user_id'),
|
||||
'school_year' => $schoolYear ?? $this->schoolYear,
|
||||
'semester' => $semester ?? $this->semester,
|
||||
'transaction_id' => $transactionId,
|
||||
'payment_method' => strtolower($paymentMethod),
|
||||
'payment_date' => $paymentDate,
|
||||
'status' => $paymentStatus,
|
||||
'check_file' => $checkFile,
|
||||
'check_number' => (strtolower($paymentMethod) === 'check') ? $checkNumber : null,
|
||||
'updated_by' => session()->get('user_id'),
|
||||
'school_year' => $schoolYear ?? $this->schoolYear,
|
||||
'semester' => $semester ?? $this->semester,
|
||||
// 'installment_index' => $installmentSeq, // use if you add a dedicated column later
|
||||
];
|
||||
|
||||
if (!$this->paymentModel->insert($paymentData)) {
|
||||
@@ -1337,53 +1741,35 @@ class PaymentController extends ResourceController
|
||||
->countAllResults();
|
||||
}
|
||||
|
||||
public function servePaymentFile(int $paymentId, string $mode = 'download')
|
||||
public function serveCheckFile($filename, $mode = 'download')
|
||||
{
|
||||
$payment = $this->paymentModel->find($paymentId);
|
||||
if (!$payment || empty($payment['check_file'])) {
|
||||
throw PageNotFoundException::forPageNotFound('Payment file not found.');
|
||||
$filename = basename($filename);
|
||||
$roots = [
|
||||
WRITEPATH . 'uploads/checks/' . $filename,
|
||||
WRITEPATH . 'uploads/cards/' . $filename,
|
||||
WRITEPATH . 'uploads/misc/' . $filename,
|
||||
WRITEPATH . 'uploads/' . $filename, // final fallback
|
||||
];
|
||||
|
||||
$path = null;
|
||||
foreach ($roots as $candidate) {
|
||||
if (is_file($candidate)) {
|
||||
$path = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$this->canViewPayment($payment)) {
|
||||
return $this->response->setStatusCode(403);
|
||||
}
|
||||
|
||||
$subdir = match (strtolower((string) ($payment['payment_method'] ?? ''))) {
|
||||
'check' => 'checks',
|
||||
'card', 'debit/credit card' => 'cards',
|
||||
default => 'misc',
|
||||
};
|
||||
|
||||
$path = $this->financialAttachmentService->resolvePath($subdir, (string) $payment['check_file']);
|
||||
if ($path === null) {
|
||||
throw PageNotFoundException::forPageNotFound('Payment file not found.');
|
||||
if (!$path) {
|
||||
throw new \CodeIgniter\Exceptions\PageNotFoundException('Payment file not found: ' . esc($filename));
|
||||
}
|
||||
|
||||
if ($mode === 'inline') {
|
||||
return $this->response
|
||||
->setHeader('Content-Type', $this->financialAttachmentService->detectMime($path))
|
||||
->setHeader('Content-Disposition', 'inline; filename="' . basename($path) . '"')
|
||||
->setHeader('Content-Type', mime_content_type($path))
|
||||
->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"')
|
||||
->setBody(file_get_contents($path));
|
||||
}
|
||||
|
||||
return $this->response->download($path, null);
|
||||
}
|
||||
|
||||
private function canViewPayment(array $payment): bool
|
||||
{
|
||||
$roles = array_map('strtolower', (array) (session()->get('roles') ?? []));
|
||||
$activeRole = strtolower((string) (session()->get('role') ?? ''));
|
||||
if ($activeRole !== '' && !in_array($activeRole, $roles, true)) {
|
||||
$roles[] = $activeRole;
|
||||
}
|
||||
|
||||
$staffRoles = ['administrator', 'administrative staff', 'principal', 'teacher', 'teacher_assistant'];
|
||||
foreach ($staffRoles as $role) {
|
||||
if (in_array($role, $roles, true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return in_array('parent', $roles, true) && (int) ($payment['parent_id'] ?? 0) === (int) session()->get('user_id');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
<?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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -438,7 +438,6 @@ class ProjectController extends Controller
|
||||
// Step 1: Get student IDs from student_class table
|
||||
$studentClassRows = $studentClassModel
|
||||
->select('student_id')
|
||||
->distinct()
|
||||
->where('class_section_id', $classSectionId)
|
||||
->where('school_year', $schoolYear)
|
||||
->findAll();
|
||||
@@ -495,7 +494,10 @@ class ProjectController extends Controller
|
||||
$studentModel = new StudentModel();
|
||||
$projectModel = new ProjectModel();
|
||||
|
||||
$studentClasses = $studentClassModel->getClassStudents($classSectionId, $this->schoolYear, null);
|
||||
$studentClasses = $studentClassModel
|
||||
->active()
|
||||
->where('student_class.class_section_id', $classSectionId)
|
||||
->findAll();
|
||||
$students = [];
|
||||
|
||||
foreach ($studentClasses as $sc) {
|
||||
|
||||
@@ -3,15 +3,12 @@
|
||||
namespace App\Controllers\View;
|
||||
|
||||
use App\Controllers\BaseController;
|
||||
use App\Libraries\FinancialAttachmentService;
|
||||
use App\Libraries\InvoiceLedgerService;
|
||||
use App\Models\RefundModel;
|
||||
use App\Models\UserModel;
|
||||
use App\Models\PaymentModel;
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\InvoiceModel;
|
||||
use App\Models\EnrollmentModel;
|
||||
use CodeIgniter\Exceptions\PageNotFoundException;
|
||||
|
||||
class RefundController extends BaseController
|
||||
{
|
||||
@@ -21,8 +18,6 @@ class RefundController extends BaseController
|
||||
protected ConfigurationModel $configModel;
|
||||
protected InvoiceModel $invoiceModel;
|
||||
protected EnrollmentModel $enrollmentModel;
|
||||
protected InvoiceLedgerService $invoiceLedgerService;
|
||||
protected FinancialAttachmentService $financialAttachmentService;
|
||||
protected $db;
|
||||
|
||||
// Allowed request types (mapped to your `refunds.request` column)
|
||||
@@ -38,8 +33,6 @@ class RefundController extends BaseController
|
||||
$this->configModel = new ConfigurationModel();
|
||||
$this->invoiceModel = new InvoiceModel();
|
||||
$this->enrollmentModel = new EnrollmentModel();
|
||||
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||
$this->financialAttachmentService = new FinancialAttachmentService();
|
||||
$this->db = \Config\Database::connect();
|
||||
}
|
||||
|
||||
@@ -452,14 +445,6 @@ class RefundController extends BaseController
|
||||
return $this->response->setJSON(['error' => 'Failed to create refund request.']);
|
||||
}
|
||||
|
||||
if (!empty($invoiceId)) {
|
||||
try {
|
||||
$this->invoiceLedgerService->recalculateInvoice((int) $invoiceId);
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'requestRefund recalc failed: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Fire refundPending notification/event for newly created refunds
|
||||
try {
|
||||
$user = $this->userModel->select('id, email, firstname, lastname')->find($parentId) ?: [];
|
||||
@@ -482,36 +467,13 @@ class RefundController extends BaseController
|
||||
// Approve refund (no money movement)
|
||||
public function approveRefund(int $refundId)
|
||||
{
|
||||
$refund = $this->refundModel->find($refundId);
|
||||
if (!$refund) {
|
||||
return $this->response->setJSON(['error' => 'Refund not found']);
|
||||
}
|
||||
|
||||
$this->db->transBegin();
|
||||
|
||||
try {
|
||||
if (!empty($refund['invoice_id'])) {
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $refund['invoice_id']]);
|
||||
}
|
||||
|
||||
$ok = $this->refundModel->update($refundId, [
|
||||
'status' => 'Approved',
|
||||
'approved_at' => utc_now(),
|
||||
'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;
|
||||
}
|
||||
$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'),
|
||||
]);
|
||||
|
||||
return $this->response->setJSON($ok ? ['success' => 'Refund approved'] : ['error' => 'Approve failed']);
|
||||
}
|
||||
@@ -519,36 +481,13 @@ class RefundController extends BaseController
|
||||
// Reject refund
|
||||
public function rejectRefund(int $refundId)
|
||||
{
|
||||
$refund = $this->refundModel->find($refundId);
|
||||
if (!$refund) {
|
||||
return $this->response->setJSON(['error' => 'Refund not found']);
|
||||
}
|
||||
|
||||
$this->db->transBegin();
|
||||
|
||||
try {
|
||||
if (!empty($refund['invoice_id'])) {
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $refund['invoice_id']]);
|
||||
}
|
||||
|
||||
$ok = $this->refundModel->update($refundId, [
|
||||
'status' => 'Rejected',
|
||||
'approved_at' => utc_now(),
|
||||
'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;
|
||||
}
|
||||
$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'),
|
||||
]);
|
||||
|
||||
return $this->response->setJSON($ok ? ['success' => 'Refund rejected'] : ['error' => 'Reject failed']);
|
||||
}
|
||||
@@ -587,21 +526,17 @@ class RefundController extends BaseController
|
||||
// Optional file upload for Check
|
||||
$checkFileName = $refund['check_file'] ?? null;
|
||||
if ($refundMethod === 'Check') {
|
||||
try {
|
||||
$checkFile = $this->request->getFile('check_file');
|
||||
$uploaded = $this->financialAttachmentService->saveUploadedFile($checkFile, 'checks');
|
||||
if ($uploaded !== null) {
|
||||
$checkFileName = $uploaded;
|
||||
}
|
||||
} catch (\RuntimeException $e) {
|
||||
return $this->response->setJSON(['error' => $e->getMessage()]);
|
||||
$checkFile = $this->request->getFile('check_file');
|
||||
if ($checkFile && $checkFile->isValid() && !$checkFile->hasMoved()) {
|
||||
$checkFileName = $checkFile->getRandomName();
|
||||
$checkFile->move(WRITEPATH . 'uploads/checks/', $checkFileName);
|
||||
}
|
||||
}
|
||||
|
||||
$newStatus = ($total < $target) ? 'Partial' : 'Paid';
|
||||
|
||||
$db = db_connect();
|
||||
$db->transBegin();
|
||||
$db->transStart();
|
||||
|
||||
// 0) If this refund is not tied to an invoice yet, assign it to the most overpaid invoice
|
||||
$assignInvoiceId = null;
|
||||
@@ -660,32 +595,26 @@ class RefundController extends BaseController
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$affectedInvoiceId = (int) ($assignInvoiceId ?? $refund['invoice_id'] ?? 0);
|
||||
if ($affectedInvoiceId > 0) {
|
||||
$db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$affectedInvoiceId]);
|
||||
}
|
||||
// 1) Update refund row
|
||||
$this->refundModel->update($refundId, [
|
||||
'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,
|
||||
// tie to invoice if determined
|
||||
'invoice_id' => $assignInvoiceId ?? $refund['invoice_id'],
|
||||
]);
|
||||
|
||||
$this->refundModel->update($refundId, [
|
||||
'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,
|
||||
]);
|
||||
// 2) Optional: If you want an accounting journal entry for payouts, write to a dedicated table.
|
||||
// We no longer insert a negative row into payments to avoid schema/validation conflicts.
|
||||
|
||||
if ($affectedInvoiceId > 0) {
|
||||
$this->invoiceLedgerService->recalculateInvoice($affectedInvoiceId);
|
||||
}
|
||||
$db->transComplete();
|
||||
|
||||
$db->transCommit();
|
||||
} catch (\Throwable $e) {
|
||||
$db->transRollback();
|
||||
log_message('error', 'updatePayment failed: ' . $e->getMessage());
|
||||
if ($db->transStatus() === false) {
|
||||
return $this->response->setJSON(['error' => 'Failed to update payment.']);
|
||||
}
|
||||
|
||||
@@ -841,77 +770,16 @@ class RefundController extends BaseController
|
||||
return $this->response->setJSON(['error' => 'Refund not found.']);
|
||||
}
|
||||
|
||||
$this->db->transBegin();
|
||||
|
||||
try {
|
||||
if (!empty($refund['invoice_id'])) {
|
||||
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $refund['invoice_id']]);
|
||||
}
|
||||
|
||||
$ok = $this->refundModel->update($refundId, [
|
||||
'status' => $status,
|
||||
'reason' => $reason,
|
||||
'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;
|
||||
}
|
||||
$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'),
|
||||
]);
|
||||
|
||||
return $this->response->setJSON($ok ? ['success' => 'Refund status updated successfully.']
|
||||
: ['error' => 'Failed to update refund status.']);
|
||||
}
|
||||
|
||||
public function serveRefundFile(int $refundId, string $mode = 'download')
|
||||
{
|
||||
$refund = $this->refundModel->find($refundId);
|
||||
if (!$refund || empty($refund['check_file'])) {
|
||||
throw PageNotFoundException::forPageNotFound('Refund file not found.');
|
||||
}
|
||||
|
||||
if (!$this->canViewRefund($refund)) {
|
||||
return $this->response->setStatusCode(403);
|
||||
}
|
||||
|
||||
$path = $this->financialAttachmentService->resolvePath('checks', (string) $refund['check_file']);
|
||||
if ($path === null) {
|
||||
throw PageNotFoundException::forPageNotFound('Refund file not found.');
|
||||
}
|
||||
|
||||
if ($mode === 'inline') {
|
||||
return $this->response
|
||||
->setHeader('Content-Type', $this->financialAttachmentService->detectMime($path))
|
||||
->setHeader('Content-Disposition', 'inline; filename="' . basename($path) . '"')
|
||||
->setBody(file_get_contents($path));
|
||||
}
|
||||
|
||||
return $this->response->download($path, null);
|
||||
}
|
||||
|
||||
private function canViewRefund(array $refund): bool
|
||||
{
|
||||
$roles = array_map('strtolower', (array) (session()->get('roles') ?? []));
|
||||
$activeRole = strtolower((string) (session()->get('role') ?? ''));
|
||||
if ($activeRole !== '' && !in_array($activeRole, $roles, true)) {
|
||||
$roles[] = $activeRole;
|
||||
}
|
||||
|
||||
foreach (['administrator', 'administrative staff', 'principal', 'teacher', 'teacher_assistant'] as $role) {
|
||||
if (in_array($role, $roles, true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return in_array('parent', $roles, true) && (int) ($refund['parent_id'] ?? 0) === (int) session()->get('user_id');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,8 +173,16 @@ class RegisterController extends Controller
|
||||
$existingUser = $this->userModel->where('email', $post['email'])->first();
|
||||
|
||||
if ($existingUser) {
|
||||
return redirect()->back()->withInput()->with('error',
|
||||
'This email address is already registered. Please check your email or log in.');
|
||||
// Step 2: Check if the user has a token (i.e., not verified yet)
|
||||
if (!empty($existingUser['token']) && $existingUser['is_verified'] == 0) {
|
||||
// User exists and is unverified
|
||||
return redirect()->back()->withInput()->with('error',
|
||||
'This email address is already registered and is pending activation. Please check your email to activate your account.');
|
||||
} else {
|
||||
// User exists and is already active or has no token
|
||||
return redirect()->back()->withInput()->with('error',
|
||||
'The email address you entered is already in use. Please try a different one.');
|
||||
}
|
||||
}
|
||||
|
||||
/* ───────────── 6. Determine role ───────────── */
|
||||
@@ -186,7 +194,6 @@ class RegisterController extends Controller
|
||||
|
||||
/* ───────────── 7. Build & insert user ───────────── */
|
||||
$token = bin2hex(random_bytes(48));
|
||||
$tokenHash = hash('sha256', $token);
|
||||
$userData = [
|
||||
'firstname' => $post['firstname'],
|
||||
'lastname' => $post['lastname'],
|
||||
@@ -198,7 +205,7 @@ class RegisterController extends Controller
|
||||
'city' => $post['city'],
|
||||
'state' => $post['state'],
|
||||
'zip' => $post['zip'],
|
||||
'token' => $tokenHash,
|
||||
'token' => $token,
|
||||
'is_verified'=> 0,
|
||||
'accept_school_policy' => (int) $post['accept_school_policy'],
|
||||
'status' => 'Inactive',
|
||||
@@ -350,4 +357,4 @@ class RegisterController extends Controller
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,19 @@ class ReportCardsController extends PrintablesBaseController
|
||||
$semesters = array_values(array_filter(array_map(static fn($r) => (string)($r['semester'] ?? ''), $rs)));
|
||||
} 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)
|
||||
$defaults = array_values(array_filter([(string)($this->semester ?? ''), 'Fall', 'Spring'], static fn($v) => $v !== ''));
|
||||
foreach ($defaults as $d) {
|
||||
@@ -317,27 +330,18 @@ class ReportCardsController extends PrintablesBaseController
|
||||
$examCommentTypes = $isSecond
|
||||
? ['final']
|
||||
: ($isFirst ? ['midterm'] : ['midterm', 'final']);
|
||||
$wantedCommentTypes = array_merge($examCommentTypes, ['ptap', 'attendance']);
|
||||
$commentTypes = array_merge($examCommentTypes, ['ptap', 'attendance', 'attendance_comment']);
|
||||
$hasCommentReview = $this->db->fieldExists('comment_review', 'score_comments');
|
||||
$hasCommentSemester = $this->db->fieldExists('semester', 'score_comments');
|
||||
$hasCommentUpdatedAt = $this->db->fieldExists('updated_at', 'score_comments');
|
||||
$commentSelectParts = ['student_id', 'score_type', 'comment'];
|
||||
if ($hasCommentReview) {
|
||||
$commentSelectParts[] = 'comment_review';
|
||||
}
|
||||
if ($hasCommentSemester) {
|
||||
$commentSelectParts[] = 'semester';
|
||||
}
|
||||
|
||||
// Do NOT filter comments by score_type or semester here.
|
||||
// A single bad row like "Attendance Comment", "attendance-comment", or a blank semester
|
||||
// should not make one student look incomplete while the PDF can still print the comment.
|
||||
$commentSelect = $hasCommentReview
|
||||
? 'student_id, score_type, comment, comment_review'
|
||||
: 'student_id, score_type, comment';
|
||||
$commentBuilder = $this->scoreCommentModel
|
||||
->select(implode(', ', $commentSelectParts))
|
||||
->select($commentSelect)
|
||||
->whereIn('student_id', $studentIds)
|
||||
->where('school_year', $year);
|
||||
if ($hasCommentUpdatedAt) {
|
||||
$commentBuilder->orderBy('updated_at', 'DESC');
|
||||
->where('school_year', $year)
|
||||
->whereIn('score_type', $commentTypes);
|
||||
if ($sem !== '') {
|
||||
$this->applySemesterFilter($commentBuilder, $sem, 'semester');
|
||||
}
|
||||
$commentRows = [];
|
||||
try {
|
||||
@@ -345,92 +349,25 @@ class ReportCardsController extends PrintablesBaseController
|
||||
} catch (\Throwable $e) {
|
||||
}
|
||||
|
||||
$cleanComment = static function ($value): string {
|
||||
$text = (string)($value ?? '');
|
||||
$text = str_replace("\xc2\xa0", ' ', $text); // normalize non-breaking spaces
|
||||
return trim($text);
|
||||
};
|
||||
|
||||
$normalizeCommentType = static function ($value) use ($cleanComment): string {
|
||||
$type = strtolower($cleanComment($value));
|
||||
$type = preg_replace('/[^a-z0-9]+/', '_', $type);
|
||||
$type = trim((string)$type, '_');
|
||||
|
||||
$map = [
|
||||
'attendance_comment' => 'attendance',
|
||||
'attendance_comments' => 'attendance',
|
||||
'attendance' => 'attendance',
|
||||
'attendence' => 'attendance',
|
||||
'attendence_comment' => 'attendance',
|
||||
'attendence_comments' => 'attendance',
|
||||
'ptap_comment' => 'ptap',
|
||||
'ptap_comments' => 'ptap',
|
||||
'ptap' => 'ptap',
|
||||
'midterm_comment' => 'midterm',
|
||||
'midterm_comments' => 'midterm',
|
||||
'midterm' => 'midterm',
|
||||
'final_comment' => 'final',
|
||||
'final_comments' => 'final',
|
||||
'final' => 'final',
|
||||
];
|
||||
|
||||
return $map[$type] ?? $type;
|
||||
};
|
||||
|
||||
$normalizeSemester = static function ($value) use ($cleanComment): string {
|
||||
$v = strtolower($cleanComment($value));
|
||||
$v = preg_replace('/[^a-z0-9]+/', ' ', $v);
|
||||
$v = trim((string)$v);
|
||||
if (in_array($v, ['fall', 'first', 'first semester', 'semester 1', '1'], true)) {
|
||||
return 'fall';
|
||||
}
|
||||
if (in_array($v, ['spring', 'second', 'second semester', 'semester 2', '2'], true)) {
|
||||
return 'spring';
|
||||
}
|
||||
return $v;
|
||||
};
|
||||
$wantedSemester = $normalizeSemester($sem);
|
||||
|
||||
$commentsByStudent = [];
|
||||
$commentPriorityByStudent = [];
|
||||
foreach ($commentRows as $row) {
|
||||
$sid = (int)($row['student_id'] ?? 0);
|
||||
if ($sid <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$typeRaw = $normalizeCommentType($row['score_type'] ?? '');
|
||||
if ($typeRaw === '' || !in_array($typeRaw, $wantedCommentTypes, true)) {
|
||||
$typeRaw = strtolower(trim((string)($row['score_type'] ?? '')));
|
||||
if ($typeRaw === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$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;
|
||||
if ($typeRaw === 'attendance_comment') {
|
||||
$typeRaw = 'attendance';
|
||||
}
|
||||
$reviewVal = $hasCommentReview ? trim((string)($row['comment_review'] ?? '')) : '';
|
||||
$commentVal = $hasCommentReview ? $reviewVal : trim((string)($row['comment'] ?? ''));
|
||||
if ($commentVal === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rowSemester = $hasCommentSemester ? $normalizeSemester($row['semester'] ?? '') : '';
|
||||
$priority = 1;
|
||||
if ($wantedSemester !== '' && $rowSemester === $wantedSemester) {
|
||||
$priority = 3;
|
||||
} elseif ($rowSemester === '') {
|
||||
$priority = 2;
|
||||
}
|
||||
|
||||
$existingPriority = $commentPriorityByStudent[$sid][$typeRaw] ?? 0;
|
||||
if (!isset($commentsByStudent[$sid][$typeRaw]) || $priority >= $existingPriority) {
|
||||
$commentsByStudent[$sid][$typeRaw] = $commentVal;
|
||||
$commentPriorityByStudent[$sid][$typeRaw] = $priority;
|
||||
}
|
||||
$commentsByStudent[$sid][$typeRaw] = $commentVal;
|
||||
}
|
||||
|
||||
$isNumeric = static fn($v) => $v !== null && $v !== '' && is_numeric($v);
|
||||
@@ -543,20 +480,6 @@ class ReportCardsController extends PrintablesBaseController
|
||||
if (trim((string)($commentSet['ptap'] ?? '')) === '') {
|
||||
$missing[] = 'PTAP comment';
|
||||
}
|
||||
|
||||
// Keep completeness consistent with the PDF report generation:
|
||||
// the report can auto-generate an attendance comment from attendance_score.
|
||||
if (trim((string)($commentSet['attendance'] ?? '')) === '' && $isNumeric($attendanceScore)) {
|
||||
$autoAttendance = attendance_comment_from_score(
|
||||
(float)$attendanceScore,
|
||||
trim((string)($student['firstname'] ?? ''))
|
||||
);
|
||||
if ($autoAttendance !== null && trim((string)$autoAttendance) !== '') {
|
||||
$commentSet['attendance'] = $autoAttendance;
|
||||
$warnings[] = 'Attendance comment computed from attendance score';
|
||||
}
|
||||
}
|
||||
|
||||
if (trim((string)($commentSet['attendance'] ?? '')) === '') {
|
||||
$missing[] = 'Attendance comment';
|
||||
}
|
||||
@@ -935,7 +858,6 @@ class ReportCardsController extends PrintablesBaseController
|
||||
$studentName = trim(($data['student']['firstname'] ?? '') . ' ' . ($data['student']['lastname'] ?? ''));
|
||||
$gradeLabel = (string)($data['grade'] ?? ($data['class_section_name'] ?? 'N/A'));
|
||||
$today = (string)($data['report_date_display'] ?? date('m-d-Y'));
|
||||
$termRank = trim((string)($data['term_rank_display'] ?? ''));
|
||||
$firstSemScore = $data['first_semester_score'] ?? null;
|
||||
$secondSemScore = $data['second_semester_score'] ?? ($data['total_score'] ?? null);
|
||||
$finalAverage = $data['final_average'] ?? null;
|
||||
@@ -1071,91 +993,54 @@ class ReportCardsController extends PrintablesBaseController
|
||||
$gradeY = $pdf->GetY();
|
||||
$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
|
||||
) {
|
||||
$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';
|
||||
$drawGradeCell = static function (\FPDF $pdf, float $x, float $y, float $w, float $h, string $label, string $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);
|
||||
};
|
||||
|
||||
$pdf->Rect($x, $y, $w, $h);
|
||||
$pdf->SetXY($x + $pad, $y + 3);
|
||||
$pdf->SetFont('Helvetica', 'B', 11);
|
||||
$pdf->Write(5, ' Class Rank: ');
|
||||
if ($semNum === 2) {
|
||||
$firstLabel = ' 1st Semester Grade:';
|
||||
$firstValue = $numFmt($firstSemScore) . '/100';
|
||||
$secondLabel = ' 2nd Semester Grade:';
|
||||
$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);
|
||||
|
||||
$labelWidth = $pdf->GetStringWidth(' Class Rank: ');
|
||||
$pdf->SetFont('Helvetica', '', 12);
|
||||
$pdf->SetXY($x + 2 + $labelWidth, $y + 3);
|
||||
$pdf->Write(5, $rankValue);
|
||||
};
|
||||
if ($semNum === 2) {
|
||||
$firstLabel = ' 1st Semester Grade:';
|
||||
$firstValue = $numFmt($firstSemScore) . '/100';
|
||||
|
||||
$secondLabel = ' 2nd Semester Grade:';
|
||||
$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);
|
||||
|
||||
// Fall: Ranking goes to the right of 1st Semester Grade.
|
||||
$drawRankCell($pdf, $gradeX + $gradeCellWidth, $gradeY, $gradeCellWidth, $gradeCellHeight, $termRank, $gradePad);
|
||||
}
|
||||
|
||||
$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();
|
||||
$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; // match Total Semester Days column width
|
||||
$finalCellHeight = $finalScoreRowHeight;
|
||||
$finalX = $pdf->GetX();
|
||||
$finalY = $pdf->GetY();
|
||||
$pdf->Rect($finalX, $finalY, $finalCellWidth, $finalCellHeight);
|
||||
$finalPad = max(0, 2 - (4 * 0.3528)); // reduce indentation by 4pt
|
||||
$pdf->SetXY($finalX + $finalPad, $finalY + 3);
|
||||
$pdf->SetFont('Helvetica', 'B', 11);
|
||||
$pdf->Write(5, ' ' . $finalLabel . ' ');
|
||||
$finalLabelWidth = $pdf->GetStringWidth(' ' . $finalLabel . ' ');
|
||||
$pdf->SetFont('Helvetica', '', 12);
|
||||
$pdf->SetXY($finalX + 2 + $finalLabelWidth, $finalY + 3);
|
||||
$pdf->Write(5, $finalValue);
|
||||
$pdf->Ln($finalCellHeight);
|
||||
$finalScoreEndY = $finalY + $finalCellHeight;
|
||||
}
|
||||
$scoresEndY = $pdf->GetY();
|
||||
|
||||
// Legend anchored near bottom with a 3mm buffer (dynamic placement)
|
||||
$examLegendLabel = ($semNum === 1) ? 'Midterm Exam' : 'Final Exam';
|
||||
@@ -1621,16 +1506,10 @@ $scoresEndY = $pdf->GetY();
|
||||
if ($typeRaw === 'attendance_comment') {
|
||||
$typeRaw = 'attendance';
|
||||
}
|
||||
$rawComment = trim((string)($row['comment'] ?? ''));
|
||||
if ($typeRaw === 'attendance') {
|
||||
// Attendance comments must come from score_comments.comment.
|
||||
$commentVal = $rawComment;
|
||||
} else {
|
||||
$reviewVal = trim((string)($row['comment_review'] ?? ''));
|
||||
$commentVal = $this->db->fieldExists('comment_review', 'score_comments') && $reviewVal !== ''
|
||||
? $reviewVal
|
||||
: $rawComment;
|
||||
}
|
||||
$reviewVal = trim((string)($row['comment_review'] ?? ''));
|
||||
$commentVal = $this->db->fieldExists('comment_review', 'score_comments')
|
||||
? $reviewVal
|
||||
: trim((string)($row['comment'] ?? ''));
|
||||
if ($commentVal === '') {
|
||||
continue;
|
||||
}
|
||||
@@ -1680,20 +1559,6 @@ $scoresEndY = $pdf->GetY();
|
||||
$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)
|
||||
$totalSemesterDays = null;
|
||||
|
||||
@@ -1701,30 +1566,34 @@ $scoresEndY = $pdf->GetY();
|
||||
$semRange = $this->semesterRangeService->getSemesterRange($refYear, ucfirst($normSemester));
|
||||
if ($semRange) {
|
||||
try {
|
||||
// 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);
|
||||
$events = $this->calendarModel->getEventsBySchoolYearAndSemester($refYear, $normSemester);
|
||||
$noSchoolDays = [];
|
||||
foreach ($events as $event) {
|
||||
if (empty($event['no_school'])) {
|
||||
continue;
|
||||
}
|
||||
$dateStr = substr((string)($event['date'] ?? ''), 0, 10);
|
||||
if ($dateStr === '' || $dateStr < $semRange[0] || $dateStr > $semRange[1]) {
|
||||
if ($dateStr === '') {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$eventDate = new \DateTime($dateStr);
|
||||
} catch (\Throwable) {
|
||||
continue;
|
||||
}
|
||||
if ($eventDate->format('N') !== '7') {
|
||||
continue;
|
||||
}
|
||||
if ($dateStr < $semRange[0] || $dateStr > $semRange[1]) {
|
||||
continue;
|
||||
}
|
||||
$noSchoolDays[$dateStr] = true;
|
||||
}
|
||||
$sundays = $this->listSundays($semRange[0], $semRange[1]);
|
||||
$anchor = $this->resolveAnchorSunday();
|
||||
$limit = $semRange[1];
|
||||
// Only cap at "today" while the semester is still in progress.
|
||||
// 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]);
|
||||
}
|
||||
if ($anchor !== '' && $anchor >= $semRange[0]) {
|
||||
$limit = min($anchor, $semRange[1]);
|
||||
}
|
||||
$totalSemesterDays = 0;
|
||||
foreach ($sundays as $date) {
|
||||
@@ -1820,254 +1689,12 @@ $scoresEndY = $pdf->GetY();
|
||||
'second_semester_score' => $secondSemesterScore,
|
||||
'first_semester_score' => $firstSemesterScore,
|
||||
'final_average' => $finalAverage,
|
||||
'term_rank' => $termRanking,
|
||||
'term_rank_display' => $termRanking['display'] ?? null,
|
||||
'comments' => $commentMap,
|
||||
'total_score' => $secondSemesterScore,
|
||||
'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),
|
||||
* relaxing semester/year if needed. Returns ['teacher_name' => string, 'ta_names' => string[]].
|
||||
|
||||
@@ -231,36 +231,18 @@ class ScoreCommentController extends BaseController
|
||||
$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();
|
||||
|
||||
$existingAttendance = [];
|
||||
foreach ($rawComments as $c) {
|
||||
$sid = (int) $c['student_id'];
|
||||
$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;
|
||||
}
|
||||
|
||||
$sid = (int)$c['student_id'];
|
||||
$typ = (string)$c['score_type'];
|
||||
$comments[$sid][$typ] = [
|
||||
'comment' => $c['comment'] ?? null,
|
||||
'comment_review' => $c['comment_review'] ?? null,
|
||||
'commented_by' => $c['commented_by'] ?? null,
|
||||
'reviewed_by' => $c['reviewed_by'] ?? null,
|
||||
];
|
||||
|
||||
if ($typ === 'attendance') {
|
||||
$existingAttendance[$sid] = $c;
|
||||
}
|
||||
@@ -453,16 +435,6 @@ class ScoreCommentController extends BaseController
|
||||
$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();
|
||||
|
||||
$data = [
|
||||
|
||||
@@ -339,6 +339,37 @@ class ScoreController extends Controller
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
$students = $this->getStudentScores($classSectionId, $semester, $schoolYear, $teacherId);
|
||||
} catch (\Throwable $e) {
|
||||
log_message('error', 'ScoreController::submitScoresLock missing check failed: ' . $e->getMessage());
|
||||
return redirect()->back()->with('error', 'Unable to validate missing scores. Please try again.');
|
||||
}
|
||||
|
||||
$missingRows = [];
|
||||
foreach ($students as $student) {
|
||||
$missingItems = $student['missing_items'] ?? [];
|
||||
if (empty($missingItems)) {
|
||||
continue;
|
||||
}
|
||||
$studentId = (int) ($student['student_id'] ?? 0);
|
||||
$studentName = trim(($student['firstname'] ?? '') . ' ' . ($student['lastname'] ?? ''));
|
||||
if ($studentName === '') {
|
||||
$studentName = $studentId > 0 ? ('Student #' . $studentId) : 'Student';
|
||||
}
|
||||
$missingRows[] = $studentName . ': ' . implode(', ', $missingItems);
|
||||
}
|
||||
|
||||
if (!empty($missingRows)) {
|
||||
$sample = array_slice($missingRows, 0, 8);
|
||||
$message = sprintf(
|
||||
'Missing entries found for %d student(s). Fill them or mark "Missing ok" before submitting. %s',
|
||||
count($missingRows),
|
||||
$sample ? ('Examples: ' . implode(' | ', $sample)) : ''
|
||||
);
|
||||
return redirect()->back()->with('error', trim($message));
|
||||
}
|
||||
|
||||
$existing = $this->gradingLockModel->getLock($classSectionId, $semester, $schoolYear);
|
||||
if (!empty($existing) && !empty($existing['is_locked'])) {
|
||||
return redirect()->back()->with('status', 'Scores already submitted and locked.');
|
||||
@@ -1287,14 +1318,14 @@ class ScoreController extends Controller
|
||||
public function viewStudentScore()
|
||||
{
|
||||
$parentId = session()->get('user_id');
|
||||
$userType = session()->get('user_type') ?? '';
|
||||
$userType = $_SESSION['user_type'];
|
||||
$firstParentId = null;
|
||||
$releaseFall = $this->getParentScoresReleasedForSemester('Fall');
|
||||
$releaseSpring = $this->getParentScoresReleasedForSemester('Spring');
|
||||
$releaseAny = $releaseFall || $releaseSpring;
|
||||
|
||||
// Identify the firstparent based on user type
|
||||
if ($userType === 'primary' || $userType === '') {
|
||||
if ($userType === 'primary') {
|
||||
$firstParentId = $parentId;
|
||||
} elseif ($userType === 'secondary') {
|
||||
$parentData = $this->db->table('parents')
|
||||
|
||||
@@ -81,10 +81,10 @@ class ScorePredictor extends Controller
|
||||
s.school_id,
|
||||
s.firstname,
|
||||
s.lastname,
|
||||
MAX(fall.semester_score) as fall_score,
|
||||
MAX(spring.semester_score) as spring_score');
|
||||
// Reduce duplication from restored students while keeping a stable class section.
|
||||
$builder->select('MAX(sc.class_section_id) as class_section_id');
|
||||
fall.semester_score as fall_score,
|
||||
spring.semester_score as spring_score');
|
||||
// Also select class section for per-class trophy decision
|
||||
$builder->select('sc.class_section_id as class_section_id');
|
||||
$yearEsc = $this->db->escape($selectedYear);
|
||||
$builder->join('student_class sc', 'sc.student_id = s.id AND sc.school_year = ' . $yearEsc, 'left');
|
||||
$builder->join('classSection cs', 'cs.class_section_id = sc.class_section_id', 'left');
|
||||
|
||||
@@ -99,7 +99,6 @@ class SubjectCurriculumController extends BaseController
|
||||
->orderBy('classes.class_name', 'ASC')
|
||||
->orderBy('subject', 'ASC')
|
||||
->orderBy('unit_number', 'ASC')
|
||||
->orderBy("CAST(SUBSTRING_INDEX(subject_curriculum_items.chapter_name, '.', 1) AS UNSIGNED)", 'ASC', false)
|
||||
->orderBy('chapter_name', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
@@ -297,16 +297,12 @@ class TeacherController extends BaseController
|
||||
$schoolYear = $forYear ?: ((string)($this->schoolYear ?? 'Not Set'));
|
||||
|
||||
$teachers = $this->teacherModel->getTeachersAndTAs();
|
||||
// Prefer class sections for the selected year if the column exists, otherwise fallback to all.
|
||||
if ($this->db->fieldExists('school_year', 'classSection')) {
|
||||
$classSections = $classSectionModel
|
||||
->where('school_year', $schoolYear)
|
||||
->orderBy('class_section_name', 'ASC')
|
||||
->findAll();
|
||||
if (empty($classSections)) {
|
||||
$classSections = $classSectionModel->orderBy('class_section_name', 'ASC')->findAll();
|
||||
}
|
||||
} else {
|
||||
// Prefer class sections for the selected year, fallback to all if none
|
||||
$classSections = $classSectionModel
|
||||
->where('school_year', $schoolYear)
|
||||
->orderBy('class_section_name', 'ASC')
|
||||
->findAll();
|
||||
if (empty($classSections)) {
|
||||
$classSections = $classSectionModel->orderBy('class_section_name', 'ASC')->findAll();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,504 +0,0 @@
|
||||
<?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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
<?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', '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']['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') ?? '',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,6 @@ require_once APPPATH . 'Helpers/pbkdf2_helper.php';
|
||||
|
||||
class UserController extends BaseController
|
||||
{
|
||||
private const ACTIVATION_TTL_HOURS = 48;
|
||||
protected $userModel;
|
||||
protected $roleModel;
|
||||
protected $userRoleModel;
|
||||
@@ -50,37 +49,6 @@ class UserController extends BaseController
|
||||
$this->resetRequestModel = new PasswordResetRequestModel();
|
||||
}
|
||||
|
||||
private function denyAccess(string $message)
|
||||
{
|
||||
if ($this->request->isAJAX() || $this->request->getHeaderLine('Accept') === 'application/json') {
|
||||
return service('response')
|
||||
->setStatusCode(403)
|
||||
->setJSON(['status' => 'error', 'message' => $message]);
|
||||
}
|
||||
|
||||
session()->setFlashdata('error', $message);
|
||||
return redirect()->to('/access_denied');
|
||||
}
|
||||
|
||||
private function requirePermission(string $permission)
|
||||
{
|
||||
if (!session()->get('is_logged_in')) {
|
||||
return redirect()->to('/login');
|
||||
}
|
||||
|
||||
$userId = (int) session()->get('user_id');
|
||||
if ($userId <= 0 || !has_permission($userId, $permission)) {
|
||||
return $this->denyAccess("You don't have permission to use this feature.");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function hashToken(string $token): string
|
||||
{
|
||||
return hash('sha256', $token);
|
||||
}
|
||||
|
||||
// Method to show the home page
|
||||
public function home()
|
||||
{
|
||||
@@ -107,10 +75,6 @@ class UserController extends BaseController
|
||||
|
||||
public function userList()
|
||||
{
|
||||
if ($resp = $this->requirePermission('read_user')) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
helper('url');
|
||||
|
||||
return view('user/user_list', [
|
||||
@@ -121,10 +85,6 @@ class UserController extends BaseController
|
||||
// Method to show the list of users
|
||||
public function index()
|
||||
{
|
||||
if ($resp = $this->requirePermission('read_user')) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
// Fetch users along with their assigned roles
|
||||
$builder = $this->db->table('users');
|
||||
$builder->select('users.id, users.firstname, users.lastname, users.email, user_roles.role_id, roles.name as role, users.status, users.updated_at');
|
||||
@@ -162,10 +122,6 @@ class UserController extends BaseController
|
||||
|
||||
public function userListData()
|
||||
{
|
||||
if ($resp = $this->requirePermission('read_user')) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
return $this->response->setJSON([
|
||||
'users' => $this->buildUsersWithRoles(),
|
||||
]);
|
||||
@@ -297,10 +253,6 @@ class UserController extends BaseController
|
||||
// Method to store a new user
|
||||
public function store()
|
||||
{
|
||||
if ($resp = $this->requirePermission('edit_user')) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
// Validate input data
|
||||
$validation = \Config\Services::validation();
|
||||
$validation->setRules([
|
||||
@@ -363,10 +315,6 @@ class UserController extends BaseController
|
||||
// Method to show the form for editing an existing user
|
||||
public function edit($id)
|
||||
{
|
||||
if ($resp = $this->requirePermission('edit_user')) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
$data['user'] = $this->userModel->find($id);
|
||||
$data['roles'] = $this->roleModel->findAll();
|
||||
$userRoles = $this->userRoleModel->where('user_id', $id)->findAll();
|
||||
@@ -379,10 +327,6 @@ class UserController extends BaseController
|
||||
// Method to delete an existing user
|
||||
public function delete($id)
|
||||
{
|
||||
if ($resp = $this->requirePermission('edit_user')) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
$this->userModel->delete($id);
|
||||
|
||||
// Delete the user's roles from the user_roles table
|
||||
@@ -425,21 +369,27 @@ class UserController extends BaseController
|
||||
$email = strtolower($this->request->getPost('email'));
|
||||
$user = $this->userModel->where('email', $email)->first();
|
||||
|
||||
// --- Handle unknown or unverified email ---
|
||||
if (!$user || (int) $user['is_verified'] === 0) {
|
||||
session()->setFlashdata('success', 'If this email is registered, you will receive a reset link.');
|
||||
log_message('info', "Password reset requested for {$email} (user missing or unverified).");
|
||||
// --- Handle unknown email ---
|
||||
if (!$user) {
|
||||
session()->setFlashdata('error', 'If this email is registered, you will receive a reset link.');
|
||||
log_message('info', "Password reset requested for non-existing user {$email}");
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
// --- Handle unverified accounts ---
|
||||
if ((int) $user['is_verified'] === 0) {
|
||||
session()->setFlashdata('error', 'Please check your email and complete the account activation process before resetting your password.');
|
||||
log_message('info', "Password reset blocked for unverified user {$email}");
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
// --- Verified user: continue with reset ---
|
||||
$token = bin2hex(random_bytes(48));
|
||||
$tokenHash = $this->hashToken($token);
|
||||
$expires_at = Time::now()->addHours(1);
|
||||
|
||||
$this->passwordResetModel->insert([
|
||||
'email' => $email,
|
||||
'token' => $tokenHash,
|
||||
'token' => $token,
|
||||
'created_at' => Time::now(),
|
||||
'expires_at' => $expires_at,
|
||||
]);
|
||||
@@ -497,12 +447,7 @@ class UserController extends BaseController
|
||||
}
|
||||
|
||||
// You may want to validate the token here
|
||||
$tokenHash = $this->hashToken($token);
|
||||
$resetEntry = $this->passwordResetModel
|
||||
->groupStart()
|
||||
->where('token', $tokenHash)
|
||||
->orWhere('token', $token)
|
||||
->groupEnd()
|
||||
$resetEntry = $this->passwordResetModel->where('token', $token)
|
||||
->where('expires_at >=', Time::now())
|
||||
->first();
|
||||
|
||||
@@ -517,10 +462,6 @@ class UserController extends BaseController
|
||||
//This function processes the new password submission, validating the token, updating the user's password, and cleaning up the reset entry.
|
||||
public function processResetPassword()
|
||||
{
|
||||
if (strtolower($this->request->getMethod()) !== 'post') {
|
||||
return redirect()->to('/')->with('error', 'Invalid request.');
|
||||
}
|
||||
|
||||
$token = $this->request->getPost('token');
|
||||
$newPassword = $this->request->getPost('password');
|
||||
$passConfirm = $this->request->getPost('pass_confirm');
|
||||
@@ -549,12 +490,7 @@ class UserController extends BaseController
|
||||
}
|
||||
|
||||
// Find the password reset entry
|
||||
$tokenHash = $this->hashToken($token);
|
||||
$resetEntry = $this->passwordResetModel
|
||||
->groupStart()
|
||||
->where('token', $tokenHash)
|
||||
->orWhere('token', $token)
|
||||
->groupEnd()
|
||||
$resetEntry = $this->passwordResetModel->where('token', $token)
|
||||
->where('expires_at >=', Time::now())
|
||||
->first();
|
||||
|
||||
@@ -583,12 +519,7 @@ class UserController extends BaseController
|
||||
]);
|
||||
|
||||
// Delete the used token from the password reset table
|
||||
$this->passwordResetModel
|
||||
->groupStart()
|
||||
->where('token', $tokenHash)
|
||||
->orWhere('token', $token)
|
||||
->groupEnd()
|
||||
->delete();
|
||||
$this->passwordResetModel->where('token', $token)->delete();
|
||||
|
||||
// Retrieve the user's IP address from the request
|
||||
$ipAddress = $this->request->getIPAddress();
|
||||
@@ -615,16 +546,10 @@ class UserController extends BaseController
|
||||
|
||||
public function confirm($token)
|
||||
{
|
||||
log_message('info', 'Processing email confirmation.');
|
||||
log_message('info', 'Processing email confirmation with token: ' . $token);
|
||||
|
||||
$tokenHash = $this->hashToken($token);
|
||||
$user = $this->userModel
|
||||
->groupStart()
|
||||
->where('token', $tokenHash)
|
||||
->orWhere('token', $token)
|
||||
->groupEnd()
|
||||
->where('created_at >=', Time::now()->subHours(self::ACTIVATION_TTL_HOURS)->toDateTimeString())
|
||||
->first();
|
||||
|
||||
$user = $this->userModel->where('token', $token)->first();
|
||||
|
||||
if (!$user || $user['is_verified'] == 1) {
|
||||
return redirect()->to('/invalid_token');
|
||||
@@ -645,14 +570,7 @@ class UserController extends BaseController
|
||||
{
|
||||
//echo "Reached setPassword with token: " . esc($token);
|
||||
//echo "Token received: " . $token;
|
||||
$tokenHash = $this->hashToken($token);
|
||||
$user = $this->userModel
|
||||
->groupStart()
|
||||
->where('token', $tokenHash)
|
||||
->orWhere('token', $token)
|
||||
->groupEnd()
|
||||
->where('created_at >=', Time::now()->subHours(self::ACTIVATION_TTL_HOURS)->toDateTimeString())
|
||||
->first();
|
||||
$user = $this->userModel->where('token', $token)->first();
|
||||
|
||||
if (!$user || $user['is_verified'] == 1) {
|
||||
return redirect()->to('/invalid_token');
|
||||
@@ -666,10 +584,6 @@ class UserController extends BaseController
|
||||
|
||||
public function savePassword()
|
||||
{
|
||||
if (strtolower($this->request->getMethod()) !== 'post') {
|
||||
return redirect()->to('/')->with('error', 'Invalid request.');
|
||||
}
|
||||
|
||||
$validation = \Config\Services::validation();
|
||||
$validation->setRules([
|
||||
'password' => [
|
||||
@@ -701,17 +615,9 @@ class UserController extends BaseController
|
||||
$token = $this->request->getPost('token');
|
||||
$password = $this->request->getPost('password');
|
||||
|
||||
$tokenHash = $this->hashToken($token);
|
||||
$user = $this->userModel
|
||||
->where('id', $userId)
|
||||
->groupStart()
|
||||
->where('token', $tokenHash)
|
||||
->orWhere('token', $token)
|
||||
->groupEnd()
|
||||
->where('created_at >=', Time::now()->subHours(self::ACTIVATION_TTL_HOURS)->toDateTimeString())
|
||||
->first();
|
||||
$user = $this->userModel->where('id', $userId)->where('token', $token)->first();
|
||||
|
||||
log_message('debug', "Attempting to set password for user $userId");
|
||||
log_message('debug', "Attempting to set password for user $userId with token $token");
|
||||
|
||||
if (!$user || $user['is_verified'] == 1) {
|
||||
return redirect()->to('/invalid_token');
|
||||
@@ -764,39 +670,20 @@ class UserController extends BaseController
|
||||
$roleKey = (string) $this->request->getPost('role');
|
||||
log_message('info', 'Role selected: ' . $roleKey);
|
||||
|
||||
$roleModel = new RoleModel();
|
||||
$route = $roleModel->getRouteByNameOrSlug($roleKey);
|
||||
|
||||
if ($route === null) {
|
||||
log_message('error', 'Invalid or inactive role selected: ' . $roleKey);
|
||||
return redirect()->back()->with('error', 'Invalid role selected.');
|
||||
}
|
||||
|
||||
$userId = (int) session()->get('user_id');
|
||||
log_message('info', 'User ID: ' . $userId);
|
||||
|
||||
if ($userId <= 0) {
|
||||
return $this->denyAccess("You don't have permission to use this feature.");
|
||||
}
|
||||
|
||||
$roleRow = $this->db->table('user_roles ur')
|
||||
->join('roles r', 'r.id = ur.role_id', 'inner')
|
||||
->select('r.name, r.slug, r.dashboard_route')
|
||||
->where('ur.user_id', $userId)
|
||||
->where('r.is_active', 1)
|
||||
->groupStart()
|
||||
->where('LOWER(r.name)', strtolower($roleKey))
|
||||
->orWhere('LOWER(r.slug)', strtolower($roleKey))
|
||||
->groupEnd()
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if (empty($roleRow)) {
|
||||
log_message('error', 'Invalid or unassigned role selected: ' . $roleKey);
|
||||
return redirect()->back()->with('error', 'Invalid role selected.');
|
||||
}
|
||||
|
||||
$route = $roleRow['dashboard_route'] ?? null;
|
||||
if ($route === null) {
|
||||
log_message('error', 'No dashboard route configured for role: ' . $roleKey);
|
||||
return redirect()->back()->with('error', 'Invalid role selected.');
|
||||
}
|
||||
|
||||
// Persist the *exact* role name or slug—choose your convention.
|
||||
// Store the canonical name to avoid arbitrary role strings.
|
||||
$this->userModel->update($userId, ['role' => $roleRow['name']]);
|
||||
// If you want to store the canonical name, fetch the row and use $row['name'].
|
||||
$this->userModel->update($userId, ['role' => $roleKey]);
|
||||
log_message('info', 'Role updated in database.');
|
||||
|
||||
log_message('info', 'Redirecting to role dashboard: ' . $route);
|
||||
@@ -815,10 +702,6 @@ class UserController extends BaseController
|
||||
|
||||
public function delete_role($roleId)
|
||||
{
|
||||
if ($resp = $this->requirePermission('edit_user')) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
// Fetch the role to be deleted
|
||||
$role = $this->roleModel->find($roleId);
|
||||
if (!$role) {
|
||||
@@ -848,10 +731,6 @@ class UserController extends BaseController
|
||||
|
||||
public function loginActivity()
|
||||
{
|
||||
if ($resp = $this->requirePermission('view_login_activity')) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
helper('url');
|
||||
|
||||
$perPage = (int) ($this->request->getGet('per_page') ?? 25);
|
||||
@@ -864,10 +743,6 @@ class UserController extends BaseController
|
||||
|
||||
public function loginActivityData()
|
||||
{
|
||||
if ($resp = $this->requirePermission('view_login_activity')) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
$perPage = (int) ($this->request->getGet('per_page') ?? 25);
|
||||
$page = (int) ($this->request->getGet('page') ?? 1);
|
||||
|
||||
@@ -877,10 +752,6 @@ class UserController extends BaseController
|
||||
// Method to update an existing user
|
||||
public function updateUser()
|
||||
{
|
||||
if ($resp = $this->requirePermission('edit_user')) {
|
||||
return $resp;
|
||||
}
|
||||
|
||||
if (strtolower($this->request->getMethod()) !== 'post') {
|
||||
return redirect()->to(site_url('user/user_list'))->with('error', 'Invalid request.');
|
||||
}
|
||||
@@ -929,6 +800,9 @@ class UserController extends BaseController
|
||||
'status' => trim((string)$this->request->getPost('status')),
|
||||
'is_suspended' => $toBool('is_suspended'),
|
||||
'is_verified' => $toBool('is_verified'),
|
||||
'token' => trim((string)$this->request->getPost('token')),
|
||||
'updated_at' => $toDT('updated_at'),
|
||||
'created_at' => $toDT('created_at'),
|
||||
];
|
||||
|
||||
// Validation
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class AddBelowSixtyNavItem extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
$db = \Config\Database::connect();
|
||||
|
||||
if (!$db->tableExists('nav_items')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$parentColumn = null;
|
||||
if ($db->fieldExists('menu_parent_id', 'nav_items')) {
|
||||
$parentColumn = 'menu_parent_id';
|
||||
} elseif ($db->fieldExists('parent_id', 'nav_items')) {
|
||||
$parentColumn = 'parent_id';
|
||||
}
|
||||
|
||||
if ($parentColumn === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$navBuilder = $db->table('nav_items');
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
$communication = $navBuilder
|
||||
->select('id')
|
||||
->where('label', 'Communication')
|
||||
->where($parentColumn, null)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if ($communication) {
|
||||
$communicationId = (int) $communication['id'];
|
||||
} else {
|
||||
$navBuilder->insert([
|
||||
$parentColumn => null,
|
||||
'label' => 'Communication',
|
||||
'url' => null,
|
||||
'sort_order' => 80,
|
||||
'is_enabled' => 1,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
$communicationId = (int) $db->insertID();
|
||||
}
|
||||
|
||||
$belowSixtyUrl = 'grading/below-60';
|
||||
$existing = $navBuilder->select('id')
|
||||
->where('url', $belowSixtyUrl)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if (!$existing) {
|
||||
$navBuilder->insert([
|
||||
$parentColumn => $communicationId ?: null,
|
||||
'label' => 'Below 60 Summary',
|
||||
'url' => $belowSixtyUrl,
|
||||
'sort_order' => 4,
|
||||
'is_enabled' => 1,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
$belowSixtyId = (int) $db->insertID();
|
||||
} else {
|
||||
$belowSixtyId = (int) $existing['id'];
|
||||
}
|
||||
|
||||
if (!$db->tableExists('role_nav_items') || !$db->tableExists('roles')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($belowSixtyId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$roleRows = $db->table('roles')
|
||||
->select('id, name')
|
||||
->whereIn('name', ['administrator', 'principal', 'vice_principal', 'admin'])
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
$roleMap = $db->table('role_nav_items');
|
||||
foreach ($roleRows as $role) {
|
||||
$roleId = (int) ($role['id'] ?? 0);
|
||||
if ($roleId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$exists = $roleMap
|
||||
->where('role_id', $roleId)
|
||||
->where('nav_item_id', $belowSixtyId)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if ($exists) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$roleMap->insert([
|
||||
'role_id' => $roleId,
|
||||
'nav_item_id' => $belowSixtyId,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
$db = \Config\Database::connect();
|
||||
|
||||
if (!$db->tableExists('nav_items')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$belowSixtyUrl = 'grading/below-60';
|
||||
$row = $db->table('nav_items')
|
||||
->select('id')
|
||||
->where('url', $belowSixtyUrl)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
if ($row && $db->tableExists('role_nav_items')) {
|
||||
$db->table('role_nav_items')
|
||||
->where('nav_item_id', (int) $row['id'])
|
||||
->delete();
|
||||
}
|
||||
|
||||
$db->table('nav_items')
|
||||
->where('url', $belowSixtyUrl)
|
||||
->delete();
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Database\Migrations;
|
||||
|
||||
use CodeIgniter\Database\Migration;
|
||||
|
||||
class AddReviewRevisionToExamDrafts extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
if (! $this->db->fieldExists('review_revision', 'exam_drafts')) {
|
||||
$this->forge->addColumn('exam_drafts', [
|
||||
'review_revision' => [
|
||||
'type' => 'INT',
|
||||
'constraint' => 11,
|
||||
'null' => false,
|
||||
'default' => 0,
|
||||
'after' => 'version',
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
if ($this->db->fieldExists('review_revision', 'exam_drafts')) {
|
||||
$this->forge->dropColumn('exam_drafts', 'review_revision');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
<?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');
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
<?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');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
<?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');
|
||||
}
|
||||
}
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
<?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');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
<?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');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -1,292 +0,0 @@
|
||||
<?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',
|
||||
'new_tuition_full_amount' => '370.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;
|
||||
}
|
||||
}
|
||||
@@ -86,9 +86,9 @@ class NavSeeder extends Seeder
|
||||
['parent'=>'Financial','label'=>'Discount Management','url'=>'discounts/list','sort_order'=>1],
|
||||
['parent'=>'Financial','label'=>'Expenses Management','url'=>'expenses/index','sort_order'=>2],
|
||||
['parent'=>'Financial','label'=>'Financial Report','url'=>'payment/financial_report','sort_order'=>3],
|
||||
['parent'=>'Financial','label'=>'Tuition Forecast','url'=>'administrator/tuition-forecast','sort_order'=>4],
|
||||
['parent'=>'Financial','label'=>'Invoices Management','url'=>'invoice_payment/invoice_management','sort_order'=>5],
|
||||
['parent'=>'Financial','label'=>'Manual Payment','url'=>'payment/manual_pay','sort_order'=>6],
|
||||
['parent'=>'Financial','label'=>'Invoices Management','url'=>'invoice_payment/invoice_management','sort_order'=>4],
|
||||
['parent'=>'Financial','label'=>'Manual Payment','url'=>'payment/manual_pay','sort_order'=>5],
|
||||
['parent'=>'Financial','label'=>'PaypalTransactions','url'=>'administrator/paypal_transactions','sort_order'=>6],
|
||||
['parent'=>'Financial','label'=>'Refund Management','url'=>'refunds/list','sort_order'=>7],
|
||||
['parent'=>'Financial','label'=>'Reimbursement Management','url'=>'reimbursements/index','sort_order'=>8],
|
||||
|
||||
|
||||
@@ -11,8 +11,6 @@ class ApiAuthFilter implements FilterInterface
|
||||
{
|
||||
public function before(RequestInterface $request, $arguments = null)
|
||||
{
|
||||
helper('security');
|
||||
|
||||
$authorization = $request->getHeaderLine('Authorization');
|
||||
if (!$authorization || stripos($authorization, 'Bearer ') !== 0) {
|
||||
return $this->unauthorized('Missing or invalid Authorization header');
|
||||
@@ -23,12 +21,7 @@ class ApiAuthFilter implements FilterInterface
|
||||
return $this->unauthorized('Bearer token is required');
|
||||
}
|
||||
|
||||
try {
|
||||
$secret = require_env('JWT_SECRET');
|
||||
} catch (\RuntimeException $e) {
|
||||
return $this->unauthorized('JWT configuration is missing');
|
||||
}
|
||||
|
||||
$secret = env('JWT_SECRET', 'change-me-in-env');
|
||||
$payload = jwt_decode($token, $secret);
|
||||
|
||||
if (!$payload || empty($payload['sub'])) {
|
||||
|
||||
@@ -13,15 +13,13 @@ class ApiDocsAuthFilter implements FilterInterface
|
||||
{
|
||||
public function before(RequestInterface $request, $arguments = null)
|
||||
{
|
||||
helper('security');
|
||||
|
||||
$authHeader = $request->getHeaderLine('Authorization');
|
||||
|
||||
if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
|
||||
$token = trim(substr($authHeader, 7));
|
||||
|
||||
try {
|
||||
$key = require_env('JWT_SECRET');
|
||||
$key = getenv('JWT_SECRET') ?: 'your_default_secret';
|
||||
$decoded = JWT::decode($token, new Key($key, 'HS256'));
|
||||
|
||||
if (!isset($decoded->roles) || empty($decoded->roles->admin)) {
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
+28
-94
@@ -35,19 +35,13 @@ class AuthFilter implements FilterInterface
|
||||
public function before(RequestInterface $request, $arguments = null)
|
||||
{
|
||||
$session = session();
|
||||
$userRoles = $session->get('roles');
|
||||
$userRoles = $session->get('roles'); // not used here, but keep if other code expects it
|
||||
$userId = $session->get('user_id');
|
||||
$loginTime = (int) $session->get('login_time');
|
||||
|
||||
// Must be logged in
|
||||
if (empty($userRoles) || empty($userId)) {
|
||||
$target = ltrim($request->getUri()->getPath(), '/');
|
||||
$query = $request->getUri()->getQuery();
|
||||
if ($query !== '') {
|
||||
$target .= '?' . $query;
|
||||
}
|
||||
|
||||
return redirect()->to('/login?redirect_to=' . rawurlencode('/' . ltrim($target, '/')));
|
||||
return redirect()->to('/login');
|
||||
}
|
||||
|
||||
// Enforce 12-hour session lifetime
|
||||
@@ -66,16 +60,35 @@ class AuthFilter implements FilterInterface
|
||||
return $this->deny($request, "You don't have permission to use this feature.");
|
||||
}
|
||||
|
||||
[$requirements, $crudAction] = $this->parseRequirements($arguments);
|
||||
// Route arguments: ['filter' => 'auth:permission_name|alt_permission,update']
|
||||
// Route arguments patterns supported:
|
||||
// auth -> default 'read'
|
||||
// auth:read -> CRUD only
|
||||
// auth:create -> CRUD only
|
||||
// auth:update -> CRUD only
|
||||
// auth:delete -> CRUD only
|
||||
// auth:permA|permB,read -> permission + CRUD
|
||||
$requiredPermission = null;
|
||||
$crudAction = 'read';
|
||||
|
||||
if (!empty($requirements)) {
|
||||
if ($this->matchesAnyRequirement($requirements, $crudAction, $roleIds, (array) $userRoles)) {
|
||||
return;
|
||||
if (!empty($arguments)) {
|
||||
$arg0 = strtolower((string) $arguments[0]);
|
||||
|
||||
// If only one argument and it's a CRUD keyword, treat as CRUD-only
|
||||
if (count($arguments) === 1 && in_array($arg0, ['create', 'read', 'update', 'delete'], true)) {
|
||||
$crudAction = $arg0;
|
||||
} else {
|
||||
// Otherwise, first arg is permission(s); optional second is CRUD
|
||||
$requiredPermission = $arguments[0]; // e.g., 'edit_student|manage_students'
|
||||
$crudAction = isset($arguments[1]) ? strtolower((string) $arguments[1]) : 'read';
|
||||
if (!in_array($crudAction, ['create', 'read', 'update', 'delete'], true)) {
|
||||
$crudAction = 'read';
|
||||
}
|
||||
}
|
||||
|
||||
return $this->deny($request, "You don't have permission to use this feature.");
|
||||
}
|
||||
|
||||
|
||||
// No explicit route permission: fall back to menu rules
|
||||
if ($this->isAllowedByMenu($request, $roleIds)) {
|
||||
return; // ✅ allowed
|
||||
}
|
||||
@@ -97,86 +110,7 @@ class AuthFilter implements FilterInterface
|
||||
]);
|
||||
}
|
||||
|
||||
$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;
|
||||
return redirect()->to('/login')->with('error', 'Your session has expired. Please log in again.');
|
||||
}
|
||||
|
||||
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -47,28 +47,6 @@ if (!function_exists('attendance_comment_template_for_score')) {
|
||||
}
|
||||
}
|
||||
|
||||
return attendance_comment_template_match($templates, $score);
|
||||
}
|
||||
}
|
||||
|
||||
if (!function_exists('attendance_comment_template_match')) {
|
||||
function attendance_comment_template_match(array $templates, float $score): ?array
|
||||
{
|
||||
if ($templates === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Attendance scores are percentage values; clamp to the expected domain
|
||||
// so minor calculation drift above 100 or below 0 does not skip a template.
|
||||
$score = max(0.0, min(100.0, $score));
|
||||
|
||||
usort($templates, static function (array $a, array $b): int {
|
||||
$aMin = isset($a['min_score']) ? (float) $a['min_score'] : 0.0;
|
||||
$bMin = isset($b['min_score']) ? (float) $b['min_score'] : 0.0;
|
||||
|
||||
return $aMin <=> $bMin;
|
||||
});
|
||||
|
||||
foreach ($templates as $template) {
|
||||
$min = isset($template['min_score']) ? (float) $template['min_score'] : 0.0;
|
||||
$max = isset($template['max_score']) ? (float) $template['max_score'] : 100.0;
|
||||
@@ -77,18 +55,6 @@ if (!function_exists('attendance_comment_template_match')) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__ . '/AuthHelper.php';
|
||||
@@ -1,41 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Interfaces;
|
||||
|
||||
interface TuitionCalculatorInterface
|
||||
{
|
||||
public function calculateFamilyTuition(array $students, array $config): array;
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
<?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';
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -1,342 +0,0 @@
|
||||
<?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_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, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,8 @@ class StaffTimeOffLinkService
|
||||
public function __construct(?string $secret = null, ?int $ttlSeconds = null)
|
||||
{
|
||||
helper('jwt');
|
||||
helper('security');
|
||||
|
||||
$this->secret = $secret ?: require_env('JWT_SECRET');
|
||||
$this->secret = $secret ?: (string)env('JWT_SECRET', 'change-me-in-env');
|
||||
$this->ttl = ($ttlSeconds !== null && $ttlSeconds > 0) ? $ttlSeconds : self::DEFAULT_TTL;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
<?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);
|
||||
$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 = [];
|
||||
|
||||
foreach (array_values($students) as $index => $student) {
|
||||
$position = $index + 1;
|
||||
|
||||
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';
|
||||
}
|
||||
|
||||
$amountCents = max(0, $fullAmountCents - $discountCents);
|
||||
|
||||
$details[] = [
|
||||
'student_id' => (int) ($student['student_id'] ?? 0),
|
||||
'student_name' => (string) ($student['student_name'] ?? ''),
|
||||
'grade_level' => $student['grade_level'] ?? null,
|
||||
'family_position' => $position,
|
||||
'full_amount' => $this->fromCents($fullAmountCents),
|
||||
'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, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
<?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'] ?? 180);
|
||||
|
||||
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, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -1,647 +0,0 @@
|
||||
<?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'];
|
||||
$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',
|
||||
];
|
||||
|
||||
$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, '.', '');
|
||||
|
||||
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),
|
||||
];
|
||||
}
|
||||
|
||||
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'),
|
||||
'new_tuition_full_amount' => $this->normalizedUnitPriceOverride(),
|
||||
'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 function normalizedUnitPriceOverride(): string
|
||||
{
|
||||
return $this->unitPriceOverride
|
||||
?? (string) ($this->configurationModel->getConfig('new_tuition_full_amount') ?? '0.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, '.', '');
|
||||
}
|
||||
}
|
||||
@@ -71,10 +71,7 @@ class BelowSixtyEmailListener
|
||||
'sent_at' => utc_now(),
|
||||
];
|
||||
|
||||
$html = trim((string)($payload['html'] ?? ''));
|
||||
if ($html === '') {
|
||||
$html = view('emails/below_sixty_performance', $emailData, ['saveData' => true]);
|
||||
}
|
||||
$html = view('emails/below_sixty_performance', $emailData, ['saveData' => true]);
|
||||
|
||||
$okAny = false;
|
||||
foreach ($emails as $to) {
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ class AdditionalChargeModel extends Model
|
||||
'description' => 'permit_empty|string',
|
||||
'amount' => 'required|decimal',
|
||||
'due_date' => 'permit_empty|valid_date',
|
||||
'status' => 'required|in_list[pending,applied,voided]',
|
||||
'status' => 'required|in_list[pending,applied]',
|
||||
'created_by' => 'permit_empty|integer',
|
||||
];
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
<?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';
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
<?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();
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,6 @@ namespace App\Models;
|
||||
|
||||
use CodeIgniter\Model;
|
||||
|
||||
/**
|
||||
* Weekly class progress reports (one row per subject per week).
|
||||
*
|
||||
* unit_title stores a compact summary of unit/chapter rows: segments joined with " ; ".
|
||||
* Teacher-entered custom Islamic or Quran topics use the prefix "Custom / {text}"
|
||||
* (see {@see \App\Controllers\ClassProgressController::CUSTOM_UNIT_ROW_LABEL} and
|
||||
* {@see \App\Controllers\ClassProgressController::splitUnitTitleForDisplay()}).
|
||||
* DB column is VARCHAR(120); controller truncates to match.
|
||||
*/
|
||||
class ClassProgressReportModel extends Model
|
||||
{
|
||||
protected $table = 'class_progress_reports';
|
||||
@@ -36,42 +27,7 @@ class ClassProgressReportModel extends Model
|
||||
'flags_json',
|
||||
'attachment_path',
|
||||
];
|
||||
|
||||
protected $useTimestamps = true;
|
||||
protected $createdField = 'created_at';
|
||||
protected $updatedField = 'updated_at';
|
||||
|
||||
/**
|
||||
* Validation is performed in {@see \App\Controllers\ClassProgressController} on HTTP input.
|
||||
* Rules below document schema limits and can be enabled if you set {@see $skipValidation} to false.
|
||||
*/
|
||||
protected $skipValidation = true;
|
||||
|
||||
protected $validationRules = [
|
||||
'class_section_id' => 'required|integer',
|
||||
'teacher_id' => 'required|integer',
|
||||
'week_start' => 'required|valid_date[Y-m-d]',
|
||||
'week_end' => 'required|valid_date[Y-m-d]',
|
||||
'subject' => 'required|string|max_length[160]',
|
||||
'unit_title' => 'permit_empty|string|max_length[120]',
|
||||
'covered' => 'permit_empty|string',
|
||||
'homework' => 'permit_empty|string',
|
||||
'assessment' => 'permit_empty|string',
|
||||
'status' => 'permit_empty|in_list[on_track,slightly_behind,behind]',
|
||||
'status_notes' => 'permit_empty|string|max_length[200]',
|
||||
'class_notes' => 'permit_empty|string',
|
||||
'next_week_plan' => 'permit_empty|string',
|
||||
'support_needed' => 'permit_empty|string',
|
||||
'flags_json' => 'permit_empty|string',
|
||||
'attachment_path' => 'permit_empty|string|max_length[255]',
|
||||
];
|
||||
|
||||
protected $validationMessages = [
|
||||
'unit_title' => [
|
||||
'max_length' => 'Unit and chapter summary cannot exceed 120 characters.',
|
||||
],
|
||||
'subject' => [
|
||||
'max_length' => 'Subject cannot exceed 160 characters.',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -22,13 +22,11 @@ class ConfigurationModel extends Model
|
||||
*/
|
||||
public function getConfigValueByKey(string $key)
|
||||
{
|
||||
// Use a fresh builder to avoid stale state from shared model builder.
|
||||
$builder = $this->db->table($this->table);
|
||||
$result = $builder->where('config_key', $key)
|
||||
// Deterministic read in case historical duplicates exist
|
||||
$result = $this->where('config_key', $key)
|
||||
->orderBy('id', 'DESC')
|
||||
->get(1)
|
||||
->getRowArray();
|
||||
return $result['config_value'] ?? null;
|
||||
->first();
|
||||
return $result ? $result['config_value'] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,20 +15,8 @@ class EventChargesModel extends Model
|
||||
'student_id',
|
||||
'participation',
|
||||
'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',
|
||||
'school_year',
|
||||
'created_by',
|
||||
'updated_by',
|
||||
'created_at',
|
||||
'updated_at'
|
||||
@@ -42,7 +30,7 @@ class EventChargesModel extends Model
|
||||
|
||||
public function getChargesWithEventInfo($parentId = null, $schoolYear = null, $semester = null)
|
||||
{
|
||||
$builder = $this->select('event_charges.*, events.event_name, events.amount AS event_amount, events.description AS event_description')
|
||||
$builder = $this->select('event_charges.*, events.event_name, events.amount')
|
||||
->join('events', 'events.id = event_charges.event_id', 'left');
|
||||
|
||||
if ($parentId) {
|
||||
|
||||
@@ -8,51 +8,19 @@ class ExamDraftModel extends Model
|
||||
{
|
||||
protected $table = 'exam_drafts';
|
||||
protected $primaryKey = 'id';
|
||||
protected $returnType = 'array';
|
||||
protected $useTimestamps = true;
|
||||
protected $createdField = 'created_at';
|
||||
protected $updatedField = 'updated_at';
|
||||
protected bool $updateOnlyChanged = false;
|
||||
|
||||
/** @var list<string> Stored in `status` column */
|
||||
public const STATUSES = [
|
||||
'submitted',
|
||||
'accepted',
|
||||
'review needed',
|
||||
'rejected',
|
||||
'canceled',
|
||||
'under review',
|
||||
'legacy',
|
||||
];
|
||||
|
||||
/** @var list<string> Stored in `acceptance_type` when status is finalized */
|
||||
public const ACCEPTANCE_TYPES = [
|
||||
'as_is',
|
||||
'minor_edits',
|
||||
];
|
||||
|
||||
protected $allowedFields = [
|
||||
'teacher_id',
|
||||
'author_id',
|
||||
'class_section_id',
|
||||
'semester',
|
||||
'school_year',
|
||||
'exam_type',
|
||||
'draft_title',
|
||||
'author_comment',
|
||||
'description',
|
||||
'teacher_file',
|
||||
'teacher_filename',
|
||||
'author_file',
|
||||
'author_filename',
|
||||
'status',
|
||||
'acceptance_type',
|
||||
'review_revision',
|
||||
'reviewer_id',
|
||||
'admin_id',
|
||||
'is_legacy',
|
||||
'reviewer_comment',
|
||||
'reviewer_comments',
|
||||
'admin_comments',
|
||||
'reviewed_at',
|
||||
'final_file',
|
||||
@@ -61,40 +29,9 @@ class ExamDraftModel extends Model
|
||||
'version',
|
||||
'previous_draft_id',
|
||||
];
|
||||
|
||||
/**
|
||||
* Applied on insert/update when validation runs (e.g. $model->insert($data, true)).
|
||||
* Uses if_exist so partial updates still validate only keys present in $data.
|
||||
*/
|
||||
protected $validationRules = [
|
||||
'status' => 'if_exist|in_list[submitted,accepted,review needed,rejected,canceled,under review,legacy]',
|
||||
'acceptance_type' => 'if_exist|permit_empty|in_list[as_is,minor_edits]',
|
||||
'author_id' => 'if_exist|is_natural_no_zero',
|
||||
'class_section_id' => 'if_exist|is_natural_no_zero',
|
||||
'version' => 'if_exist|is_natural_no_zero',
|
||||
];
|
||||
|
||||
protected $validationMessages = [
|
||||
'status' => [
|
||||
'in_list' => 'Invalid exam draft status.',
|
||||
],
|
||||
'acceptance_type' => [
|
||||
'in_list' => 'Acceptance must be as_is or minor_edits.',
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected array $casts = [
|
||||
'teacher_id' => 'int',
|
||||
'author_id' => 'int',
|
||||
'class_section_id' => 'int',
|
||||
'reviewer_id' => '?int',
|
||||
'admin_id' => '?int',
|
||||
'review_revision' => 'int',
|
||||
'version' => 'int',
|
||||
'previous_draft_id' => '?int',
|
||||
'is_legacy' => 'boolean',
|
||||
];
|
||||
protected $returnType = 'array';
|
||||
protected $useTimestamps = true;
|
||||
protected $createdField = 'created_at';
|
||||
protected $updatedField = 'updated_at';
|
||||
protected bool $updateOnlyChanged = false; // force updates even if CI thinks nothing changed
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?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
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ class PaymentModel extends Model
|
||||
'paid_amount',
|
||||
'balance',
|
||||
'number_of_installments',
|
||||
'installment_seq',
|
||||
'transaction_id',
|
||||
'check_file',
|
||||
'check_number',
|
||||
@@ -115,7 +114,6 @@ class PaymentModel extends Model
|
||||
->selectSum('paid_amount', 'total_paid')
|
||||
->where('parent_id', $parentId)
|
||||
->where('school_year', $schoolYear)
|
||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user