Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6e8da3cc2c | |||
| 384ae8b719 | |||
| 654453222f | |||
| a18e8b92a6 | |||
| 6444b61416 | |||
| 090cb88573 | |||
| 95bcefc3a9 | |||
| f24f4311e8 | |||
| 89913d7473 | |||
| 079c869477 | |||
| 9ee75fe4cc | |||
| fcfa56b3f5 |
@@ -0,0 +1,171 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Commands;
|
||||||
|
|
||||||
|
use App\Libraries\InvoiceLedgerService;
|
||||||
|
use App\Models\InvoiceModel;
|
||||||
|
use CodeIgniter\CLI\BaseCommand;
|
||||||
|
use CodeIgniter\CLI\CLI;
|
||||||
|
|
||||||
|
class RecalculateInvoices extends BaseCommand
|
||||||
|
{
|
||||||
|
protected $group = 'Financial';
|
||||||
|
protected $name = 'financial:recalculate-invoices';
|
||||||
|
protected $description = 'Audits invoice totals against the centralized ledger and optionally writes the corrected values.';
|
||||||
|
protected $usage = 'financial:recalculate-invoices [--commit] [--invoice-id=123] [--parent-id=456] [--school-year=2025-2026] [--semester=Fall]';
|
||||||
|
protected $options = [
|
||||||
|
'--commit' => 'Persist recalculated totals. Without this flag the command runs in dry-run mode.',
|
||||||
|
'--invoice-id' => 'Only process a single invoice ID.',
|
||||||
|
'--parent-id' => 'Only process invoices for one parent.',
|
||||||
|
'--school-year' => 'Only process invoices for the specified school year.',
|
||||||
|
'--semester' => 'Only process invoices for the specified semester.',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function run(array $params)
|
||||||
|
{
|
||||||
|
$options = $this->parseOptions($params);
|
||||||
|
$invoiceModel = new InvoiceModel();
|
||||||
|
$ledgerService = new InvoiceLedgerService();
|
||||||
|
$invoiceIds = $this->loadInvoiceIds($invoiceModel, $options);
|
||||||
|
|
||||||
|
if ($invoiceIds === []) {
|
||||||
|
CLI::write('No invoices matched the provided filters.', 'yellow');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$commit = !empty($options['commit']);
|
||||||
|
CLI::write(($commit ? 'Applying' : 'Dry-run auditing') . ' ' . count($invoiceIds) . ' invoice(s)...', 'yellow');
|
||||||
|
|
||||||
|
$changed = 0;
|
||||||
|
$unchanged = 0;
|
||||||
|
$errors = 0;
|
||||||
|
|
||||||
|
foreach ($invoiceIds as $invoiceId) {
|
||||||
|
$invoice = $invoiceModel->find($invoiceId);
|
||||||
|
if (!$invoice) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$calculation = $ledgerService->calculateInvoice($invoiceId);
|
||||||
|
$diffs = $this->diffInvoice($invoice, $calculation);
|
||||||
|
|
||||||
|
if ($diffs === []) {
|
||||||
|
$unchanged++;
|
||||||
|
CLI::write('Invoice #' . $invoiceId . ' unchanged.', 'green');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$changed++;
|
||||||
|
CLI::write('Invoice #' . $invoiceId . ' requires recalculation:', 'light_yellow');
|
||||||
|
foreach ($diffs as $label => $values) {
|
||||||
|
CLI::write(sprintf(
|
||||||
|
' %s: %s -> %s',
|
||||||
|
$label,
|
||||||
|
(string) $values['from'],
|
||||||
|
(string) $values['to']
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($commit) {
|
||||||
|
$ledgerService->recalculateInvoice($invoiceId);
|
||||||
|
CLI::write(' saved', 'blue');
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$errors++;
|
||||||
|
CLI::error('Invoice #' . $invoiceId . ' failed: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CLI::newLine();
|
||||||
|
CLI::write('Processed: ' . count($invoiceIds), 'white');
|
||||||
|
CLI::write('Changed: ' . $changed, $changed > 0 ? 'yellow' : 'white');
|
||||||
|
CLI::write('Unchanged: ' . $unchanged, 'green');
|
||||||
|
CLI::write('Errors: ' . $errors, $errors > 0 ? 'red' : 'white');
|
||||||
|
|
||||||
|
if (!$commit) {
|
||||||
|
CLI::write('Dry-run complete. Re-run with --commit to persist corrections.', 'light_blue');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function parseOptions(array $params): array
|
||||||
|
{
|
||||||
|
$options = [
|
||||||
|
'commit' => false,
|
||||||
|
'invoice-id' => null,
|
||||||
|
'parent-id' => null,
|
||||||
|
'school-year' => null,
|
||||||
|
'semester' => null,
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($params as $param) {
|
||||||
|
$value = trim((string) $param);
|
||||||
|
if ($value === '--commit') {
|
||||||
|
$options['commit'] = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!str_starts_with($value, '--') || !str_contains($value, '=')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
[$key, $raw] = explode('=', substr($value, 2), 2);
|
||||||
|
if (array_key_exists($key, $options)) {
|
||||||
|
$options[$key] = $raw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $options;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function loadInvoiceIds(InvoiceModel $invoiceModel, array $options): array
|
||||||
|
{
|
||||||
|
$builder = $invoiceModel->select('id')->orderBy('id', 'ASC');
|
||||||
|
|
||||||
|
if (!empty($options['invoice-id'])) {
|
||||||
|
$builder->where('id', (int) $options['invoice-id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($options['parent-id'])) {
|
||||||
|
$builder->where('parent_id', (int) $options['parent-id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($options['school-year'])) {
|
||||||
|
$builder->where('school_year', (string) $options['school-year']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!empty($options['semester'])) {
|
||||||
|
$builder->where('semester', (string) $options['semester']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_map(
|
||||||
|
static fn (array $row): int => (int) ($row['id'] ?? 0),
|
||||||
|
$builder->findAll()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function diffInvoice(array $invoice, array $calculation): array
|
||||||
|
{
|
||||||
|
$fields = [
|
||||||
|
'total_amount' => 'total_amount',
|
||||||
|
'paid_amount' => 'paid_amount',
|
||||||
|
'balance' => 'balance',
|
||||||
|
'status' => 'status',
|
||||||
|
'has_discount' => 'has_discount',
|
||||||
|
];
|
||||||
|
$diffs = [];
|
||||||
|
|
||||||
|
foreach ($fields as $invoiceKey => $calcKey) {
|
||||||
|
$current = (string) ($invoice[$invoiceKey] ?? '');
|
||||||
|
$recalculated = (string) ($calculation[$calcKey] ?? '');
|
||||||
|
if ($current !== $recalculated) {
|
||||||
|
$diffs[$invoiceKey] = [
|
||||||
|
'from' => $current,
|
||||||
|
'to' => $recalculated,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $diffs;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,232 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Commands;
|
|
||||||
|
|
||||||
use CodeIgniter\CLI\BaseCommand;
|
|
||||||
use CodeIgniter\CLI\CLI;
|
|
||||||
use App\Models\PayPalPaymentModel;
|
|
||||||
use App\Models\PaymentModel;
|
|
||||||
use App\Models\UserModel;
|
|
||||||
use App\Models\ConfigurationModel;
|
|
||||||
use App\Models\InvoiceModel;
|
|
||||||
use App\Models\StudentModel;
|
|
||||||
use App\Models\EnrollmentModel;
|
|
||||||
|
|
||||||
class SyncPaypalPayments extends BaseCommand
|
|
||||||
{
|
|
||||||
protected $group = 'Payments';
|
|
||||||
protected $name = 'payments:sync-paypal';
|
|
||||||
protected $description = 'Sync PayPal payments to internal payments table from paypal_payments';
|
|
||||||
protected $configModel;
|
|
||||||
protected $semester;
|
|
||||||
protected $schoolYear;
|
|
||||||
protected $paypalModel;
|
|
||||||
protected $paymentModel;
|
|
||||||
protected $userModel;
|
|
||||||
protected $invoiceModel;
|
|
||||||
protected $studentModel;
|
|
||||||
protected $enrollmentModel;
|
|
||||||
|
|
||||||
public function __construct()
|
|
||||||
{
|
|
||||||
$this->configModel = new ConfigurationModel();
|
|
||||||
$this->paypalModel = new PayPalPaymentModel();
|
|
||||||
$this->paymentModel = new PaymentModel();
|
|
||||||
$this->userModel = new UserModel();
|
|
||||||
$this->invoiceModel = new InvoiceModel();
|
|
||||||
$this->studentModel = new StudentModel();
|
|
||||||
$this->enrollmentModel = new EnrollmentModel();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function run(array $params)
|
|
||||||
{
|
|
||||||
$this->semester = (string) ($this->configModel->getConfig('semester') ?? '');
|
|
||||||
$this->schoolYear = (string) ($this->configModel->getConfig('school_year') ?? '');
|
|
||||||
|
|
||||||
$dryRun = CLI::getOption('dry-run');
|
|
||||||
$reportOnly = CLI::getOption('report-only');
|
|
||||||
$mode = $reportOnly ? 'REPORT-ONLY' : ($dryRun ? 'DRY-RUN' : 'LIVE');
|
|
||||||
|
|
||||||
$paypalEntries = $this->paypalModel
|
|
||||||
->where('status', 'COMPLETED')
|
|
||||||
->where('synced', 0)
|
|
||||||
->where('sync_attempts <', 3)
|
|
||||||
->where('transaction_id IS NOT NULL')
|
|
||||||
->findAll();
|
|
||||||
|
|
||||||
$syncedCount = 0;
|
|
||||||
$failed = [];
|
|
||||||
|
|
||||||
foreach ($paypalEntries as $entry) {
|
|
||||||
$parentId = null;
|
|
||||||
$invoiceId = 0;
|
|
||||||
|
|
||||||
$users = $this->userModel->getUsersBySchoolId($entry['parent_school_id']);
|
|
||||||
$user = $users[0] ?? null;
|
|
||||||
|
|
||||||
// Always increment sync_attempts unless report-only
|
|
||||||
if (!$reportOnly) {
|
|
||||||
$this->paypalModel->update($entry['id'], [
|
|
||||||
'sync_attempts' => $entry['sync_attempts'] + 1
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($user) {
|
|
||||||
$parentId = $user['id'];
|
|
||||||
|
|
||||||
$invoice = $this->invoiceModel->getInvoicesByParentId($parentId, $this->schoolYear);
|
|
||||||
|
|
||||||
if (!$reportOnly && !$dryRun) {
|
|
||||||
if ($invoice) {
|
|
||||||
$invoiceId = $invoice['id'];
|
|
||||||
|
|
||||||
$success = $this->processPayment(
|
|
||||||
$invoiceId,
|
|
||||||
$entry['amount'],
|
|
||||||
'PayPal',
|
|
||||||
null,
|
|
||||||
$entry['transaction_id'],
|
|
||||||
date('Y-m-d', strtotime($entry['created_at'])),
|
|
||||||
$this->schoolYear,
|
|
||||||
$this->semester
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!$success) {
|
|
||||||
$failed[] = $entry['transaction_id'];
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$this->paymentModel->insert([
|
|
||||||
'parent_id' => $parentId,
|
|
||||||
'invoice_id' => 0,
|
|
||||||
'total_amount' => $entry['amount'],
|
|
||||||
'paid_amount' => $entry['amount'],
|
|
||||||
'balance' => 0.00,
|
|
||||||
'number_of_installments' => 1,
|
|
||||||
'transaction_id' => $entry['transaction_id'],
|
|
||||||
'payment_method' => 'PayPal',
|
|
||||||
'payment_date' => date('Y-m-d', strtotime($entry['created_at'])),
|
|
||||||
'school_year' => $this->schoolYear,
|
|
||||||
'semester' => $this->semester,
|
|
||||||
'status' => 'Completed',
|
|
||||||
'updated_by' => null,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mark as synced only in LIVE mode
|
|
||||||
$this->paypalModel->update($entry['id'], ['synced' => 1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$syncedCount++;
|
|
||||||
} else {
|
|
||||||
log_message('error', "[PAYPAL SYNC FAILED] No user found for parent_school_id: {$entry['parent_school_id']}");
|
|
||||||
$failed[] = $entry['transaction_id'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// === Logging ===
|
|
||||||
log_message('info', "[$mode] PAYPAL SYNC: $syncedCount processed.");
|
|
||||||
if (!empty($failed)) {
|
|
||||||
log_message('error', "[$mode] PAYPAL SYNC Failed: " . implode(', ', $failed));
|
|
||||||
}
|
|
||||||
|
|
||||||
// === CLI Output ===
|
|
||||||
CLI::write("[$mode] $syncedCount PayPal payments processed.", 'green');
|
|
||||||
if (!empty($failed)) {
|
|
||||||
CLI::error("[$mode] Failed transactions: " . implode(', ', $failed));
|
|
||||||
}
|
|
||||||
|
|
||||||
// === Email Report: Only if there's any update ===
|
|
||||||
if ($syncedCount > 0 || !empty($failed)) {
|
|
||||||
helper('email');
|
|
||||||
$email = \Config\Services::email();
|
|
||||||
$email->setTo('support@alrahmaisgl.org');
|
|
||||||
$email->setFrom('no-parentsreply@alrahmaisgl.org', 'PayPal Sync Report');
|
|
||||||
$email->setSubject("[$mode] PayPal Sync Report - " . date('Y-m-d H:i'));
|
|
||||||
|
|
||||||
$body = "PayPal Sync Mode: $mode\n\n";
|
|
||||||
$body .= "$syncedCount PayPal payments processed.\n\n";
|
|
||||||
|
|
||||||
if (!empty($failed)) {
|
|
||||||
$body .= count($failed) . " failed transactions:\n";
|
|
||||||
$body .= implode("\n", $failed);
|
|
||||||
} else {
|
|
||||||
$body .= "No failed transactions.\n";
|
|
||||||
}
|
|
||||||
|
|
||||||
$email->setMessage(nl2br($body));
|
|
||||||
|
|
||||||
if ($email->send()) {
|
|
||||||
CLI::write("[$mode] Email report sent successfully.", 'yellow');
|
|
||||||
} else {
|
|
||||||
CLI::error("[$mode] Failed to send email report.");
|
|
||||||
log_message('error', 'Email send error: ' . $email->printDebugger(['headers']));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log_message('info', "[$mode] No PayPal sync updates. Email not sent.");
|
|
||||||
CLI::write("[$mode] No changes to report. Email not sent.", 'blue');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private function processPayment($invoiceId, $amount, $paymentMethod, $checkFile = null, $transactionId = null, $paymentDate = null, $schoolYear = null, $semester = null)
|
|
||||||
{
|
|
||||||
$invoice = $this->invoiceModel->find($invoiceId);
|
|
||||||
if (!$invoice) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$transactionId = $transactionId ?? 'INV-' . $invoiceId . '-' . time();
|
|
||||||
$paymentDate = $paymentDate ?? date('Y-m-d');
|
|
||||||
|
|
||||||
$newPaid = $invoice['paid_amount'] + $amount;
|
|
||||||
$newBalance = $invoice['balance'] - $amount;
|
|
||||||
|
|
||||||
$invoiceUpdateData = [
|
|
||||||
'paid_amount' => $newPaid,
|
|
||||||
'balance' => $newBalance,
|
|
||||||
'status' => ($newBalance <= 0) ? 'Paid' : $invoice['status'],
|
|
||||||
];
|
|
||||||
|
|
||||||
if (!$this->invoiceModel->update($invoiceId, $invoiceUpdateData)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->paymentModel->insert([
|
|
||||||
'parent_id' => $invoice['parent_id'],
|
|
||||||
'invoice_id' => $invoiceId,
|
|
||||||
'total_amount' => $invoice['total_amount'],
|
|
||||||
'paid_amount' => $amount,
|
|
||||||
'balance' => $newBalance,
|
|
||||||
'number_of_installments' => 1,
|
|
||||||
'transaction_id' => $transactionId,
|
|
||||||
'payment_method' => $paymentMethod,
|
|
||||||
'payment_date' => $paymentDate,
|
|
||||||
'status' => ($newBalance <= 0) ? 'Full' : 'Partial',
|
|
||||||
'check_file' => $checkFile,
|
|
||||||
'updated_by' => null, // Avoid using session()->get() in CLI
|
|
||||||
'school_year' => $schoolYear,
|
|
||||||
'semester' => $semester
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->updateEnrollmentStatusIfPaid($invoiceId, $schoolYear);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private function updateEnrollmentStatusIfPaid($invoiceId, $schoolYear)
|
|
||||||
{
|
|
||||||
$invoice = $this->invoiceModel->find($invoiceId);
|
|
||||||
if (!$invoice || $invoice['balance'] > 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$students = $this->studentModel->where('parent_id', $invoice['parent_id'])
|
|
||||||
->where('school_year', $schoolYear)
|
|
||||||
->findAll();
|
|
||||||
|
|
||||||
foreach ($students as $student) {
|
|
||||||
$this->enrollmentModel->set(['enrollment_status' => 'enrolled'])
|
|
||||||
->where('student_id', $student['id'])
|
|
||||||
->update();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -16,11 +16,11 @@ class Commands extends BaseService
|
|||||||
\App\Commands\CleanupPasswordResets::class,
|
\App\Commands\CleanupPasswordResets::class,
|
||||||
\App\Commands\ConfigUpdate::class,
|
\App\Commands\ConfigUpdate::class,
|
||||||
\App\Commands\DeleteInactiveUsers::class,
|
\App\Commands\DeleteInactiveUsers::class,
|
||||||
|
\App\Commands\RecalculateInvoices::class,
|
||||||
\App\Commands\SendAbsenteesSummary::class,
|
\App\Commands\SendAbsenteesSummary::class,
|
||||||
\App\Commands\SendLatesSummary::class,
|
\App\Commands\SendLatesSummary::class,
|
||||||
\App\Commands\SendMonthlyPaymentNotifications::class,
|
\App\Commands\SendMonthlyPaymentNotifications::class,
|
||||||
\App\Commands\SendTestPaymentNotification::class,
|
\App\Commands\SendTestPaymentNotification::class,
|
||||||
\App\Commands\SyncPaypalPayments::class,
|
|
||||||
\App\Commands\RecalculateAttendance::class,
|
\App\Commands\RecalculateAttendance::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -47,10 +47,6 @@ class Filters extends BaseConfig
|
|||||||
'sanitizeinput',
|
'sanitizeinput',
|
||||||
'invalidchars',
|
'invalidchars',
|
||||||
'csrf' => ['except' => [
|
'csrf' => ['except' => [
|
||||||
// Webhooks / integrations
|
|
||||||
'api/paypal-webhook',
|
|
||||||
'index.php/api/paypal-webhook',
|
|
||||||
|
|
||||||
// WhatsApp membership management (legacy allowances retained)
|
// WhatsApp membership management (legacy allowances retained)
|
||||||
'whatsapp/update-membership',
|
'whatsapp/update-membership',
|
||||||
'index.php/whatsapp/update-membership',
|
'index.php/whatsapp/update-membership',
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Config;
|
|
||||||
|
|
||||||
use CodeIgniter\Config\BaseConfig;
|
|
||||||
|
|
||||||
class PaypalConfig extends BaseConfig
|
|
||||||
{
|
|
||||||
// PayPal API Credentials
|
|
||||||
public $paypalClientId = 'YOUR_PAYPAL_CLIENT_ID';
|
|
||||||
public $paypalSecret = 'YOUR_PAYPAL_SECRET';
|
|
||||||
public $paypalMode = 'sandbox'; // Change to 'live' when moving to production
|
|
||||||
}
|
|
||||||
+69
-75
@@ -257,15 +257,17 @@ $routes->post('administrator/sections/auto-distribute', 'View\StudentController:
|
|||||||
$routes->get('administrator/sections/promotion-totals', 'View\StudentController::promotionTotalsApi');
|
$routes->get('administrator/sections/promotion-totals', 'View\StudentController::promotionTotalsApi');
|
||||||
|
|
||||||
|
|
||||||
$routes->get('refunds/list', 'View\RefundController::listRefunds');
|
$routes->get('refunds/list', 'View\RefundController::listRefunds', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->post('refunds/request', 'View\RefundController::requestRefund');
|
$routes->post('refunds/request', 'View\RefundController::requestRefund', ['filter' => 'auth:create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||||
$routes->post('refunds/approve/(:num)', 'View\RefundController::approveRefund/$1');
|
$routes->post('refunds/approve/(:num)', 'View\RefundController::approveRefund/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->post('refunds/pay/(:num)', 'View\RefundController::payRefund/$1');
|
$routes->post('refunds/pay/(:num)', 'View\RefundController::payRefund/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->post('refunds/updateStatus/(:num)', 'View\RefundController::updateStatus/$1');
|
$routes->post('refunds/updateStatus/(:num)', 'View\RefundController::updateStatus/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->post('refunds/processRefunds', 'View\RefundController::processRefunds');
|
$routes->post('refunds/processRefunds', 'View\RefundController::processRefunds', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->post('refunds/updateStatus', 'View\RefundController::updateStatus');
|
$routes->post('refunds/updateStatus', 'View\RefundController::updateStatus', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->post('refunds/updatePayment', 'View\RefundController::updatePayment');
|
$routes->post('refunds/updatePayment', 'View\RefundController::updatePayment', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->post('refunds/recalculateOverpayments', 'View\RefundController::recalculateOverpayments');
|
$routes->post('refunds/recalculateOverpayments', 'View\RefundController::recalculateOverpayments', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
|
$routes->get('refunds/file/(:num)', 'View\RefundController::serveRefundFile/$1', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||||
|
$routes->get('refunds/file/(:num)/(:segment)', 'View\RefundController::serveRefundFile/$1/$2', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -528,10 +530,17 @@ $routes->post('grading/decisions/generate', 'View\GradingController::generateAll
|
|||||||
$routes->get('grading/below-60/decisions', 'View\GradingController::belowSixtyDecisions', ['filter' => 'auth:read']);
|
$routes->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->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/student-details', 'View\GradingController::studentDecisionDetails', ['filter' => 'auth:read']);
|
||||||
$routes->get('grading/below-60/decisions/email/preview', 'View\GradingController::previewDecisionEmail', ['filter' => 'auth:read']);
|
$routes->get(
|
||||||
$routes->get('grading/below-60/decisions/email/edit', 'View\GradingController::editDecisionEmail', ['filter' => 'auth:read']);
|
'grading/below-60/decisions/email/preview',
|
||||||
$routes->post('grading/below-60/decisions/email', 'View\GradingController::sendDecisionEmail', ['filter' => 'auth:read']);
|
'View\GradingController::previewBelowSixtyDecisionEmail',
|
||||||
|
['filter' => 'auth:read']
|
||||||
|
);
|
||||||
|
|
||||||
|
$routes->post(
|
||||||
|
'grading/below-60/decisions/email',
|
||||||
|
'View\GradingController::sendBelowSixtyDecisionEmail',
|
||||||
|
['filter' => 'auth:read']
|
||||||
|
);
|
||||||
|
|
||||||
// Final part
|
// Final part
|
||||||
$routes->get('grading/(:segment)/(:num)/(:num)', 'View\GradingController::show/$1/$2/$3');
|
$routes->get('grading/(:segment)/(:num)/(:num)', 'View\GradingController::show/$1/$2/$3');
|
||||||
@@ -579,19 +588,19 @@ $routes->post('invoices/updateStatus/(:num)', 'View\InvoiceController::updateSta
|
|||||||
// app/Config/Routes.php
|
// app/Config/Routes.php
|
||||||
$routes->group('payment', ['filter' => 'auth'], static function ($routes) {
|
$routes->group('payment', ['filter' => 'auth'], static function ($routes) {
|
||||||
// Read
|
// Read
|
||||||
$routes->get('manual_pay', 'View\PaymentController::manualPaySearch', ['filter' => 'auth:read']);
|
$routes->get('manual_pay', 'View\PaymentController::manualPaySearch', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->get('manual_pay_suggest', 'View\PaymentController::manualPaySuggest', ['filter' => 'auth:read']);
|
$routes->get('manual_pay_suggest', 'View\PaymentController::manualPaySuggest', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||||
|
|
||||||
// Create
|
// Create
|
||||||
$routes->post('manual_pay', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:create']);
|
$routes->post('manual_pay', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:create_payment|create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||||
|
|
||||||
// Update
|
// Update
|
||||||
$routes->post('manual_pay_edit', 'View\PaymentController::manualPayEdit', ['filter' => 'auth:update']);
|
$routes->post('manual_pay_edit', 'View\PaymentController::manualPayEdit', ['filter' => 'auth:update_payment|update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->post('manual_pay_update', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:update']);
|
$routes->post('manual_pay_update', 'View\PaymentController::manualPayUpdate', ['filter' => 'auth:create_payment|create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||||
|
|
||||||
// Read (serve files)
|
// Read (serve files)
|
||||||
$routes->get('serveCheckFile/(:any)/(:any)', 'View\PaymentController::serveCheckFile/$1/$2', ['filter' => 'auth:read']);
|
$routes->get('file/(:num)/(:segment)', 'View\PaymentController::servePaymentFile/$1/$2', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->get('serveCheckFile/(:any)', 'View\PaymentController::serveCheckFile/$1', ['filter' => 'auth:read']);
|
$routes->get('file/(:num)', 'View\PaymentController::servePaymentFile/$1', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
@@ -634,9 +643,14 @@ $routes->group('admin', ['filter' => 'auth'], static function ($routes) {
|
|||||||
$routes->post('admin/broadcast-email/upload-image', 'View\BroadcastEmailController::uploadImage');
|
$routes->post('admin/broadcast-email/upload-image', 'View\BroadcastEmailController::uploadImage');
|
||||||
|
|
||||||
|
|
||||||
$routes->get('payment/financial_report', 'View\FinancialController::financialReport');
|
$routes->get('payment/financial_report', 'View\FinancialController::financialReport', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||||
$routes->get('financial-report/financialReportSummary', 'View\FinancialController::financialReportSummary');
|
$routes->get('financial-report/financialReportSummary', 'View\FinancialController::financialReportSummary', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||||
$routes->get('payment/download_csv', 'View\FinancialController::downloadCsv');
|
$routes->get('financial-report/downloadSummaryCsv', 'View\FinancialController::downloadSummaryCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||||
|
$routes->get('financial-report/downloadSummaryAllDetailsCsv', 'View\FinancialController::downloadSummaryAllDetailsCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||||
|
$routes->get('payment/download_csv', 'View\FinancialController::downloadCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||||
|
$routes->get('administrator/tuition-forecast', 'View\TuitionForecastController::index', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||||
|
$routes->post('administrator/tuition-forecast/calculate', 'View\TuitionForecastController::calculate', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||||
|
$routes->get('administrator/tuition-forecast/export', 'View\TuitionForecastController::exportCsv', ['filter' => 'auth:view_financial_reports|view_invoice|administrator|administrative staff|principal']);
|
||||||
$routes->get('reports/downloadFinancialReport', 'View\FinancialController::downloadFinancialReport');
|
$routes->get('reports/downloadFinancialReport', 'View\FinancialController::downloadFinancialReport');
|
||||||
// Financial APIs (JSON)
|
// Financial APIs (JSON)
|
||||||
$routes->get('api/financial/report', 'View\FinancialController::financialReportData', ['filter' => 'auth']);
|
$routes->get('api/financial/report', 'View\FinancialController::financialReportData', ['filter' => 'auth']);
|
||||||
@@ -647,27 +661,27 @@ $routes->get('payment/unpaid-parents', 'View\FinancialController::unpaidParents'
|
|||||||
$routes->get('api/financial/unpaid-parents', 'View\FinancialController::unpaidParents', ['filter' => 'auth:view_invoice']);
|
$routes->get('api/financial/unpaid-parents', 'View\FinancialController::unpaidParents', ['filter' => 'auth:view_invoice']);
|
||||||
|
|
||||||
|
|
||||||
$routes->get('expenses/index', 'View\ExpenseController::index');
|
$routes->get('expenses/index', 'View\ExpenseController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->get('expenses/create', 'View\ExpenseController::create');
|
$routes->get('expenses/create', 'View\ExpenseController::create', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->post('expenses/store', 'View\ExpenseController::store');
|
$routes->post('expenses/store', 'View\ExpenseController::store', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,create']);
|
||||||
$routes->post('expenses/updateStatus', 'View\ExpenseController::updateStatus');
|
$routes->post('expenses/updateStatus', 'View\ExpenseController::updateStatus', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
|
|
||||||
$routes->get('reimbursements/index', 'View\ReimbursementController::index');
|
$routes->get('reimbursements/index', 'View\ReimbursementController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->get('reimbursements/create', 'View\ReimbursementController::create');
|
$routes->get('reimbursements/create', 'View\ReimbursementController::create', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->post('reimbursements/store', 'View\ReimbursementController::store');
|
$routes->post('reimbursements/store', 'View\ReimbursementController::store', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,create']);
|
||||||
$routes->get('reimbursements/under-processing', 'View\ReimbursementController::underProcessing');
|
$routes->get('reimbursements/under-processing', 'View\ReimbursementController::underProcessing', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->post('reimbursements/mark-donation', 'View\ReimbursementController::markDonation');
|
$routes->post('reimbursements/mark-donation', 'View\ReimbursementController::markDonation', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->post('reimbursements/batch/create', 'View\ReimbursementController::createBatch');
|
$routes->post('reimbursements/batch/create', 'View\ReimbursementController::createBatch', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,create']);
|
||||||
$routes->post('reimbursements/batch/update', 'View\ReimbursementController::updateBatchAssignment');
|
$routes->post('reimbursements/batch/update', 'View\ReimbursementController::updateBatchAssignment', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->post('reimbursements/batch/lock', 'View\ReimbursementController::lockBatch');
|
$routes->post('reimbursements/batch/lock', 'View\ReimbursementController::lockBatch', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->post('reimbursements/batch/admin-file/upload', 'View\ReimbursementController::uploadBatchAdminFile');
|
$routes->post('reimbursements/batch/admin-file/upload', 'View\ReimbursementController::uploadBatchAdminFile', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->get('reimbursements/batch/admin-file/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1');
|
$routes->get('reimbursements/batch/admin-file/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->get('reimbursements/batch/admin-file/(:segment)/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1/$2');
|
$routes->get('reimbursements/batch/admin-file/(:segment)/(:segment)', 'View\ReimbursementController::serveAdminCheckFile/$1/$2', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->post('reimbursements/batch/send', 'View\ReimbursementController::sendBatchEmail');
|
$routes->post('reimbursements/batch/send', 'View\ReimbursementController::sendBatchEmail', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->get('reimbursements/batch/export', 'View\ReimbursementController::exportBatch');
|
$routes->get('reimbursements/batch/export', 'View\ReimbursementController::exportBatch', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->post('reimbursements/process', 'View\ReimbursementController::process');
|
$routes->post('reimbursements/process', 'View\ReimbursementController::process', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->get('reimbursements/export', 'View\ReimbursementController::export');
|
$routes->get('reimbursements/export', 'View\ReimbursementController::export', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->get('reimbursements', 'View\ReimbursementController::index');
|
$routes->get('reimbursements', 'View\ReimbursementController::index', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
|
|
||||||
// Health check (upload dirs + DB timezone columns)
|
// Health check (upload dirs + DB timezone columns)
|
||||||
$routes->get('admin/health', 'View\HealthController::index');
|
$routes->get('admin/health', 'View\HealthController::index');
|
||||||
@@ -734,14 +748,9 @@ $routes->get('payment_transactions/getByPayment/(:num)', 'View\PaymentTransactio
|
|||||||
$routes->get('payment_transactions/create', 'View\PaymentTransactionController::create');
|
$routes->get('payment_transactions/create', 'View\PaymentTransactionController::create');
|
||||||
$routes->post('payment_transactions/updateStatus/(:num)', 'View\PaymentTransactionController::updateStatus/$1');
|
$routes->post('payment_transactions/updateStatus/(:num)', 'View\PaymentTransactionController::updateStatus/$1');
|
||||||
|
|
||||||
// Routes for PayPal integration
|
// Routes for payment pages
|
||||||
$routes->get('payments/createPaypalPayment/(:num)', 'View\PaymentController::createPaypalPayment/$1');
|
|
||||||
$routes->get('payments/executePaypalPayment', 'View\PaymentController::executePaypalPayment');
|
|
||||||
$routes->get('payments/cancelPaypalPayment', 'View\PaymentController::cancelPaypalPayment');
|
|
||||||
|
|
||||||
$routes->get('payments/view/(:num)', 'View\PaymentController::viewPayment/$1');
|
$routes->get('payments/view/(:num)', 'View\PaymentController::viewPayment/$1');
|
||||||
$routes->post('payments/createPaypalPayment/(:num)', 'View\PaymentController::createPaypalPayment/$1');
|
$routes->get('payment/get_enrolled_students/(:num)', 'View\PaymentController::getEnrolledStudents/$1', ['filter' => 'auth:view_invoice|view_payment|view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->get('payment/get_enrolled_students/(:num)', 'View\PaymentController::getEnrolledStudents/$1');
|
|
||||||
|
|
||||||
// Payment Notification Management
|
// Payment Notification Management
|
||||||
$routes->get('payment/notification_management', 'View\PaymentNotificationController::index', ['filter' => 'auth:view_invoice']);
|
$routes->get('payment/notification_management', 'View\PaymentNotificationController::index', ['filter' => 'auth:view_invoice']);
|
||||||
@@ -961,15 +970,6 @@ $routes->group('inventory', ['filter' => 'csrf'], static function ($routes) {
|
|||||||
$routes->get('admin/enrollment/new-students', 'View\AdministratorController::showNewStudents', ['filter' => 'auth:view_new_students']);
|
$routes->get('admin/enrollment/new-students', 'View\AdministratorController::showNewStudents', ['filter' => 'auth:view_new_students']);
|
||||||
|
|
||||||
|
|
||||||
//Paypal transactions
|
|
||||||
$routes->post('api/paypal-webhook', 'Api\PaypalWebhook::handle');
|
|
||||||
$routes->get('administrator/paypal_transactions', 'View\PaypalTransactionsController::index');
|
|
||||||
$routes->get('administrator/paypal_transactions/export', 'View\PaypalTransactionsController::exportCsv');
|
|
||||||
$routes->get('admin/paypal-transactions', 'View\PaypalTransactionsController::index');
|
|
||||||
$routes->get('admin/paypal-transactions/export', 'View\PaypalTransactionsController::exportCsv');
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
//Emergency Contact
|
//Emergency Contact
|
||||||
$routes->get('administrator/emergency_contact', 'View\EmergencyContactController::index');
|
$routes->get('administrator/emergency_contact', 'View\EmergencyContactController::index');
|
||||||
$routes->get('administrator/emergency_contact/edit/(:num)', 'View\EmergencyContactController::edit/$1');
|
$routes->get('administrator/emergency_contact/edit/(:num)', 'View\EmergencyContactController::edit/$1');
|
||||||
@@ -1048,16 +1048,16 @@ $routes->get('family', 'View\FamilyAdminController::index');
|
|||||||
//////////////////////////////////////////////////////////
|
//////////////////////////////////////////////////////////
|
||||||
|
|
||||||
//upload files
|
//upload files
|
||||||
$routes->get('receipts/(:any)', 'View\FilesController::receipt/$1');
|
$routes->get('receipts/(:any)', 'View\FilesController::receipt/$1', ['filter' => 'auth']);
|
||||||
$routes->get('reimbreceipts/(:any)', 'View\FilesController::reimb/$1'); // serves from writable/uploads/reimbursements
|
$routes->get('reimbreceipts/(:any)', 'View\FilesController::reimb/$1', ['filter' => 'auth']); // serves from writable/uploads/reimbursements
|
||||||
$routes->get('early-dismissal-signatures/(:any)', 'View\FilesController::earlyDismissalSignature/$1');
|
$routes->get('early-dismissal-signatures/(:any)', 'View\FilesController::earlyDismissalSignature/$1');
|
||||||
// Expenses
|
// Expenses
|
||||||
$routes->get('expenses/edit/(:num)', 'View\ExpenseController::edit/$1');
|
$routes->get('expenses/edit/(:num)', 'View\ExpenseController::edit/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->post('expenses/update/(:num)', 'View\ExpenseController::update/$1');
|
$routes->post('expenses/update/(:num)', 'View\ExpenseController::update/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
|
|
||||||
// Reimbursements
|
// Reimbursements
|
||||||
$routes->get('reimbursements/edit/(:num)', 'View\ReimbursementController::edit/$1');
|
$routes->get('reimbursements/edit/(:num)', 'View\ReimbursementController::edit/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->post('reimbursements/update/(:num)', 'View\ReimbursementController::update/$1');
|
$routes->post('reimbursements/update/(:num)', 'View\ReimbursementController::update/$1', ['filter' => 'auth:view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1202,16 +1202,15 @@ $routes->get('/terms_of_service', 'View\PageController::termsOfService');
|
|||||||
$routes->get('/help_center', 'View\PageController::helpCenter');
|
$routes->get('/help_center', 'View\PageController::helpCenter');
|
||||||
|
|
||||||
//payment
|
//payment
|
||||||
$routes->get('/payment', 'View\PaymentController::redirectPage');
|
$routes->get('/payment', 'View\PaymentController::redirectPage', ['filter' => 'auth:parent']);
|
||||||
$routes->get('/payment/paypal', 'View\PaymentController::paypal');
|
|
||||||
$routes->get('/payment/manual', 'View\PaymentController::manual');
|
$routes->get('/payment/manual', 'View\PaymentController::manual');
|
||||||
$routes->post('/payment/manual', 'View\PaymentController::manual');
|
$routes->post('/payment/manual', 'View\PaymentController::manual');
|
||||||
|
|
||||||
// Voucher management
|
// Voucher management
|
||||||
$routes->get('discounts/list', 'View\DiscountController::listVouchers');
|
$routes->get('discounts/list', 'View\DiscountController::listVouchers', ['filter' => 'auth:view_invoice|view_financial_reports|administrator|administrative staff|principal']);
|
||||||
$routes->match(['get', 'post'], 'discount/create', 'View\DiscountController::createVoucher');
|
$routes->match(['get', 'post'], 'discount/create', 'View\DiscountController::createVoucher', ['filter' => 'auth:create_invoice|view_financial_reports|administrator|administrative staff|principal,create']);
|
||||||
$routes->match(['get', 'post'], 'discount/editVoucher/(:num)', 'View\DiscountController::editVoucher/$1');
|
$routes->match(['get', 'post'], 'discount/editVoucher/(:num)', 'View\DiscountController::editVoucher/$1', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
$routes->match(['get', 'post'], 'discount/apply', 'View\DiscountController::applyVoucher');
|
$routes->match(['get', 'post'], 'discount/apply', 'View\DiscountController::applyVoucher', ['filter' => 'auth:update_invoice|view_financial_reports|administrator|administrative staff|principal,update']);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1555,11 +1554,6 @@ $routes->group('api/v1', ['filter' => 'apiAuth', 'namespace' => 'App\Controllers
|
|||||||
$routes->get('class-preparation/(:num)', 'View\SupportController::show/$1');
|
$routes->get('class-preparation/(:num)', 'View\SupportController::show/$1');
|
||||||
$routes->post('class-preparation/(:num)/mark-printed', 'View\SupportController::markPrinted/$1');
|
$routes->post('class-preparation/(:num)/mark-printed', 'View\SupportController::markPrinted/$1');
|
||||||
|
|
||||||
// PayPal Transactions
|
|
||||||
$routes->get('paypal-transactions', 'View\UserController::index');
|
|
||||||
$routes->get('paypal-transactions/(:num)', 'View\SupportController::show/$1');
|
|
||||||
$routes->get('paypal-transactions/transaction/(:segment)', 'View\SupportController::getByTransactionId/$1');
|
|
||||||
|
|
||||||
// Stats
|
// Stats
|
||||||
$routes->get('stats', 'View\UserController::index');
|
$routes->get('stats', 'View\UserController::index');
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ use App\Controllers\BaseController;
|
|||||||
use App\Models\ClassSectionModel;
|
use App\Models\ClassSectionModel;
|
||||||
use App\Models\ConfigurationModel;
|
use App\Models\ConfigurationModel;
|
||||||
use App\Models\CertificateRecordModel;
|
use App\Models\CertificateRecordModel;
|
||||||
use App\Models\StudentDecisionModel;
|
|
||||||
|
|
||||||
class CertificateController extends BaseController
|
class CertificateController extends BaseController
|
||||||
{
|
{
|
||||||
@@ -27,9 +26,9 @@ class CertificateController extends BaseController
|
|||||||
|
|
||||||
public function index()
|
public function index()
|
||||||
{
|
{
|
||||||
$db = \Config\Database::connect();
|
$db = \Config\Database::connect();
|
||||||
$selectedCsid = $this->request->getGet('class_section_id');
|
$selectedCsid = $this->request->getGet('class_section_id');
|
||||||
$schoolYear = $this->request->getGet('school_year') ?? $this->schoolYear;
|
$schoolYear = $this->request->getGet('school_year') ?? $this->schoolYear;
|
||||||
|
|
||||||
// ── All enrolled students across every class section ───────────────────
|
// ── All enrolled students across every class section ───────────────────
|
||||||
$allEnrolled = $db->table('student_class sc')
|
$allEnrolled = $db->table('student_class sc')
|
||||||
@@ -40,96 +39,126 @@ class CertificateController extends BaseController
|
|||||||
->where('sc.school_year', $schoolYear)
|
->where('sc.school_year', $schoolYear)
|
||||||
->orderBy('s.firstname', 'ASC')
|
->orderBy('s.firstname', 'ASC')
|
||||||
->orderBy('s.lastname', 'ASC')
|
->orderBy('s.lastname', 'ASC')
|
||||||
->get()->getResultArray();
|
->get()
|
||||||
|
->getResultArray();
|
||||||
|
|
||||||
$allIds = array_unique(array_column($allEnrolled, 'student_id'));
|
$allIds = array_values(array_unique(array_map('intval', array_column($allEnrolled, 'student_id'))));
|
||||||
|
|
||||||
|
// ── Saved generated YEAR decisions from student_decisions ──────────────
|
||||||
|
//
|
||||||
|
// Source of truth:
|
||||||
|
// student_decisions.year_score
|
||||||
|
// student_decisions.decision
|
||||||
|
//
|
||||||
|
// Do NOT recalculate certificate decisions here from semester_scores.
|
||||||
|
$decisionsByStudent = [];
|
||||||
|
|
||||||
// ── Semester scores ────────────────────────────────────────────────────
|
|
||||||
$allScoreMap = [];
|
|
||||||
if (!empty($allIds)) {
|
if (!empty($allIds)) {
|
||||||
foreach ($db->table('semester_scores')
|
$decisionRows = $db->table('student_decisions')
|
||||||
->select('student_id, semester, semester_score')
|
|
||||||
->whereIn('student_id', $allIds)
|
->whereIn('student_id', $allIds)
|
||||||
->where('school_year', $schoolYear)
|
->where('school_year', $schoolYear)
|
||||||
->where('semester_score IS NOT NULL', null, false)
|
->get()
|
||||||
->get()->getResultArray() as $sr) {
|
->getResultArray();
|
||||||
$allScoreMap[(int)$sr['student_id']][ucfirst(strtolower($sr['semester']))] =
|
|
||||||
is_numeric($sr['semester_score']) ? (float)$sr['semester_score'] : null;
|
foreach ($decisionRows as $d) {
|
||||||
|
$sid = (int)($d['student_id'] ?? 0);
|
||||||
|
|
||||||
|
if ($sid <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$decision = trim((string)($d['decision'] ?? ''));
|
||||||
|
$source = trim((string)($d['source'] ?? ''));
|
||||||
|
|
||||||
|
if ($source === '') {
|
||||||
|
$source = $decision === '' ? 'pending' : 'manual';
|
||||||
|
}
|
||||||
|
|
||||||
|
$decisionsByStudent[$sid]['Year'] = [
|
||||||
|
'decision' => $decision,
|
||||||
|
'source' => $source,
|
||||||
|
'notes' => (string)($d['notes'] ?? ''),
|
||||||
|
'year_score' => $d['year_score'] ?? null,
|
||||||
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Below-60 manual decisions ──────────────────────────────────────────
|
// ── Certificate records: most recent per student ───────────────────────
|
||||||
$allBelowMap = [];
|
|
||||||
if (!empty($allIds)) {
|
|
||||||
foreach ($db->table('below_sixty_decisions')
|
|
||||||
->whereIn('student_id', $allIds)
|
|
||||||
->where('school_year', $schoolYear)
|
|
||||||
->get()->getResultArray() as $b) {
|
|
||||||
$allBelowMap[(int)$b['student_id']][ucfirst(strtolower($b['semester']))] = (string)$b['decision'];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Certificate records (most recent per student) ──────────────────────
|
|
||||||
$certsByStudent = [];
|
$certsByStudent = [];
|
||||||
|
|
||||||
if (!empty($allIds)) {
|
if (!empty($allIds)) {
|
||||||
foreach ($db->table('certificate_records')
|
foreach ($db->table('certificate_records')
|
||||||
->select('student_id, certificate_number, issued_at')
|
->select('student_id, certificate_number, issued_at')
|
||||||
->whereIn('student_id', $allIds)
|
->whereIn('student_id', $allIds)
|
||||||
->where('school_year', $schoolYear)
|
->where('school_year', $schoolYear)
|
||||||
->orderBy('issued_at', 'DESC')
|
->orderBy('issued_at', 'DESC')
|
||||||
->get()->getResultArray() as $c) {
|
->get()
|
||||||
|
->getResultArray() as $c) {
|
||||||
$sid = (int)$c['student_id'];
|
$sid = (int)$c['student_id'];
|
||||||
|
|
||||||
if (!isset($certsByStudent[$sid])) {
|
if (!isset($certsByStudent[$sid])) {
|
||||||
$certsByStudent[$sid] = $c['certificate_number'];
|
$certsByStudent[$sid] = $c['certificate_number'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Build per-student decisions + per-class buckets ────────────────────
|
// ── Build per-class buckets and stats ──────────────────────────────────
|
||||||
$decisionsByStudent = [];
|
$studentsByClass = [];
|
||||||
$studentsByClass = []; // [csid => [student rows...]]
|
$statsPerClass = [];
|
||||||
$statsPerClass = []; // [csid => {name, total, pass, cert}]
|
|
||||||
|
|
||||||
foreach ($allEnrolled as $row) {
|
foreach ($allEnrolled as $row) {
|
||||||
$sid = (int)$row['student_id'];
|
$sid = (int)$row['student_id'];
|
||||||
$csid = (int)$row['class_section_id'];
|
$csid = (int)$row['class_section_id'];
|
||||||
|
|
||||||
// Decisions per semester
|
if (!isset($statsPerClass[$csid])) {
|
||||||
foreach ($allScoreMap[$sid] ?? [] as $sem => $score) {
|
$statsPerClass[$csid] = [
|
||||||
if ($score === null) continue;
|
'name' => $row['class_section_name'],
|
||||||
if ($score >= 60) {
|
'total' => 0,
|
||||||
$dec = 'Pass'; $src = 'auto';
|
'pass' => 0,
|
||||||
} elseif (!empty($allBelowMap[$sid][$sem])) {
|
'cert' => 0,
|
||||||
$dec = $allBelowMap[$sid][$sem]; $src = 'manual';
|
];
|
||||||
} else {
|
|
||||||
$dec = ''; $src = 'pending';
|
|
||||||
}
|
|
||||||
$decisionsByStudent[$sid][$sem] = ['decision' => $dec, 'source' => $src];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Per-class stats
|
|
||||||
if (!isset($statsPerClass[$csid])) {
|
|
||||||
$statsPerClass[$csid] = ['name' => $row['class_section_name'], 'total' => 0, 'pass' => 0, 'cert' => 0];
|
|
||||||
}
|
|
||||||
$statsPerClass[$csid]['total']++;
|
$statsPerClass[$csid]['total']++;
|
||||||
|
|
||||||
$sems = $allScoreMap[$sid] ?? [];
|
// If no generated decision exists yet, explicitly mark pending.
|
||||||
$isPass = !empty($sems);
|
if (!isset($decisionsByStudent[$sid])) {
|
||||||
foreach ($sems as $sem => $score) {
|
$decisionsByStudent[$sid]['Decision'] = [
|
||||||
if ($score === null) { $isPass = false; break; }
|
'decision' => '',
|
||||||
if ($score >= 60) continue;
|
'source' => 'pending',
|
||||||
$md = $allBelowMap[$sid][$sem] ?? '';
|
'notes' => '',
|
||||||
if ($md === '' || $md !== 'Pass') { $isPass = false; break; }
|
'year_score' => null,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Certificate eligibility:
|
||||||
|
// A student is eligible only if the saved final generated decision is Pass.
|
||||||
|
$studentDecisions = $decisionsByStudent[$sid] ?? [];
|
||||||
|
$isPass = !empty($studentDecisions);
|
||||||
|
|
||||||
|
foreach ($studentDecisions as $decisionRow) {
|
||||||
|
$decision = trim((string)($decisionRow['decision'] ?? ''));
|
||||||
|
|
||||||
|
if (strcasecmp($decision, 'Pass') !== 0) {
|
||||||
|
$isPass = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isPass) {
|
||||||
|
$statsPerClass[$csid]['pass']++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isset($certsByStudent[$sid])) {
|
||||||
|
$statsPerClass[$csid]['cert']++;
|
||||||
}
|
}
|
||||||
if ($isPass) $statsPerClass[$csid]['pass']++;
|
|
||||||
if (isset($certsByStudent[$sid])) $statsPerClass[$csid]['cert']++;
|
|
||||||
|
|
||||||
// Group students by class
|
|
||||||
$studentsByClass[$csid][] = $row;
|
$studentsByClass[$csid][] = $row;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Determine default active tab ───────────────────────────────────────
|
// ── Determine default active tab ───────────────────────────────────────
|
||||||
$firstCsid = !empty($allEnrolled) ? (int)$allEnrolled[0]['class_section_id'] : null;
|
$firstCsid = !empty($allEnrolled) ? (int)$allEnrolled[0]['class_section_id'] : null;
|
||||||
|
|
||||||
if ($selectedCsid === null && $firstCsid !== null) {
|
if ($selectedCsid === null && $firstCsid !== null) {
|
||||||
$selectedCsid = (string)$firstCsid;
|
$selectedCsid = (string)$firstCsid;
|
||||||
}
|
}
|
||||||
@@ -181,9 +210,12 @@ class CertificateController extends BaseController
|
|||||||
->where('cr.verification_token', $certNumber)
|
->where('cr.verification_token', $certNumber)
|
||||||
->orWhere('cr.certificate_number', strtoupper($certNumber))
|
->orWhere('cr.certificate_number', strtoupper($certNumber))
|
||||||
->groupEnd()
|
->groupEnd()
|
||||||
->get()->getRowArray();
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
|
||||||
return view('certificates/verify', ['record' => $record ?: null]);
|
return view('certificates/verify', [
|
||||||
|
'record' => $record ?: null,
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Reprint an existing certificate ──────────────────────────────────────
|
// ─── Reprint an existing certificate ──────────────────────────────────────
|
||||||
@@ -193,7 +225,8 @@ class CertificateController extends BaseController
|
|||||||
$record = \Config\Database::connect()
|
$record = \Config\Database::connect()
|
||||||
->table('certificate_records')
|
->table('certificate_records')
|
||||||
->where('certificate_number', strtoupper($certNumber))
|
->where('certificate_number', strtoupper($certNumber))
|
||||||
->get()->getRowArray();
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
|
||||||
if (!$record) {
|
if (!$record) {
|
||||||
return redirect()->to('administrator/certificates/log')
|
return redirect()->to('administrator/certificates/log')
|
||||||
@@ -201,23 +234,26 @@ class CertificateController extends BaseController
|
|||||||
}
|
}
|
||||||
|
|
||||||
$certDateFormatted = '';
|
$certDateFormatted = '';
|
||||||
|
|
||||||
if (!empty($record['cert_date'])) {
|
if (!empty($record['cert_date'])) {
|
||||||
$ts = strtotime((string)$record['cert_date']);
|
$ts = strtotime((string)$record['cert_date']);
|
||||||
|
|
||||||
if ($ts) {
|
if ($ts) {
|
||||||
$certDateFormatted = date('m/d/Y', $ts);
|
$certDateFormatted = date('m/d/Y', $ts);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$student = [
|
$student = [
|
||||||
'firstname' => (string)($record['student_name'] ?? ''),
|
'firstname' => (string)($record['student_name'] ?? ''),
|
||||||
'lastname' => '',
|
'lastname' => '',
|
||||||
'grade' => (string)($record['grade'] ?? ''),
|
'grade' => (string)($record['grade'] ?? ''),
|
||||||
'cert_number' => (string)($record['certificate_number'] ?? ''),
|
'cert_number' => (string)($record['certificate_number'] ?? ''),
|
||||||
'verify_token' => $this->ensureVerificationTokenForRecord($record),
|
'verify_token' => $this->ensureVerificationTokenForRecord($record),
|
||||||
];
|
];
|
||||||
|
|
||||||
// student_name is stored as "Firstname Lastname" — split for the PDF builder
|
// student_name is stored as "Firstname Lastname" — split for the PDF builder.
|
||||||
$parts = explode(' ', trim($student['firstname']), 2);
|
$parts = explode(' ', trim($student['firstname']), 2);
|
||||||
|
|
||||||
if (count($parts) === 2) {
|
if (count($parts) === 2) {
|
||||||
$student['firstname'] = $parts[0];
|
$student['firstname'] = $parts[0];
|
||||||
$student['lastname'] = $parts[1];
|
$student['lastname'] = $parts[1];
|
||||||
@@ -246,13 +282,15 @@ class CertificateController extends BaseController
|
|||||||
return $this->response
|
return $this->response
|
||||||
->setStatusCode(422)
|
->setStatusCode(422)
|
||||||
->setJSON([
|
->setJSON([
|
||||||
'ok' => false,
|
'ok' => false,
|
||||||
'error' => 'Please select at least one student.',
|
'error' => 'Please select at least one student.',
|
||||||
'csrf_token' => csrf_token(),
|
'csrf_token' => csrf_token(),
|
||||||
'csrf_hash' => csrf_hash(),
|
'csrf_hash' => csrf_hash(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
return redirect()->to('administrator/certificates')->with('error', 'Please select at least one student.');
|
|
||||||
|
return redirect()->to('administrator/certificates')
|
||||||
|
->with('error', 'Please select at least one student.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$studentIds = array_filter(array_map('intval', $studentIds));
|
$studentIds = array_filter(array_map('intval', $studentIds));
|
||||||
@@ -263,13 +301,15 @@ class CertificateController extends BaseController
|
|||||||
return $this->response
|
return $this->response
|
||||||
->setStatusCode(422)
|
->setStatusCode(422)
|
||||||
->setJSON([
|
->setJSON([
|
||||||
'ok' => false,
|
'ok' => false,
|
||||||
'error' => 'Invalid student selection.',
|
'error' => 'Invalid student selection.',
|
||||||
'csrf_token' => csrf_token(),
|
'csrf_token' => csrf_token(),
|
||||||
'csrf_hash' => csrf_hash(),
|
'csrf_hash' => csrf_hash(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
return redirect()->to('administrator/certificates')->with('error', 'Invalid student selection.');
|
|
||||||
|
return redirect()->to('administrator/certificates')
|
||||||
|
->with('error', 'Invalid student selection.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$db = \Config\Database::connect();
|
$db = \Config\Database::connect();
|
||||||
@@ -277,21 +317,26 @@ class CertificateController extends BaseController
|
|||||||
|
|
||||||
foreach ($studentIds as $id) {
|
foreach ($studentIds as $id) {
|
||||||
$row = null;
|
$row = null;
|
||||||
|
|
||||||
if ($classSectionId) {
|
if ($classSectionId) {
|
||||||
$row = $db->table('student_class sc')
|
$row = $db->table('student_class sc')
|
||||||
->select('s.id, s.firstname, s.lastname, cs.class_section_name AS grade')
|
->select('s.id, s.firstname, s.lastname, cs.class_section_name AS grade')
|
||||||
->join('students s', 's.id = sc.student_id')
|
->join('students s', 's.id = sc.student_id')
|
||||||
->join('classSection cs', 'cs.class_section_id = sc.class_section_id')
|
->join('classSection cs', 'cs.class_section_id = sc.class_section_id')
|
||||||
->where('sc.class_section_id', (int) $classSectionId)
|
->where('sc.class_section_id', (int)$classSectionId)
|
||||||
|
->where('sc.school_year', $schoolYear)
|
||||||
->where('s.id', $id)
|
->where('s.id', $id)
|
||||||
->get()->getRowArray();
|
->get()
|
||||||
|
->getRowArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$row) {
|
if (!$row) {
|
||||||
$s = $db->table('students')
|
$s = $db->table('students')
|
||||||
->select('id, firstname, lastname, registration_grade AS grade')
|
->select('id, firstname, lastname, registration_grade AS grade')
|
||||||
->where('id', $id)
|
->where('id', $id)
|
||||||
->get()->getRowArray();
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
|
||||||
$row = $s ?: null;
|
$row = $s ?: null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,57 +350,62 @@ class CertificateController extends BaseController
|
|||||||
return $this->response
|
return $this->response
|
||||||
->setStatusCode(422)
|
->setStatusCode(422)
|
||||||
->setJSON([
|
->setJSON([
|
||||||
'ok' => false,
|
'ok' => false,
|
||||||
'error' => 'No valid students found.',
|
'error' => 'No valid students found.',
|
||||||
'csrf_token' => csrf_token(),
|
'csrf_token' => csrf_token(),
|
||||||
'csrf_hash' => csrf_hash(),
|
'csrf_hash' => csrf_hash(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
return redirect()->to('administrator/certificates')->with('error', 'No valid students found.');
|
|
||||||
|
return redirect()->to('administrator/certificates')
|
||||||
|
->with('error', 'No valid students found.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$issuedBy = session()->get('user_id');
|
$issuedAt = date('Y-m-d H:i:s');
|
||||||
$issuedAt = date('Y-m-d H:i:s');
|
|
||||||
$certDateDb = $this->parseCertDate($certDate);
|
|
||||||
|
|
||||||
// Load any existing certificates for these students this school year
|
// Load existing certificates for these students this school year.
|
||||||
$db = \Config\Database::connect();
|
|
||||||
$existingCerts = $db->table('certificate_records')
|
$existingCerts = $db->table('certificate_records')
|
||||||
->select('id, student_id, certificate_number, verification_token')
|
->select('id, student_id, certificate_number, verification_token')
|
||||||
->whereIn('student_id', array_column($students, 'id'))
|
->whereIn('student_id', array_column($students, 'id'))
|
||||||
->where('school_year', $schoolYear)
|
->where('school_year', $schoolYear)
|
||||||
->get()->getResultArray();
|
->get()
|
||||||
|
->getResultArray();
|
||||||
|
|
||||||
$existingCertMap = [];
|
$existingCertMap = [];
|
||||||
|
|
||||||
foreach ($existingCerts as $ec) {
|
foreach ($existingCerts as $ec) {
|
||||||
$existingCertMap[(int)$ec['student_id']] = $ec;
|
$existingCertMap[(int)$ec['student_id']] = $ec;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($students as &$student) {
|
foreach ($students as &$student) {
|
||||||
$sid = (int)$student['id'];
|
$sid = (int)$student['id'];
|
||||||
|
|
||||||
if (isset($existingCertMap[$sid])) {
|
if (isset($existingCertMap[$sid])) {
|
||||||
// Reuse existing certificate number — do not create a new record
|
// Reuse existing certificate number — do not create a new record.
|
||||||
$existing = $existingCertMap[$sid];
|
$existing = $existingCertMap[$sid];
|
||||||
$student['cert_number'] = (string)($existing['certificate_number'] ?? '');
|
|
||||||
|
$student['cert_number'] = (string)($existing['certificate_number'] ?? '');
|
||||||
$student['verify_token'] = $this->ensureVerificationTokenForRecord($existing);
|
$student['verify_token'] = $this->ensureVerificationTokenForRecord($existing);
|
||||||
} else {
|
} else {
|
||||||
$certNumber = $this->certRecordModel->nextNumber($schoolYear);
|
$certNumber = $this->certRecordModel->nextNumber($schoolYear);
|
||||||
$verifyToken = $this->certRecordModel->generateVerificationToken();
|
$verifyToken = $this->certRecordModel->generateVerificationToken();
|
||||||
|
|
||||||
$this->certRecordModel->insert([
|
$this->certRecordModel->insert([
|
||||||
'certificate_number' => $certNumber,
|
'certificate_number' => $certNumber,
|
||||||
'verification_token' => $verifyToken,
|
'verification_token' => $verifyToken,
|
||||||
'student_id' => $sid,
|
'student_id' => $sid,
|
||||||
'student_name' => $student['firstname'] . ' ' . $student['lastname'],
|
'student_name' => $student['firstname'] . ' ' . $student['lastname'],
|
||||||
'grade' => $this->formatGrade($student['grade'] ?? ''),
|
'grade' => $this->formatGrade($student['grade'] ?? ''),
|
||||||
//'cert_date' => $certDateDb,
|
|
||||||
'school_year' => $schoolYear,
|
'school_year' => $schoolYear,
|
||||||
'class_section_id' => $classSectionId ?: null,
|
'class_section_id' => $classSectionId ?: null,
|
||||||
//'issued_by' => $issuedBy,
|
|
||||||
'issued_at' => $issuedAt,
|
'issued_at' => $issuedAt,
|
||||||
]);
|
]);
|
||||||
$student['cert_number'] = $certNumber;
|
|
||||||
|
$student['cert_number'] = $certNumber;
|
||||||
$student['verify_token'] = $verifyToken;
|
$student['verify_token'] = $verifyToken;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
unset($student);
|
unset($student);
|
||||||
|
|
||||||
$pdfData = $this->buildPdf($students, $certDate);
|
$pdfData = $this->buildPdf($students, $certDate);
|
||||||
@@ -376,9 +426,11 @@ class CertificateController extends BaseController
|
|||||||
if (preg_match('#^(\d{2})/(\d{2})/(\d{4})$#', $certDate, $m)) {
|
if (preg_match('#^(\d{2})/(\d{2})/(\d{4})$#', $certDate, $m)) {
|
||||||
return $m[3] . '-' . $m[1] . '-' . $m[2];
|
return $m[3] . '-' . $m[1] . '-' . $m[2];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (preg_match('#^\d{4}-\d{2}-\d{2}$#', $certDate)) {
|
if (preg_match('#^\d{4}-\d{2}-\d{2}$#', $certDate)) {
|
||||||
return $certDate;
|
return $certDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -387,17 +439,20 @@ class CertificateController extends BaseController
|
|||||||
$clean = trim($raw);
|
$clean = trim($raw);
|
||||||
$lower = strtolower($clean);
|
$lower = strtolower($clean);
|
||||||
|
|
||||||
// Strip section suffix: "Grade 1-A" → "Grade 1", "Grade 2-B" → "Grade 2"
|
// Strip section suffix: "Grade 1-A" → "Grade 1", "Grade 2-B" → "Grade 2".
|
||||||
if (preg_match('/^grade\s*(\d+)/i', $clean, $m)) {
|
if (preg_match('/^grade\s*(\d+)/i', $clean, $m)) {
|
||||||
return 'Grade ' . (int)$m[1];
|
return 'Grade ' . (int)$m[1];
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($lower === 'youth') {
|
if ($lower === 'youth') {
|
||||||
return 'Youth';
|
return 'Youth';
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($lower === 'kg' || $lower === 'kindergarten') {
|
if ($lower === 'kg' || $lower === 'kindergarten') {
|
||||||
return 'Kindergarten';
|
return 'Kindergarten';
|
||||||
}
|
}
|
||||||
// Raw number or number-section (e.g. "1", "1-A", "2-B") → keep number only
|
|
||||||
|
// Raw number or number-section: "1", "1-A", "2-B" → keep number only.
|
||||||
if (preg_match('/^(\d+)([- ][A-Za-z0-9]+)?$/', $clean, $m)) {
|
if (preg_match('/^(\d+)([- ][A-Za-z0-9]+)?$/', $clean, $m)) {
|
||||||
return 'Grade ' . (int)$m[1];
|
return 'Grade ' . (int)$m[1];
|
||||||
}
|
}
|
||||||
@@ -408,17 +463,22 @@ class CertificateController extends BaseController
|
|||||||
private function ensureVerificationTokenForRecord(array $record): string
|
private function ensureVerificationTokenForRecord(array $record): string
|
||||||
{
|
{
|
||||||
$token = trim((string)($record['verification_token'] ?? ''));
|
$token = trim((string)($record['verification_token'] ?? ''));
|
||||||
|
|
||||||
if ($token !== '') {
|
if ($token !== '') {
|
||||||
return $token;
|
return $token;
|
||||||
}
|
}
|
||||||
|
|
||||||
$recordId = (int)($record['id'] ?? 0);
|
$recordId = (int)($record['id'] ?? 0);
|
||||||
|
|
||||||
if ($recordId <= 0) {
|
if ($recordId <= 0) {
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
$token = $this->certRecordModel->generateVerificationToken();
|
$token = $this->certRecordModel->generateVerificationToken();
|
||||||
$this->certRecordModel->update($recordId, ['verification_token' => $token]);
|
|
||||||
|
$this->certRecordModel->update($recordId, [
|
||||||
|
'verification_token' => $token,
|
||||||
|
]);
|
||||||
|
|
||||||
return $token;
|
return $token;
|
||||||
}
|
}
|
||||||
@@ -431,10 +491,11 @@ class CertificateController extends BaseController
|
|||||||
$imgDir = FCPATH . 'assets' . DIRECTORY_SEPARATOR . 'certificates' . DIRECTORY_SEPARATOR . 'images' . 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);
|
$edwardianFont = \TCPDF_FONTS::addTTFfont($fontDir . 'Edwardian Script ITC Regular.ttf', 'TrueTypeUnicode', '', 32);
|
||||||
$garamondBold = \TCPDF_FONTS::addTTFfont($fontDir . 'Garamond Bold.ttf', 'TrueTypeUnicode', '', 32);
|
$garamondBold = \TCPDF_FONTS::addTTFfont($fontDir . 'Garamond Bold.ttf', 'TrueTypeUnicode', '', 32);
|
||||||
$ebGaramond = \TCPDF_FONTS::addTTFfont($fontDir . 'EBGaramond-Regular.ttf', 'TrueTypeUnicode', '', 32);
|
$ebGaramond = \TCPDF_FONTS::addTTFfont($fontDir . 'EBGaramond-Regular.ttf', 'TrueTypeUnicode', '', 32);
|
||||||
|
|
||||||
$pdf = new \TCPDF('L', 'pt', 'A4', true, 'UTF-8', false);
|
$pdf = new \TCPDF('L', 'pt', 'A4', true, 'UTF-8', false);
|
||||||
|
|
||||||
$pdf->SetCreator('Al Rahma Sunday School');
|
$pdf->SetCreator('Al Rahma Sunday School');
|
||||||
$pdf->SetTitle('Student Certificates');
|
$pdf->SetTitle('Student Certificates');
|
||||||
$pdf->SetMargins(0, 0, 0, true);
|
$pdf->SetMargins(0, 0, 0, true);
|
||||||
@@ -450,9 +511,9 @@ class CertificateController extends BaseController
|
|||||||
foreach ($students as $student) {
|
foreach ($students as $student) {
|
||||||
$pdf->AddPage();
|
$pdf->AddPage();
|
||||||
|
|
||||||
$name = $student['firstname'] . ' ' . $student['lastname'];
|
$name = trim((string)($student['firstname'] ?? '') . ' ' . (string)($student['lastname'] ?? ''));
|
||||||
$grade = $this->formatGrade($student['grade'] ?? '');
|
$grade = $this->formatGrade($student['grade'] ?? '');
|
||||||
$certNumber = $student['cert_number'] ?? '';
|
$certNumber = $student['cert_number'] ?? '';
|
||||||
$verifyToken = $student['verify_token'] ?? '';
|
$verifyToken = $student['verify_token'] ?? '';
|
||||||
|
|
||||||
$verifyUrl = $verifyToken !== ''
|
$verifyUrl = $verifyToken !== ''
|
||||||
@@ -460,10 +521,18 @@ class CertificateController extends BaseController
|
|||||||
: null;
|
: null;
|
||||||
|
|
||||||
$this->drawCertificate(
|
$this->drawCertificate(
|
||||||
$pdf, $W, $H,
|
$pdf,
|
||||||
$name, $grade, $certDate, $certNumber,
|
$W,
|
||||||
|
$H,
|
||||||
|
$name,
|
||||||
|
$grade,
|
||||||
|
$certDate,
|
||||||
|
$certNumber,
|
||||||
$verifyUrl,
|
$verifyUrl,
|
||||||
$imgDir, $edwardianFont, $garamondBold, $ebGaramond
|
$imgDir,
|
||||||
|
$edwardianFont,
|
||||||
|
$garamondBold,
|
||||||
|
$ebGaramond
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -476,8 +545,8 @@ class CertificateController extends BaseController
|
|||||||
*/
|
*/
|
||||||
private function drawCertificate(
|
private function drawCertificate(
|
||||||
\TCPDF $pdf,
|
\TCPDF $pdf,
|
||||||
float $W,
|
float $W,
|
||||||
float $H,
|
float $H,
|
||||||
string $name,
|
string $name,
|
||||||
string $grade,
|
string $grade,
|
||||||
string $certDate,
|
string $certDate,
|
||||||
@@ -489,9 +558,9 @@ class CertificateController extends BaseController
|
|||||||
string $ebGaramond
|
string $ebGaramond
|
||||||
): void {
|
): void {
|
||||||
// ── Images
|
// ── Images
|
||||||
$pdf->Image($imgDir . 'title.png', 126, 0, 600);
|
$pdf->Image($imgDir . 'title.png', 126, 0, 600);
|
||||||
$pdf->Image($imgDir . 'background.png', 280, 176, 291, 340);
|
$pdf->Image($imgDir . 'background.png', 280, 176, 291, 340);
|
||||||
$pdf->Image($imgDir . 'signature.png', 140, 410, 90, 80);
|
$pdf->Image($imgDir . 'signature.png', 140, 410, 90, 80);
|
||||||
|
|
||||||
// ── "Presented to:"
|
// ── "Presented to:"
|
||||||
$pdf->SetFont('times', 'B', 24);
|
$pdf->SetFont('times', 'B', 24);
|
||||||
@@ -499,21 +568,24 @@ class CertificateController extends BaseController
|
|||||||
$pdf->SetXY(0, 151);
|
$pdf->SetXY(0, 151);
|
||||||
$pdf->Cell($W, 24, 'Presented to:', 0, 0, 'C');
|
$pdf->Cell($W, 24, 'Presented to:', 0, 0, 'C');
|
||||||
|
|
||||||
// ── QR code — left-aligned with "Presented to:", vertically centred on that line
|
// ── QR code — left-aligned with "Presented to:", vertically centred on that line.
|
||||||
$qrSize = 42; // pt
|
$qrSize = 42;
|
||||||
|
|
||||||
if (!empty($verifyUrl)) {
|
if (!empty($verifyUrl)) {
|
||||||
$qrX = 120; // ~1 cm from left edge
|
$qrX = 120;
|
||||||
$qrY = 171 + (24 - $qrSize) / 2; // vertically centred on "Presented to:" row
|
$qrY = 171 + (24 - $qrSize) / 2;
|
||||||
|
|
||||||
$style = [
|
$style = [
|
||||||
'border' => false,
|
'border' => false,
|
||||||
'padding' => 0,
|
'padding' => 0,
|
||||||
'fgcolor' => [0, 0, 0],
|
'fgcolor' => [0, 0, 0],
|
||||||
'bgcolor' => false,
|
'bgcolor' => false,
|
||||||
];
|
];
|
||||||
|
|
||||||
$pdf->write2DBarcode($verifyUrl, 'QRCODE,L', $qrX, $qrY, $qrSize, $qrSize, $style, 'N');
|
$pdf->write2DBarcode($verifyUrl, 'QRCODE,L', $qrX, $qrY, $qrSize, $qrSize, $style, 'N');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Student name — center based on actual string width
|
// ── Student name — center based on actual string width.
|
||||||
$pdf->SetFont($edwardianFont, '', 38);
|
$pdf->SetFont($edwardianFont, '', 38);
|
||||||
$nameX = ($W - $pdf->GetStringWidth($name)) / 2;
|
$nameX = ($W - $pdf->GetStringWidth($name)) / 2;
|
||||||
$this->drawGradientText($pdf, $edwardianFont, 38, $name, $nameX, 221.5);
|
$this->drawGradientText($pdf, $edwardianFont, 38, $name, $nameX, 221.5);
|
||||||
@@ -543,7 +615,7 @@ class CertificateController extends BaseController
|
|||||||
$pdf->SetXY(0, 375);
|
$pdf->SetXY(0, 375);
|
||||||
$pdf->Cell($W, 20, 'Al Rahma Sunday School', 0, 0, 'C');
|
$pdf->Cell($W, 20, 'Al Rahma Sunday School', 0, 0, 'C');
|
||||||
|
|
||||||
// ── Date (gradient script)
|
// ── Date
|
||||||
$this->drawGradientText($pdf, $edwardianFont, 26, $certDate, 586, 456);
|
$this->drawGradientText($pdf, $edwardianFont, 26, $certDate, 586, 456);
|
||||||
|
|
||||||
// ── Date underline + label
|
// ── Date underline + label
|
||||||
@@ -559,7 +631,7 @@ class CertificateController extends BaseController
|
|||||||
$pdf->SetXY(106, 492);
|
$pdf->SetXY(106, 492);
|
||||||
$pdf->Cell(168, 20, 'Signature', 0, 0, 'C');
|
$pdf->Cell(168, 20, 'Signature', 0, 0, 'C');
|
||||||
|
|
||||||
// ── Certificate number — 1.4 cm from bottom, 2.5 cm from left
|
// ── Certificate number — 1.4 cm from bottom, 2.5 cm from left.
|
||||||
if ($certNumber !== '') {
|
if ($certNumber !== '') {
|
||||||
$pdf->SetFont('helvetica', '', 8);
|
$pdf->SetFont('helvetica', '', 8);
|
||||||
$pdf->SetTextColor(150, 150, 150);
|
$pdf->SetTextColor(150, 150, 150);
|
||||||
@@ -569,8 +641,14 @@ class CertificateController extends BaseController
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private function drawGradientText(\TCPDF $pdf, string $fontName, float $fontSize, string $text, float $x, float $y): void
|
private function drawGradientText(
|
||||||
{
|
\TCPDF $pdf,
|
||||||
|
string $fontName,
|
||||||
|
float $fontSize,
|
||||||
|
string $text,
|
||||||
|
float $x,
|
||||||
|
float $y
|
||||||
|
): void {
|
||||||
$pdf->SetFont($fontName, '', $fontSize);
|
$pdf->SetFont($fontName, '', $fontSize);
|
||||||
|
|
||||||
for ($i = 0; $i < 6; $i++) {
|
for ($i = 0; $i < 6; $i++) {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace App\Controllers\View;
|
namespace App\Controllers\View;
|
||||||
use App\Controllers\BaseController;
|
use App\Controllers\BaseController;
|
||||||
|
use App\Libraries\InvoiceLedgerService;
|
||||||
use App\Models\DiscountVoucherModel;
|
use App\Models\DiscountVoucherModel;
|
||||||
use App\Models\DiscountUsageModel;
|
use App\Models\DiscountUsageModel;
|
||||||
use App\Models\InvoiceModel;
|
use App\Models\InvoiceModel;
|
||||||
@@ -28,6 +29,7 @@ class DiscountController extends BaseController
|
|||||||
protected $eventChargesModel;
|
protected $eventChargesModel;
|
||||||
protected $additionalChargeModel;
|
protected $additionalChargeModel;
|
||||||
protected $classSectionModel;
|
protected $classSectionModel;
|
||||||
|
protected $invoiceLedgerService;
|
||||||
|
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
@@ -41,6 +43,7 @@ class DiscountController extends BaseController
|
|||||||
$this->eventChargesModel = new EventChargesModel();
|
$this->eventChargesModel = new EventChargesModel();
|
||||||
$this->additionalChargeModel = new AdditionalChargeModel();
|
$this->additionalChargeModel = new AdditionalChargeModel();
|
||||||
$this->classSectionModel = new ClassSectionModel();
|
$this->classSectionModel = new ClassSectionModel();
|
||||||
|
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||||
|
|
||||||
$this->schoolYear = $this->configModel->getConfig('school_year');
|
$this->schoolYear = $this->configModel->getConfig('school_year');
|
||||||
$this->semester = $this->configModel->getConfig('semester');
|
$this->semester = $this->configModel->getConfig('semester');
|
||||||
@@ -121,6 +124,8 @@ class DiscountController extends BaseController
|
|||||||
foreach ($invoices as $invoice) {
|
foreach ($invoices as $invoice) {
|
||||||
if ($remainingUses <= 0) break 2; // out of parentIds loop too
|
if ($remainingUses <= 0) break 2; // out of parentIds loop too
|
||||||
|
|
||||||
|
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $invoice['id']]);
|
||||||
|
|
||||||
// Snapshot current balance BEFORE applying
|
// Snapshot current balance BEFORE applying
|
||||||
$initialPreBalance = (float) $this->getCurrentInvoiceBalance($invoice['id'], $this->schoolYear);
|
$initialPreBalance = (float) $this->getCurrentInvoiceBalance($invoice['id'], $this->schoolYear);
|
||||||
if ($initialPreBalance <= 0) {
|
if ($initialPreBalance <= 0) {
|
||||||
@@ -201,22 +206,9 @@ class DiscountController extends BaseController
|
|||||||
'updated_at' => $now,
|
'updated_at' => $now,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Update invoice balance based on pre-discount snapshot (supports multiple discounts)
|
$ledger = $this->invoiceLedgerService->recalculateInvoice((int) $invoice['id']);
|
||||||
$newBalance = max(0.0, round($initialPreBalance - $discount, 2));
|
$postBalance = (float) ($ledger['balance'] ?? 0.0);
|
||||||
$this->db->table('invoices')
|
$currentBalance = $postBalance;
|
||||||
->where('id', $invoice['id'])
|
|
||||||
->update([
|
|
||||||
'balance' => $newBalance,
|
|
||||||
'has_discount' => 1,
|
|
||||||
'updated_at' => $now,
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Compute post-balance based on pre-snapshot (more stable than $invoice['balance'])
|
|
||||||
$postBalance = round($initialPreBalance - $discount, 2);
|
|
||||||
if ($postBalance < 0) $postBalance = 0.0;
|
|
||||||
|
|
||||||
// (Optional) current balance re-check (in case of concurrent writes)
|
|
||||||
$currentBalance = (float) $this->getCurrentInvoiceBalance($invoice['id'], $this->schoolYear);
|
|
||||||
|
|
||||||
// Increment voucher usage
|
// Increment voucher usage
|
||||||
$this->db->table('discount_vouchers')
|
$this->db->table('discount_vouchers')
|
||||||
@@ -596,53 +588,11 @@ class DiscountController extends BaseController
|
|||||||
*/
|
*/
|
||||||
private function getCurrentInvoiceBalance($invoiceId, $schoolYear)
|
private function getCurrentInvoiceBalance($invoiceId, $schoolYear)
|
||||||
{
|
{
|
||||||
$invoice = $this->invoiceModel->find($invoiceId);
|
try {
|
||||||
if (!$invoice) return 0.0;
|
return (float) ($this->invoiceLedgerService->calculateInvoice((int) $invoiceId)['balance'] ?? 0.0);
|
||||||
|
} catch (\Throwable $e) {
|
||||||
// Payments (exclude void/refund/failed, honor year)
|
return 0.0;
|
||||||
$qb = $this->paymentModel
|
|
||||||
->select('COALESCE(SUM(paid_amount),0) AS total_paid')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->where('school_year', $schoolYear);
|
|
||||||
|
|
||||||
$table = $this->paymentModel->table;
|
|
||||||
$hasStatus = $this->db->fieldExists('status', $table);
|
|
||||||
$hasVoid = $this->db->fieldExists('is_void', $table);
|
|
||||||
if ($hasStatus) {
|
|
||||||
$qb->groupStart()
|
|
||||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
|
||||||
->orWhere('status IS NULL', null, false)
|
|
||||||
->groupEnd();
|
|
||||||
}
|
}
|
||||||
if ($hasVoid) {
|
|
||||||
$qb->groupStart()
|
|
||||||
->where('is_void', 0)
|
|
||||||
->orWhere('is_void IS NULL', null, false)
|
|
||||||
->groupEnd();
|
|
||||||
}
|
|
||||||
$rowPaid = $qb->first();
|
|
||||||
$totalPaid = (float)($rowPaid['total_paid'] ?? 0);
|
|
||||||
|
|
||||||
// Discounts for this invoice in this year
|
|
||||||
$rowDisc = $this->db->table('discount_usages du')
|
|
||||||
->select('COALESCE(SUM(du.discount_amount),0) AS total_disc')
|
|
||||||
->join('invoices i', 'i.id = du.invoice_id')
|
|
||||||
->where('du.invoice_id', $invoiceId)
|
|
||||||
->where('i.school_year', $schoolYear)
|
|
||||||
->get()->getRowArray();
|
|
||||||
$totalDisc = (float)($rowDisc['total_disc'] ?? 0);
|
|
||||||
|
|
||||||
// Refunds PAID for this invoice in this year
|
|
||||||
$rowRefund = $this->db->table('refunds')
|
|
||||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->where('school_year', $schoolYear)
|
|
||||||
->whereIn('status', ['Partial', 'Paid'])
|
|
||||||
->get()->getRowArray();
|
|
||||||
$totalRefundPaid = (float)($rowRefund['total_refund_paid'] ?? 0);
|
|
||||||
|
|
||||||
$total = (float)($invoice['total_amount'] ?? 0);
|
|
||||||
return max(0.0, round($total - $totalPaid - $totalDisc - $totalRefundPaid, 2));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -650,169 +600,7 @@ class DiscountController extends BaseController
|
|||||||
*/
|
*/
|
||||||
private function recalculateInvoice($invoiceId, $schoolYear): void
|
private function recalculateInvoice($invoiceId, $schoolYear): void
|
||||||
{
|
{
|
||||||
$invoice = $this->invoiceModel->find($invoiceId);
|
$this->invoiceLedgerService->recalculateInvoice((int) $invoiceId);
|
||||||
if (!$invoice) return;
|
|
||||||
|
|
||||||
$parentId = (int)($invoice['parent_id'] ?? 0);
|
|
||||||
if ($parentId <= 0) return;
|
|
||||||
|
|
||||||
// ---- Tuition (recompute from enrollments) ----
|
|
||||||
$enrollments = $this->enrollmentModel
|
|
||||||
->where('parent_id', $parentId)
|
|
||||||
->where('school_year', $schoolYear)
|
|
||||||
->findAll();
|
|
||||||
|
|
||||||
$registered = [];
|
|
||||||
$withdrawn = [];
|
|
||||||
foreach ($enrollments as $e) {
|
|
||||||
$row = [
|
|
||||||
'student_id' => (int)($e['student_id'] ?? 0),
|
|
||||||
'class_section_id' => $e['class_section_id'] ?? null,
|
|
||||||
'enrollment_status'=> (string)($e['enrollment_status'] ?? ''),
|
|
||||||
];
|
|
||||||
if (in_array($row['enrollment_status'], ['enrolled','payment pending'], true)) {
|
|
||||||
$registered[] = $row;
|
|
||||||
} elseif (in_array($row['enrollment_status'], ['withdrawn','refund pending','withdraw under review'], true)) {
|
|
||||||
$withdrawn[] = $row;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Refund window check – if after deadline, withdrawn still billed
|
|
||||||
$refundDeadline = (string)($this->configModel->getConfig('refund_deadline') ?? '');
|
|
||||||
$refundAllowed = true;
|
|
||||||
try {
|
|
||||||
$tzName = (string) (config('School')->attendance['timezone'] ?? user_timezone());
|
|
||||||
$tz = new \DateTimeZone($tzName);
|
|
||||||
$today = new \DateTimeImmutable('today', $tz);
|
|
||||||
$deadline = new \DateTimeImmutable($refundDeadline, $tz);
|
|
||||||
$refundAllowed = $today <= $deadline;
|
|
||||||
} catch (\Throwable $e) {
|
|
||||||
$refundAllowed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
$tuitionStudents = $registered;
|
|
||||||
if (!$refundAllowed) {
|
|
||||||
$tuitionStudents = array_merge($tuitionStudents, $withdrawn);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Grade threshold and fees
|
|
||||||
$gradeFee = (int)($this->configModel->getConfig('grade_fee') ?? 9);
|
|
||||||
$firstStudentFee = (float)($this->configModel->getConfig('first_student_fee') ?? 350);
|
|
||||||
$secondStudentFee = (float)($this->configModel->getConfig('second_student_fee') ?? 200);
|
|
||||||
$youthFee = (float)($this->configModel->getConfig('youth_fee') ?? 180);
|
|
||||||
|
|
||||||
// Normalize grades for tuition students
|
|
||||||
foreach ($tuitionStudents as &$s) {
|
|
||||||
$name = null;
|
|
||||||
if (!empty($s['class_section_id'])) {
|
|
||||||
$name = $this->classSectionModel->getClassSectionNameBySectionId($s['class_section_id']);
|
|
||||||
}
|
|
||||||
$s['grade_name'] = is_string($name) ? strtoupper(trim($name)) : 'N/A';
|
|
||||||
}
|
|
||||||
unset($s);
|
|
||||||
|
|
||||||
// Count regular vs youth and compute tuition
|
|
||||||
$regularCount = 0;
|
|
||||||
$youthCount = 0;
|
|
||||||
foreach ($tuitionStudents as $s) {
|
|
||||||
$lvl = $this->parseGradeLevel($s['grade_name']);
|
|
||||||
if ($lvl > $gradeFee) $youthCount++; else $regularCount++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$tuitionSubtotal = 0.0;
|
|
||||||
$tuitionSubtotal += $youthCount * $youthFee;
|
|
||||||
if ($regularCount >= 2) {
|
|
||||||
$tuitionSubtotal += $firstStudentFee + ($regularCount - 1) * $secondStudentFee;
|
|
||||||
} elseif ($regularCount === 1) {
|
|
||||||
$tuitionSubtotal += $firstStudentFee;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Event charges (parent-year) ----
|
|
||||||
$eventSubtotal = 0.0;
|
|
||||||
try {
|
|
||||||
$events = $this->eventChargesModel->getChargesWithEventInfo($parentId, $schoolYear) ?? [];
|
|
||||||
foreach ($events as $ev) { $eventSubtotal += (float)($ev['charged'] ?? 0.0); }
|
|
||||||
} catch (\Throwable $e) {}
|
|
||||||
|
|
||||||
// ---- Additional charges (per-invoice) ----
|
|
||||||
$additionalSubtotal = 0.0;
|
|
||||||
try {
|
|
||||||
$rows = $this->additionalChargeModel
|
|
||||||
->select('charge_type, amount')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->where('status', 'applied')
|
|
||||||
->findAll();
|
|
||||||
foreach ($rows as $r) {
|
|
||||||
$amt = (float)($r['amount'] ?? 0);
|
|
||||||
$typ = strtolower((string)($r['charge_type'] ?? 'add'));
|
|
||||||
if ($typ === 'deduct') $amt = -abs($amt); else $amt = abs($amt);
|
|
||||||
$additionalSubtotal += $amt;
|
|
||||||
}
|
|
||||||
} catch (\Throwable $e) {}
|
|
||||||
|
|
||||||
$discountableTotal = $tuitionSubtotal + $additionalSubtotal;
|
|
||||||
$nonDiscountableTotal = $eventSubtotal;
|
|
||||||
$newTotal = round($discountableTotal + $nonDiscountableTotal, 2);
|
|
||||||
|
|
||||||
// ---- Payments / Discounts / Refunds ----
|
|
||||||
$db = $this->db;
|
|
||||||
$table = $this->paymentModel->table;
|
|
||||||
$hasStatus = $db->fieldExists('status', $table);
|
|
||||||
$hasVoid = $db->fieldExists('is_void', $table);
|
|
||||||
$exclude = ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'];
|
|
||||||
|
|
||||||
$qb = $this->paymentModel
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->where('school_year', $schoolYear);
|
|
||||||
|
|
||||||
if ($hasStatus) {
|
|
||||||
$qb->groupStart()
|
|
||||||
->whereNotIn('status', $exclude)
|
|
||||||
->orWhere('status IS NULL', null, false)
|
|
||||||
->groupEnd();
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($hasVoid) {
|
|
||||||
$qb->groupStart()
|
|
||||||
->where('is_void', 0)
|
|
||||||
->orWhere('is_void IS NULL', null, false)
|
|
||||||
->groupEnd();
|
|
||||||
}
|
|
||||||
|
|
||||||
$payments = $qb->findAll();
|
|
||||||
$totalPaid = 0.0;
|
|
||||||
foreach ($payments as $p) { $totalPaid += (float)($p['paid_amount'] ?? 0); }
|
|
||||||
|
|
||||||
$discRow = $this->db->table('discount_usages')
|
|
||||||
->select('COALESCE(SUM(discount_amount),0) AS total_disc')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->get()->getRowArray();
|
|
||||||
$totalDisc = (float)($discRow['total_disc'] ?? 0);
|
|
||||||
|
|
||||||
$refundRow = $this->db->table('refunds')
|
|
||||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->whereIn('status', ['Partial','Paid'])
|
|
||||||
->get()->getRowArray();
|
|
||||||
$totalRefundPaid = (float)($refundRow['total_refund_paid'] ?? 0);
|
|
||||||
|
|
||||||
$appliedDiscount = min($totalDisc, $discountableTotal);
|
|
||||||
$newBalance = max(0.0, $newTotal - $appliedDiscount - $totalPaid - $totalRefundPaid);
|
|
||||||
$newStatus = ($newBalance <= 0.00001) ? 'Paid' : (($totalPaid > 0) ? 'Partially Paid' : 'Unpaid');
|
|
||||||
|
|
||||||
$updateData = [
|
|
||||||
'total_amount' => $newTotal,
|
|
||||||
'paid_amount' => $totalPaid,
|
|
||||||
'balance' => $newBalance,
|
|
||||||
'status' => $newStatus,
|
|
||||||
'has_discount' => ($totalDisc > 0.0) ? 1 : 0,
|
|
||||||
];
|
|
||||||
|
|
||||||
if ($this->db->fieldExists('discount', $this->invoiceModel->table)) {
|
|
||||||
$updateData['discount'] = $totalDisc;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->invoiceModel->update($invoiceId, $updateData);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
namespace App\Controllers\View;
|
namespace App\Controllers\View;
|
||||||
|
|
||||||
use App\Controllers\BaseController;
|
use App\Controllers\BaseController;
|
||||||
|
use App\Libraries\FinancialStatus;
|
||||||
|
use App\Libraries\InvoiceLedgerService;
|
||||||
use App\Models\AdditionalChargeModel;
|
use App\Models\AdditionalChargeModel;
|
||||||
use CodeIgniter\Controller;
|
use CodeIgniter\Controller;
|
||||||
use App\Models\UserModel;
|
use App\Models\UserModel;
|
||||||
@@ -28,6 +30,7 @@ class ExtraChargesController extends BaseController
|
|||||||
protected $studentClassModel;
|
protected $studentClassModel;
|
||||||
protected $enableAttendance;
|
protected $enableAttendance;
|
||||||
protected $attendanceDayModel;
|
protected $attendanceDayModel;
|
||||||
|
protected $invoiceLedgerService;
|
||||||
|
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
@@ -39,6 +42,7 @@ class ExtraChargesController extends BaseController
|
|||||||
$this->invoiceModel = new InvoiceModel();
|
$this->invoiceModel = new InvoiceModel();
|
||||||
$this->semester = $this->configModel->getConfig('semester');
|
$this->semester = $this->configModel->getConfig('semester');
|
||||||
$this->schoolYear = $this->configModel->getConfig('school_year');
|
$this->schoolYear = $this->configModel->getConfig('school_year');
|
||||||
|
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function index()
|
public function index()
|
||||||
@@ -247,13 +251,9 @@ class ExtraChargesController extends BaseController
|
|||||||
// keep status as-is
|
// keep status as-is
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// If it’s already applied on an invoice and the amount changed, reflect the delta
|
if (($row['status'] ?? '') === FinancialStatus::ADDITIONAL_CHARGE_APPLIED && !empty($row['invoice_id'])) {
|
||||||
if ($row['status'] === 'applied' && !empty($row['invoice_id']) && abs($delta) > 0.00001) {
|
$db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $row['invoice_id']]);
|
||||||
if ($delta > 0) {
|
$this->invoiceLedgerService->recalculateInvoice((int) $row['invoice_id']);
|
||||||
$this->invoiceModel->applyAdditionalCharge((int)$row['invoice_id'], $delta);
|
|
||||||
} else {
|
|
||||||
$this->invoiceModel->reverseAdditionalCharge((int)$row['invoice_id'], -$delta);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$db->transComplete();
|
$db->transComplete();
|
||||||
@@ -343,7 +343,7 @@ class ExtraChargesController extends BaseController
|
|||||||
'description' => trim($data['description'] ?? ''),
|
'description' => trim($data['description'] ?? ''),
|
||||||
'amount' => $signedAmount,
|
'amount' => $signedAmount,
|
||||||
'due_date' => !empty($data['due_date']) ? $data['due_date'] : null,
|
'due_date' => !empty($data['due_date']) ? $data['due_date'] : null,
|
||||||
'status' => $invoiceId ? 'applied' : 'pending',
|
'status' => $invoiceId ? FinancialStatus::ADDITIONAL_CHARGE_APPLIED : FinancialStatus::ADDITIONAL_CHARGE_PENDING,
|
||||||
'created_by' => (int)(session()->get('user_id') ?? 0),
|
'created_by' => (int)(session()->get('user_id') ?? 0),
|
||||||
'created_at' => \CodeIgniter\I18n\Time::now('UTC')->toDateTimeString(), // store UTC
|
'created_at' => \CodeIgniter\I18n\Time::now('UTC')->toDateTimeString(), // store UTC
|
||||||
];
|
];
|
||||||
@@ -357,17 +357,9 @@ class ExtraChargesController extends BaseController
|
|||||||
$this->additionalChargeModel->insert($payload);
|
$this->additionalChargeModel->insert($payload);
|
||||||
$chargeId = (int)$this->additionalChargeModel->getInsertID();
|
$chargeId = (int)$this->additionalChargeModel->getInsertID();
|
||||||
|
|
||||||
// Apply to invoice if present
|
|
||||||
if ($invoiceId) {
|
if ($invoiceId) {
|
||||||
try {
|
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$invoiceId]);
|
||||||
if ($chargeType === 'add') {
|
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||||
$this->invoiceModel->applyAdditionalCharge($invoiceId, $amountAbs);
|
|
||||||
} else {
|
|
||||||
$this->invoiceModel->deductAdditionalCharge($invoiceId, $amountAbs);
|
|
||||||
}
|
|
||||||
} catch (\Throwable $e) {
|
|
||||||
log_message('error', 'apply/deductAdditionalCharge failed: ' . $e->getMessage());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AFTER
|
// AFTER
|
||||||
@@ -470,23 +462,15 @@ class ExtraChargesController extends BaseController
|
|||||||
|
|
||||||
$this->db->transStart();
|
$this->db->transStart();
|
||||||
|
|
||||||
if ($status === 'applied' && $invoiceId > 0 && $amountAbs > 0) {
|
|
||||||
try {
|
|
||||||
if ($chargeType === 'add') {
|
|
||||||
$this->invoiceModel->reverseAdditionalCharge($invoiceId, $amountAbs);
|
|
||||||
} else {
|
|
||||||
// voiding a deduction -> add back
|
|
||||||
$this->invoiceModel->applyAdditionalCharge($invoiceId, $amountAbs);
|
|
||||||
}
|
|
||||||
} catch (\Throwable $e) {
|
|
||||||
log_message('error', 'void(): invoice adjust failed: ' . $e->getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->additionalChargeModel->update((int)$id, [
|
$this->additionalChargeModel->update((int)$id, [
|
||||||
'status' => 'void',
|
'status' => FinancialStatus::ADDITIONAL_CHARGE_VOIDED,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
if ($status === FinancialStatus::ADDITIONAL_CHARGE_APPLIED && $invoiceId > 0) {
|
||||||
|
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$invoiceId]);
|
||||||
|
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||||
|
}
|
||||||
|
|
||||||
$this->db->transComplete();
|
$this->db->transComplete();
|
||||||
|
|
||||||
if (!$this->db->transStatus()) {
|
if (!$this->db->transStatus()) {
|
||||||
@@ -514,26 +498,19 @@ class ExtraChargesController extends BaseController
|
|||||||
$chargeType = (string)($row['charge_type'] ?? 'add');
|
$chargeType = (string)($row['charge_type'] ?? 'add');
|
||||||
$status = (string)($row['status'] ?? 'pending');
|
$status = (string)($row['status'] ?? 'pending');
|
||||||
|
|
||||||
if ($status !== 'applied' || $invoiceId <= 0 || $amountAbs <= 0) {
|
if ($status !== FinancialStatus::ADDITIONAL_CHARGE_APPLIED || $invoiceId <= 0 || $amountAbs <= 0) {
|
||||||
if ($this->wantsJson()) return $this->response->setJSON(['ok' => false, 'error' => 'Nothing to reverse']);
|
if ($this->wantsJson()) return $this->response->setJSON(['ok' => false, 'error' => 'Nothing to reverse']);
|
||||||
return redirect()->back()->with('error', 'Nothing to reverse.');
|
return redirect()->back()->with('error', 'Nothing to reverse.');
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->db->transStart();
|
$this->db->transStart();
|
||||||
try {
|
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$invoiceId]);
|
||||||
if ($chargeType === 'add') {
|
|
||||||
$this->invoiceModel->reverseAdditionalCharge($invoiceId, $amountAbs);
|
|
||||||
} else {
|
|
||||||
$this->invoiceModel->applyAdditionalCharge($invoiceId, $amountAbs);
|
|
||||||
}
|
|
||||||
} catch (\Throwable $e) {
|
|
||||||
log_message('error', 'reverse(): invoice adjust failed: ' . $e->getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->additionalChargeModel->update((int)$id, [
|
$this->additionalChargeModel->update((int)$id, [
|
||||||
'status' => 'pending',
|
'status' => FinancialStatus::ADDITIONAL_CHARGE_PENDING,
|
||||||
'invoice_id' => null,
|
'invoice_id' => null,
|
||||||
]);
|
]);
|
||||||
|
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||||
|
|
||||||
$this->db->transComplete();
|
$this->db->transComplete();
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ namespace App\Controllers\View;
|
|||||||
|
|
||||||
use CodeIgniter\Controller;
|
use CodeIgniter\Controller;
|
||||||
use CodeIgniter\Exceptions\PageNotFoundException;
|
use CodeIgniter\Exceptions\PageNotFoundException;
|
||||||
use Config\Database;
|
|
||||||
|
|
||||||
class FilesController extends Controller
|
class FilesController extends Controller
|
||||||
{
|
{
|
||||||
@@ -22,7 +21,11 @@ class FilesController extends Controller
|
|||||||
throw PageNotFoundException::forPageNotFound();
|
throw PageNotFoundException::forPageNotFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3) Build path under writable
|
$expense = $this->expenseRecordForFile($name);
|
||||||
|
if ($expense === null || !$this->canViewExpenseFile($expense)) {
|
||||||
|
return $this->response->setStatusCode(403, 'You are not allowed to access this file.');
|
||||||
|
}
|
||||||
|
|
||||||
$path = WRITEPATH . 'uploads/receipts/' . $name;
|
$path = WRITEPATH . 'uploads/receipts/' . $name;
|
||||||
if (!is_file($path)) {
|
if (!is_file($path)) {
|
||||||
throw PageNotFoundException::forPageNotFound();
|
throw PageNotFoundException::forPageNotFound();
|
||||||
@@ -79,7 +82,11 @@ class FilesController extends Controller
|
|||||||
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
|
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3) Build path under writable (REIMBURSEMENTS)
|
$reimbursement = $this->reimbursementRecordForFile($name);
|
||||||
|
if ($reimbursement === null || !$this->canViewReimbursementFile($reimbursement)) {
|
||||||
|
return $this->response->setStatusCode(403, 'You are not allowed to access this file.');
|
||||||
|
}
|
||||||
|
|
||||||
$path = WRITEPATH . 'uploads/reimbursements/' . $name;
|
$path = WRITEPATH . 'uploads/reimbursements/' . $name;
|
||||||
if (!is_file($path)) {
|
if (!is_file($path)) {
|
||||||
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
|
throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
|
||||||
@@ -425,4 +432,69 @@ class FilesController extends Controller
|
|||||||
|
|
||||||
return $draftSemester === '' || $currentSemester === '' || $draftSemester === $currentSemester;
|
return $draftSemester === '' || $currentSemester === '' || $draftSemester === $currentSemester;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function expenseRecordForFile(string $name): ?array
|
||||||
|
{
|
||||||
|
return \Config\Database::connect()
|
||||||
|
->table('expenses')
|
||||||
|
->where('receipt_path', $name)
|
||||||
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function reimbursementRecordForFile(string $name): ?array
|
||||||
|
{
|
||||||
|
return \Config\Database::connect()
|
||||||
|
->table('reimbursements')
|
||||||
|
->where('receipt_path', $name)
|
||||||
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function canViewExpenseFile(array $expense): bool
|
||||||
|
{
|
||||||
|
if ($this->hasFinancialStaffAccess()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$userId = (int) (session()->get('user_id') ?? 0);
|
||||||
|
|
||||||
|
return $userId > 0 && in_array($userId, [
|
||||||
|
(int) ($expense['purchased_by'] ?? 0),
|
||||||
|
(int) ($expense['added_by'] ?? 0),
|
||||||
|
(int) ($expense['approved_by'] ?? 0),
|
||||||
|
], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function canViewReimbursementFile(array $reimbursement): bool
|
||||||
|
{
|
||||||
|
if ($this->hasFinancialStaffAccess()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$userId = (int) (session()->get('user_id') ?? 0);
|
||||||
|
|
||||||
|
return $userId > 0 && in_array($userId, [
|
||||||
|
(int) ($reimbursement['reimbursed_to'] ?? 0),
|
||||||
|
(int) ($reimbursement['approved_by'] ?? 0),
|
||||||
|
(int) ($reimbursement['added_by'] ?? 0),
|
||||||
|
], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function hasFinancialStaffAccess(): bool
|
||||||
|
{
|
||||||
|
$roles = array_map('strtolower', (array) (session()->get('roles') ?? []));
|
||||||
|
$activeRole = strtolower((string) (session()->get('role') ?? ''));
|
||||||
|
if ($activeRole !== '' && !in_array($activeRole, $roles, true)) {
|
||||||
|
$roles[] = $activeRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (['administrator', 'administrative staff', 'principal', 'teacher', 'teacher_assistant'] as $role) {
|
||||||
|
if (in_array($role, $roles, true)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -74,7 +74,7 @@ class InvoiceController extends ResourceController
|
|||||||
$this->dueDate = $this->configModel->getConfig('due_date');
|
$this->dueDate = $this->configModel->getConfig('due_date');
|
||||||
$this->firstStudentFee = (float) ($this->configModel->getConfig('first_student_fee') ?? 350);
|
$this->firstStudentFee = (float) ($this->configModel->getConfig('first_student_fee') ?? 350);
|
||||||
$this->secondStudentFee = (float) ($this->configModel->getConfig('second_student_fee') ?? 200);
|
$this->secondStudentFee = (float) ($this->configModel->getConfig('second_student_fee') ?? 200);
|
||||||
$this->youthFee = (float) ($this->configModel->getConfig('youth_fee') ?? 180);
|
$this->youthFee = (float) ($this->configModel->getConfig('youth_fee') ?? 200);
|
||||||
$this->refundDeadline = date('Y-m-d', strtotime($this->configModel->getConfig('refund_deadline')));
|
$this->refundDeadline = date('Y-m-d', strtotime($this->configModel->getConfig('refund_deadline')));
|
||||||
$this->db = \Config\Database::connect();
|
$this->db = \Config\Database::connect();
|
||||||
$this->request = \Config\Services::request();
|
$this->request = \Config\Services::request();
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
namespace App\Controllers\View;
|
namespace App\Controllers\View;
|
||||||
|
|
||||||
|
use App\Libraries\FinancialAttachmentService;
|
||||||
|
use App\Libraries\FinancialStatus;
|
||||||
|
use App\Libraries\InvoiceLedgerService;
|
||||||
use App\Models\PaymentModel;
|
use App\Models\PaymentModel;
|
||||||
use App\Models\AdditionalChargeModel;
|
use App\Models\AdditionalChargeModel;
|
||||||
use App\Models\ClassSectionModel;
|
use App\Models\ClassSectionModel;
|
||||||
@@ -16,23 +19,14 @@ use App\Models\PaymentErrorModel;
|
|||||||
use App\Models\InvoiceModel;
|
use App\Models\InvoiceModel;
|
||||||
use App\Models\TeacherClassModel;
|
use App\Models\TeacherClassModel;
|
||||||
use App\Models\DiscountUsageModel;
|
use App\Models\DiscountUsageModel;
|
||||||
use Config\PaypalConfig;
|
|
||||||
use PayPal\Api\Amount;
|
|
||||||
use PayPal\Api\Payment;
|
|
||||||
use PayPal\Api\PaymentExecution;
|
|
||||||
use PayPal\Api\Payer;
|
|
||||||
use PayPal\Api\Transaction;
|
|
||||||
use PayPal\Rest\ApiContext;
|
|
||||||
use PayPal\Auth\OAuthTokenCredential;
|
|
||||||
|
|
||||||
use CodeIgniter\RESTful\ResourceController;
|
use CodeIgniter\RESTful\ResourceController;
|
||||||
use CodeIgniter\Events\Events;
|
use CodeIgniter\Events\Events;
|
||||||
|
use CodeIgniter\Exceptions\PageNotFoundException;
|
||||||
|
|
||||||
class PaymentController extends ResourceController
|
class PaymentController extends ResourceController
|
||||||
{
|
{
|
||||||
protected $paymentModel;
|
protected $paymentModel;
|
||||||
protected $paypalConfig;
|
|
||||||
protected $apiContext;
|
|
||||||
protected $request;
|
protected $request;
|
||||||
protected $db;
|
protected $db;
|
||||||
protected $invoiceModel;
|
protected $invoiceModel;
|
||||||
@@ -51,6 +45,8 @@ class PaymentController extends ResourceController
|
|||||||
protected $discountUsageModel;
|
protected $discountUsageModel;
|
||||||
protected $additionalChargeModel;
|
protected $additionalChargeModel;
|
||||||
protected $classSectionModel;
|
protected $classSectionModel;
|
||||||
|
protected $invoiceLedgerService;
|
||||||
|
protected $financialAttachmentService;
|
||||||
|
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
@@ -60,7 +56,6 @@ class PaymentController extends ResourceController
|
|||||||
$this->eventChargesModel = new EventChargesModel();
|
$this->eventChargesModel = new EventChargesModel();
|
||||||
$this->manualPaymentModel = new ManualPaymentModel();
|
$this->manualPaymentModel = new ManualPaymentModel();
|
||||||
$this->paymentModel = new PaymentModel();
|
$this->paymentModel = new PaymentModel();
|
||||||
$this->paypalConfig = new PaypalConfig();
|
|
||||||
$this->request = \Config\Services::request();
|
$this->request = \Config\Services::request();
|
||||||
$this->db = \Config\Database::connect();
|
$this->db = \Config\Database::connect();
|
||||||
$this->invoiceModel = new InvoiceModel();
|
$this->invoiceModel = new InvoiceModel();
|
||||||
@@ -73,20 +68,9 @@ class PaymentController extends ResourceController
|
|||||||
$this->installmentDate = $this->configModel->getConfig('installment_date');
|
$this->installmentDate = $this->configModel->getConfig('installment_date');
|
||||||
$this->discountUsageModel = new DiscountUsageModel();
|
$this->discountUsageModel = new DiscountUsageModel();
|
||||||
$this->additionalChargeModel = new AdditionalChargeModel();
|
$this->additionalChargeModel = new AdditionalChargeModel();
|
||||||
$this->classSectionModel = new ClassSectionModel();
|
$this->classSectionModel = new ClassSectionModel();
|
||||||
|
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||||
// Set up PayPal API context
|
$this->financialAttachmentService = new FinancialAttachmentService();
|
||||||
$this->apiContext = new ApiContext(
|
|
||||||
new OAuthTokenCredential(
|
|
||||||
$this->paypalConfig->paypalClientId,
|
|
||||||
$this->paypalConfig->paypalSecret
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
$this->apiContext->setConfig([
|
|
||||||
'mode' => $this->paypalConfig->paypalMode, // 'sandbox' or 'live'
|
|
||||||
'http.headers' => ['Connection' => 'Close']
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// API: Create a new payment plan
|
// API: Create a new payment plan
|
||||||
@@ -185,135 +169,11 @@ class PaymentController extends ResourceController
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Create a PayPal payment
|
|
||||||
public function createPaypalPayment($paymentId)
|
|
||||||
{
|
|
||||||
// Fetch the payment details from the database
|
|
||||||
$payment = $this->paymentModel->find($paymentId);
|
|
||||||
|
|
||||||
// Create the payer object (who is making the payment)
|
|
||||||
$payer = new Payer();
|
|
||||||
$payer->setPaymentMethod('paypal');
|
|
||||||
|
|
||||||
// Set up the payment amount
|
|
||||||
$amount = new Amount();
|
|
||||||
$amount->setCurrency('USD')
|
|
||||||
->setTotal($payment['balance_amount']); // The balance amount to be paid
|
|
||||||
|
|
||||||
// Set up the transaction details
|
|
||||||
$transaction = new Transaction();
|
|
||||||
$transaction->setAmount($amount)
|
|
||||||
->setDescription('Payment for school fees')
|
|
||||||
->setInvoiceNumber(uniqid());
|
|
||||||
|
|
||||||
// Create the payment and set the redirect URLs
|
|
||||||
$payment = new Payment();
|
|
||||||
$payment->setIntent('sale')
|
|
||||||
->setPayer($payer)
|
|
||||||
->setTransactions([$transaction]);
|
|
||||||
|
|
||||||
// Set the approval URL for the payment
|
|
||||||
$redirectUrls = new \PayPal\Api\RedirectUrls();
|
|
||||||
$redirectUrls->setReturnUrl(base_url('payments/executePaypalPayment')) // Set this to where the user will be redirected after approval
|
|
||||||
->setCancelUrl(base_url('payments/cancelPaypalPayment'));
|
|
||||||
|
|
||||||
$payment->setRedirectUrls($redirectUrls);
|
|
||||||
|
|
||||||
// Create the payment and get the approval URL
|
|
||||||
try {
|
|
||||||
$payment->create($this->apiContext);
|
|
||||||
// Store the payment ID in the session to retrieve it later
|
|
||||||
session()->set('paypalPaymentId', $payment->getId());
|
|
||||||
session()->set('paymentId', $paymentId);
|
|
||||||
$approvalUrl = $payment->getApprovalLink();
|
|
||||||
|
|
||||||
return redirect()->to($approvalUrl); // Redirect the user to PayPal's approval page
|
|
||||||
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
|
|
||||||
// Handle errors
|
|
||||||
echo $ex->getData();
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Execute the PayPal payment after user approval
|
|
||||||
public function executePaypalPayment()
|
|
||||||
{
|
|
||||||
// Get the payment ID and Payer ID from the request
|
|
||||||
$paymentId = session()->get('paypalPaymentId');
|
|
||||||
$payerId = $this->request->getGet('PayerID');
|
|
||||||
|
|
||||||
// Get the payment object using the payment ID
|
|
||||||
$payment = Payment::get($paymentId, $this->apiContext);
|
|
||||||
|
|
||||||
// Create an execution object to execute the payment
|
|
||||||
$execution = new PaymentExecution();
|
|
||||||
$execution->setPayerId($payerId);
|
|
||||||
|
|
||||||
// Execute the payment
|
|
||||||
try {
|
|
||||||
$result = $payment->execute($execution, $this->apiContext);
|
|
||||||
|
|
||||||
// Payment successful, update the payment status in the database
|
|
||||||
$paymentId = session()->get('paymentId');
|
|
||||||
$this->paymentModel->update($paymentId, ['status' => 'Completed']);
|
|
||||||
|
|
||||||
return redirect()->to('/payments'); // Redirect to the payments page after success
|
|
||||||
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
|
|
||||||
// Handle payment execution failure
|
|
||||||
echo $ex->getData();
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cancel the PayPal payment
|
|
||||||
public function cancelPaypalPayment()
|
|
||||||
{
|
|
||||||
// Payment was canceled by the user
|
|
||||||
return redirect()->to('/payments')->with('error', 'Payment was canceled.');
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public function redirectPage()
|
public function redirectPage()
|
||||||
{
|
{
|
||||||
$modeCheck = $this->configModel->getConfig('paypal_mode');
|
return redirect()
|
||||||
|
->to(site_url('parent/invoice_payment'))
|
||||||
$parentId = session()->get('user_id'); // assuming this is the logged-in parent
|
->with('info', 'Online payment is currently unavailable. Please contact the school office to complete payment.');
|
||||||
|
|
||||||
// Get parent name and school ID
|
|
||||||
$parent = $this->db->table('users')
|
|
||||||
->select('firstname, lastname, school_id')
|
|
||||||
->where('id', $parentId)
|
|
||||||
->get()
|
|
||||||
->getRowArray();
|
|
||||||
|
|
||||||
$parentName = isset($parent['firstname'], $parent['lastname'])
|
|
||||||
? $parent['firstname'] . ' ' . $parent['lastname']
|
|
||||||
: 'Parent';
|
|
||||||
|
|
||||||
$schoolId = $parent['school_id'] ?? null;
|
|
||||||
|
|
||||||
// Get latest invoice total_amount
|
|
||||||
$latestInvoice = $this->invoiceModel->where('parent_id', $parentId)
|
|
||||||
->orderBy('created_at', 'DESC')
|
|
||||||
->select('total_amount')
|
|
||||||
->get()
|
|
||||||
->getRowArray();
|
|
||||||
|
|
||||||
$totalAmount = $latestInvoice['total_amount'] ?? 0;
|
|
||||||
|
|
||||||
return view('payment/payment_redirect', [
|
|
||||||
'parentName' => $parentName,
|
|
||||||
'totalAmount' => $totalAmount,
|
|
||||||
'schoolId' => $schoolId,
|
|
||||||
'modeCheck' => $modeCheck,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public function paypal()
|
|
||||||
{
|
|
||||||
// Redirect to PayPal API or show instructions
|
|
||||||
return redirect()->to('https://www.paypal.com/ncp/payment/87FJL3EV8C7NE');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function manual()
|
public function manual()
|
||||||
@@ -329,11 +189,7 @@ class PaymentController extends ResourceController
|
|||||||
|
|
||||||
// Handle file upload if present
|
// Handle file upload if present
|
||||||
$proof = $this->request->getFile('proof');
|
$proof = $this->request->getFile('proof');
|
||||||
if ($proof && $proof->isValid() && !$proof->hasMoved()) {
|
$data['proof_path'] = $this->financialAttachmentService->saveUploadedFile($proof, 'payments');
|
||||||
$filename = $proof->getRandomName();
|
|
||||||
$proof->move(WRITEPATH . 'uploads/payments/', $filename);
|
|
||||||
$data['proof_path'] = $filename;
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->manualPaymentModel->insert($data);
|
$this->manualPaymentModel->insert($data);
|
||||||
|
|
||||||
@@ -1057,26 +913,13 @@ class PaymentController extends ResourceController
|
|||||||
// Optional receipt upload
|
// Optional receipt upload
|
||||||
$checkFile = null;
|
$checkFile = null;
|
||||||
$paymentFile = $this->request->getFile('payment_file');
|
$paymentFile = $this->request->getFile('payment_file');
|
||||||
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) {
|
try {
|
||||||
$okTypes = ['image/jpeg', 'image/png', 'application/pdf'];
|
$checkFile = $this->financialAttachmentService->saveUploadedFile(
|
||||||
$okExts = ['jpg', 'jpeg', 'png', 'pdf'];
|
$paymentFile,
|
||||||
|
$paymentMethod === 'check' ? 'checks' : ($paymentMethod === 'card' ? 'cards' : 'misc')
|
||||||
$mime = $paymentFile->getMimeType();
|
);
|
||||||
$ext = strtolower($paymentFile->getClientExtension());
|
} catch (\RuntimeException $e) {
|
||||||
|
return redirect()->back()->withInput()->with('error', $e->getMessage());
|
||||||
if (!in_array($mime, $okTypes, true) || !in_array($ext, $okExts, true)) {
|
|
||||||
return redirect()->back()->withInput()->with('error', 'Unsupported file type. Use JPG, PNG, or PDF.');
|
|
||||||
}
|
|
||||||
if ($paymentFile->getSize() > 5 * 1024 * 1024) {
|
|
||||||
return redirect()->back()->withInput()->with('error', 'File too large. Max 5MB.');
|
|
||||||
}
|
|
||||||
|
|
||||||
$fileName = $paymentFile->getRandomName();
|
|
||||||
$subdir = ($paymentMethod === 'check') ? 'checks' : (($paymentMethod === 'card') ? 'cards' : 'misc');
|
|
||||||
$targetDir = WRITEPATH . 'uploads/' . $subdir . '/';
|
|
||||||
if (!is_dir($targetDir)) @mkdir($targetDir, 0775, true);
|
|
||||||
$paymentFile->move($targetDir, $fileName);
|
|
||||||
$checkFile = $fileName;
|
|
||||||
}
|
}
|
||||||
$this->db->transBegin();
|
$this->db->transBegin();
|
||||||
|
|
||||||
@@ -1096,10 +939,7 @@ class PaymentController extends ResourceController
|
|||||||
$invYear = (string)($row['school_year'] ?? $this->schoolYear);
|
$invYear = (string)($row['school_year'] ?? $this->schoolYear);
|
||||||
|
|
||||||
// Recompute invoice totals from tuition + events + additional charges
|
// Recompute invoice totals from tuition + events + additional charges
|
||||||
$this->recalculateInvoice($invoiceId, $invYear);
|
$currentBalance = (float) $this->invoiceLedgerService->recalculateInvoice($invoiceId)['balance'];
|
||||||
|
|
||||||
// Authoritative balance
|
|
||||||
$currentBalance = $this->getCurrentInvoiceBalance($invoiceId);
|
|
||||||
|
|
||||||
if ($amount > $currentBalance + 0.00001) {
|
if ($amount > $currentBalance + 0.00001) {
|
||||||
$this->db->transRollback();
|
$this->db->transRollback();
|
||||||
@@ -1135,7 +975,9 @@ class PaymentController extends ResourceController
|
|||||||
$this->schoolYear,
|
$this->schoolYear,
|
||||||
$this->semester,
|
$this->semester,
|
||||||
$checkNumber,
|
$checkNumber,
|
||||||
$installmentSeq
|
$installmentSeq,
|
||||||
|
(array) $this->invoiceModel->find($invoiceId),
|
||||||
|
$currentBalance
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!$ok) {
|
if (!$ok) {
|
||||||
@@ -1144,11 +986,10 @@ class PaymentController extends ResourceController
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure invoice totals/balance reflect discounts and this payment
|
// Ensure invoice totals/balance reflect discounts and this payment
|
||||||
$this->recalculateInvoice($invoiceId, $this->schoolYear);
|
$ledger = $this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||||
|
|
||||||
// Post-payment balance from snapshot
|
// Post-payment balance from snapshot
|
||||||
$postBalance = (float)round($initialPreBalance - $amount, 2);
|
$postBalance = (float) ($ledger['balance'] ?? max(0.0, round($initialPreBalance - $amount, 2)));
|
||||||
if ($postBalance < 0) $postBalance = 0.0;
|
|
||||||
|
|
||||||
// Optional enrollment update
|
// Optional enrollment update
|
||||||
$enrollmentupdated = $this->updateEnrollmentStatusIfPaid($invoiceId);
|
$enrollmentupdated = $this->updateEnrollmentStatusIfPaid($invoiceId);
|
||||||
@@ -1235,20 +1076,21 @@ class PaymentController extends ResourceController
|
|||||||
$checkFile = $payment['check_file']; // default keep old file
|
$checkFile = $payment['check_file']; // default keep old file
|
||||||
|
|
||||||
// Handle optional check or card payment receipt upload
|
// Handle optional check or card payment receipt upload
|
||||||
if (strtolower($paymentMethod) === 'check') {
|
try {
|
||||||
$paymentFile = $this->request->getFile('payment_file'); // ✅ Updated to payment_file
|
$paymentFile = $this->request->getFile('payment_file');
|
||||||
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) {
|
if (strtolower($paymentMethod) === 'check') {
|
||||||
$fileName = $paymentFile->getRandomName();
|
$uploaded = $this->financialAttachmentService->saveUploadedFile($paymentFile, 'checks');
|
||||||
$paymentFile->move(WRITEPATH . 'uploads/checks/', $fileName);
|
if ($uploaded !== null) {
|
||||||
$checkFile = $fileName;
|
$checkFile = $uploaded;
|
||||||
}
|
}
|
||||||
} elseif (strtolower($paymentMethod) === 'card') {
|
} elseif (strtolower($paymentMethod) === 'card') {
|
||||||
$paymentFile = $this->request->getFile('payment_file'); // ✅ Updated to payment_file
|
$uploaded = $this->financialAttachmentService->saveUploadedFile($paymentFile, 'cards');
|
||||||
if ($paymentFile && $paymentFile->isValid() && !$paymentFile->hasMoved()) {
|
if ($uploaded !== null) {
|
||||||
$fileName = $paymentFile->getRandomName();
|
$checkFile = $uploaded;
|
||||||
$paymentFile->move(WRITEPATH . 'uploads/cards/', $fileName);
|
}
|
||||||
$checkFile = $fileName; // reuse for compatibility
|
|
||||||
}
|
}
|
||||||
|
} catch (\RuntimeException $e) {
|
||||||
|
return redirect()->back()->withInput()->with('error', $e->getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
// ❌ Validate amount - negative or zero
|
// ❌ Validate amount - negative or zero
|
||||||
@@ -1259,41 +1101,51 @@ class PaymentController extends ResourceController
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🔄 Recalculate invoice first to ensure totals reflect tuition + events + additional
|
$this->db->transBegin();
|
||||||
$this->recalculateInvoice($payment['invoice_id'], $this->schoolYear);
|
|
||||||
|
|
||||||
// 🔄 Get current balance based on actual payments (with school_year filter)
|
try {
|
||||||
// We need to calculate what the balance would be WITHOUT the current payment being edited
|
$invoiceId = (int) ($payment['invoice_id'] ?? 0);
|
||||||
$currentBalance = $this->getCurrentInvoiceBalanceExcludingPayment($payment['invoice_id'], $paymentId);
|
$lockedInvoice = $this->db->query(
|
||||||
|
'SELECT id FROM invoices WHERE id = ? FOR UPDATE',
|
||||||
|
[$invoiceId]
|
||||||
|
)->getRowArray();
|
||||||
|
|
||||||
if ($paidAmount > $currentBalance) {
|
if (!$lockedInvoice) {
|
||||||
return redirect()->back()->with(
|
$this->db->transRollback();
|
||||||
'error',
|
return redirect()->back()->with('error', 'Linked invoice not found.');
|
||||||
'Entered amount (' . number_format($paidAmount, 2) . ') exceeds remaining balance (' . number_format($currentBalance, 2) . ').'
|
}
|
||||||
);
|
|
||||||
|
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||||
|
$currentBalance = $this->getCurrentInvoiceBalanceExcludingPayment($invoiceId, $paymentId);
|
||||||
|
|
||||||
|
if ($paidAmount > $currentBalance + 0.00001) {
|
||||||
|
$this->db->transRollback();
|
||||||
|
return redirect()->back()->with(
|
||||||
|
'error',
|
||||||
|
'Entered amount (' . number_format($paidAmount, 2) . ') exceeds remaining balance (' . number_format($currentBalance, 2) . ').'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$updateData = [
|
||||||
|
'paid_amount' => $paidAmount,
|
||||||
|
'payment_method' => strtolower($paymentMethod),
|
||||||
|
'check_file' => $checkFile,
|
||||||
|
'check_number' => strtolower($paymentMethod) === 'check' ? $checkNumber : null,
|
||||||
|
'balance' => max(0.0, round($currentBalance - $paidAmount, 2)),
|
||||||
|
'status' => FinancialStatus::PAYMENT_RECORDED,
|
||||||
|
'updated_by' => session()->get('user_id'),
|
||||||
|
];
|
||||||
|
|
||||||
|
$this->paymentModel->update($paymentId, $updateData);
|
||||||
|
$this->invoiceLedgerService->recalculateInvoice($invoiceId);
|
||||||
|
$this->db->transCommit();
|
||||||
|
|
||||||
|
return redirect()->back()->with('success', 'Payment updated successfully.');
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$this->db->transRollback();
|
||||||
|
log_message('error', '[manualPayEdit] ' . $e->getMessage());
|
||||||
|
return redirect()->back()->withInput()->with('error', 'Unexpected error while updating payment.');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ✅ Update edited payment with check_number
|
|
||||||
$updateData = [
|
|
||||||
'paid_amount' => $paidAmount,
|
|
||||||
'payment_method' => strtolower($paymentMethod),
|
|
||||||
'check_file' => $checkFile,
|
|
||||||
'updated_by' => session()->get('user_id')
|
|
||||||
];
|
|
||||||
|
|
||||||
// ✅ Only add check_number if payment method is check
|
|
||||||
if (strtolower($paymentMethod) === 'check') {
|
|
||||||
$updateData['check_number'] = $checkNumber;
|
|
||||||
} else {
|
|
||||||
$updateData['check_number'] = null; // Clear check number for non-check payments
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->paymentModel->update($paymentId, $updateData);
|
|
||||||
|
|
||||||
// 🔄 Always recalc invoice after change
|
|
||||||
$this->recalculateInvoice($payment['invoice_id'], $this->schoolYear);
|
|
||||||
|
|
||||||
return redirect()->back()->with('success', 'Payment updated successfully.');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -1302,164 +1154,7 @@ class PaymentController extends ResourceController
|
|||||||
*/
|
*/
|
||||||
private function recalculateInvoice($invoiceId, $schoolYear)
|
private function recalculateInvoice($invoiceId, $schoolYear)
|
||||||
{
|
{
|
||||||
$invoice = $this->invoiceModel->find($invoiceId);
|
$this->invoiceLedgerService->recalculateInvoice((int) $invoiceId);
|
||||||
if (!$invoice) return;
|
|
||||||
|
|
||||||
$parentId = (int)($invoice['parent_id'] ?? 0);
|
|
||||||
if ($parentId <= 0) return;
|
|
||||||
|
|
||||||
// ---- Tuition (recompute from enrollments) ----
|
|
||||||
$enrollments = $this->enrollmentModel
|
|
||||||
->where('parent_id', $parentId)
|
|
||||||
->where('school_year', $schoolYear)
|
|
||||||
->findAll();
|
|
||||||
|
|
||||||
$registered = [];
|
|
||||||
$withdrawn = [];
|
|
||||||
foreach ($enrollments as $e) {
|
|
||||||
$row = [
|
|
||||||
'student_id' => (int)($e['student_id'] ?? 0),
|
|
||||||
'class_section_id' => $e['class_section_id'] ?? null,
|
|
||||||
'enrollment_status'=> (string)($e['enrollment_status'] ?? ''),
|
|
||||||
];
|
|
||||||
if (in_array($row['enrollment_status'], ['enrolled','payment pending'], true)) {
|
|
||||||
$registered[] = $row;
|
|
||||||
} elseif (in_array($row['enrollment_status'], ['withdrawn','refund pending','withdraw under review'], true)) {
|
|
||||||
$withdrawn[] = $row;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Refund window check – if after deadline, withdrawn still billed
|
|
||||||
$refundDeadline = (string)($this->configModel->getConfig('refund_deadline') ?? '');
|
|
||||||
$refundAllowed = true;
|
|
||||||
try {
|
|
||||||
$tzName = (string) (config('School')->attendance['timezone'] ?? user_timezone());
|
|
||||||
$tz = new \DateTimeZone($tzName);
|
|
||||||
$today = new \DateTimeImmutable('today', $tz);
|
|
||||||
$deadline = new \DateTimeImmutable($refundDeadline, $tz);
|
|
||||||
$refundAllowed = $today <= $deadline;
|
|
||||||
} catch (\Throwable $e) {
|
|
||||||
$refundAllowed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
$tuitionStudents = $registered;
|
|
||||||
if (!$refundAllowed) {
|
|
||||||
$tuitionStudents = array_merge($tuitionStudents, $withdrawn);
|
|
||||||
}
|
|
||||||
|
|
||||||
$tuitionStudents = array_values(array_filter($tuitionStudents, function ($student) use ($schoolYear) {
|
|
||||||
$sid = (int)($student['student_id'] ?? 0);
|
|
||||||
return $sid > 0 && $this->studentClassModel->hasNonEventAssignment($sid, $schoolYear);
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Grade threshold and fees
|
|
||||||
$gradeFee = (int)($this->configModel->getConfig('grade_fee') ?? 9);
|
|
||||||
$firstStudentFee = (float)($this->configModel->getConfig('first_student_fee') ?? 350);
|
|
||||||
$secondStudentFee = (float)($this->configModel->getConfig('second_student_fee') ?? 200);
|
|
||||||
$youthFee = (float)($this->configModel->getConfig('youth_fee') ?? 180);
|
|
||||||
|
|
||||||
// Normalize grades for tuition students
|
|
||||||
foreach ($tuitionStudents as &$s) {
|
|
||||||
$name = null;
|
|
||||||
if (!empty($s['class_section_id'])) {
|
|
||||||
$name = $this->classSectionModel->getClassSectionNameBySectionId($s['class_section_id']);
|
|
||||||
}
|
|
||||||
$s['grade_name'] = is_string($name) ? strtoupper(trim($name)) : 'N/A';
|
|
||||||
}
|
|
||||||
unset($s);
|
|
||||||
|
|
||||||
// Count regular vs youth and compute tuition
|
|
||||||
$regularCount = 0;
|
|
||||||
$youthCount = 0;
|
|
||||||
foreach ($tuitionStudents as $s) {
|
|
||||||
$lvl = $this->parseGradeLevel($s['grade_name']);
|
|
||||||
if ($lvl > $gradeFee) $youthCount++; else $regularCount++;
|
|
||||||
}
|
|
||||||
|
|
||||||
$tuitionSubtotal = 0.0;
|
|
||||||
$tuitionSubtotal += $youthCount * $youthFee;
|
|
||||||
if ($regularCount >= 2) {
|
|
||||||
$tuitionSubtotal += $firstStudentFee + ($regularCount - 1) * $secondStudentFee;
|
|
||||||
} elseif ($regularCount === 1) {
|
|
||||||
$tuitionSubtotal += $firstStudentFee;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- Event charges (parent-year) ----
|
|
||||||
$eventSubtotal = 0.0;
|
|
||||||
try {
|
|
||||||
$events = $this->eventChargesModel->getChargesWithEventInfo($parentId, $schoolYear) ?? [];
|
|
||||||
foreach ($events as $ev) { $eventSubtotal += (float)($ev['charged'] ?? 0.0); }
|
|
||||||
} catch (\Throwable $e) {}
|
|
||||||
|
|
||||||
// ---- Additional charges (per-invoice) ----
|
|
||||||
$additionalSubtotal = 0.0;
|
|
||||||
try {
|
|
||||||
$rows = $this->additionalChargeModel
|
|
||||||
->select('charge_type, amount')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->where('status', 'applied')
|
|
||||||
->findAll();
|
|
||||||
foreach ($rows as $r) {
|
|
||||||
$amt = (float)($r['amount'] ?? 0);
|
|
||||||
$typ = strtolower((string)($r['charge_type'] ?? 'add'));
|
|
||||||
if ($typ === 'deduct') $amt = -abs($amt); else $amt = abs($amt);
|
|
||||||
$additionalSubtotal += $amt;
|
|
||||||
}
|
|
||||||
} catch (\Throwable $e) {}
|
|
||||||
|
|
||||||
$newTotal = round($tuitionSubtotal + $eventSubtotal + $additionalSubtotal, 2);
|
|
||||||
|
|
||||||
// ---- Payments / Discounts / Refunds ----
|
|
||||||
$db = $this->db;
|
|
||||||
$table = $this->paymentModel->table;
|
|
||||||
$hasStatus = $db->fieldExists('status', $table);
|
|
||||||
$hasVoid = $db->fieldExists('is_void', $table);
|
|
||||||
$exclude = ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'];
|
|
||||||
|
|
||||||
$qb = $this->paymentModel
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->where('school_year', $schoolYear);
|
|
||||||
|
|
||||||
if ($hasStatus) {
|
|
||||||
$qb->groupStart()
|
|
||||||
->whereNotIn('status', $exclude)
|
|
||||||
->orWhere('status IS NULL', null, false)
|
|
||||||
->groupEnd();
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($hasVoid) {
|
|
||||||
$qb->groupStart()
|
|
||||||
->where('is_void', 0)
|
|
||||||
->orWhere('is_void IS NULL', null, false)
|
|
||||||
->groupEnd();
|
|
||||||
}
|
|
||||||
|
|
||||||
$payments = $qb->findAll();
|
|
||||||
$totalPaid = 0.0;
|
|
||||||
foreach ($payments as $p) { $totalPaid += (float)($p['paid_amount'] ?? 0); }
|
|
||||||
|
|
||||||
$discRow = $this->db->table('discount_usages')
|
|
||||||
->select('COALESCE(SUM(discount_amount),0) AS total_disc')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->get()->getRowArray();
|
|
||||||
$totalDisc = (float)($discRow['total_disc'] ?? 0);
|
|
||||||
|
|
||||||
$refundRow = $this->db->table('refunds')
|
|
||||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->whereIn('status', ['Partial','Paid'])
|
|
||||||
->get()->getRowArray();
|
|
||||||
$totalRefundPaid = (float)($refundRow['total_refund_paid'] ?? 0);
|
|
||||||
|
|
||||||
$newBalance = max(0.0, $newTotal - $totalDisc - $totalPaid - $totalRefundPaid);
|
|
||||||
$newStatus = ($newBalance <= 0.00001) ? 'Paid' : (($totalPaid > 0) ? 'Partially Paid' : 'Unpaid');
|
|
||||||
|
|
||||||
$this->invoiceModel->update($invoiceId, [
|
|
||||||
'total_amount' => $newTotal,
|
|
||||||
'paid_amount' => $totalPaid,
|
|
||||||
'balance' => $newBalance,
|
|
||||||
'status' => $newStatus,
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1521,106 +1216,28 @@ class PaymentController extends ResourceController
|
|||||||
/** Get current invoice balance = total - payments - discounts - refundsPaid (no school_year filter). */
|
/** Get current invoice balance = total - payments - discounts - refundsPaid (no school_year filter). */
|
||||||
private function getCurrentInvoiceBalance(int $invoiceId): float
|
private function getCurrentInvoiceBalance(int $invoiceId): float
|
||||||
{
|
{
|
||||||
$invoice = $this->invoiceModel->find($invoiceId);
|
try {
|
||||||
if (!$invoice) return 0.0;
|
return (float) ($this->invoiceLedgerService->calculateInvoice($invoiceId)['balance'] ?? 0.0);
|
||||||
|
} catch (\Throwable $e) {
|
||||||
$db = $this->db;
|
return 0.0;
|
||||||
$table = $this->paymentModel->table; // usually 'payments'
|
|
||||||
$hasStatus = $db->fieldExists('status', $table);
|
|
||||||
$hasVoid = $db->fieldExists('is_void', $table);
|
|
||||||
|
|
||||||
$qb = $this->paymentModel
|
|
||||||
->select('COALESCE(SUM(paid_amount),0) AS total_paid')
|
|
||||||
->where('invoice_id', $invoiceId);
|
|
||||||
|
|
||||||
if ($hasStatus) {
|
|
||||||
$qb->groupStart()
|
|
||||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
|
||||||
->orWhere('status IS NULL', null, false)
|
|
||||||
->groupEnd();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($hasVoid) {
|
|
||||||
$qb->groupStart()
|
|
||||||
->where('is_void', 0)
|
|
||||||
->orWhere('is_void IS NULL', null, false)
|
|
||||||
->groupEnd();
|
|
||||||
}
|
|
||||||
|
|
||||||
$row = $qb->first();
|
|
||||||
$totalPaid = (float)($row['total_paid'] ?? 0);
|
|
||||||
|
|
||||||
// Discount sum on this invoice
|
|
||||||
$discRow = $this->db->table('discount_usages')
|
|
||||||
->select('COALESCE(SUM(discount_amount),0) AS total_disc')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->get()->getRowArray();
|
|
||||||
$totalDisc = (float)($discRow['total_disc'] ?? 0);
|
|
||||||
|
|
||||||
// Refunds paid
|
|
||||||
$refundRow = $this->db->table('refunds')
|
|
||||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->whereIn('status', ['Partial','Paid'])
|
|
||||||
->get()->getRowArray();
|
|
||||||
$totalRefundPaid = (float)($refundRow['total_refund_paid'] ?? 0);
|
|
||||||
|
|
||||||
$total = (float)($invoice['total_amount'] ?? 0);
|
|
||||||
|
|
||||||
return max(0.0, round($total - $totalPaid - $totalDisc - $totalRefundPaid, 2));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Balance excluding a specific payment (for edit scenarios) and subtracting discounts/refunds. */
|
/** Balance excluding a specific payment (for edit scenarios) and subtracting discounts/refunds. */
|
||||||
private function getCurrentInvoiceBalanceExcludingPayment(int $invoiceId, int $excludePaymentId): float
|
private function getCurrentInvoiceBalanceExcludingPayment(int $invoiceId, int $excludePaymentId): float
|
||||||
{
|
{
|
||||||
$invoice = $this->invoiceModel->find($invoiceId);
|
$payment = $this->paymentModel->find($excludePaymentId);
|
||||||
if (!$invoice) return 0.0;
|
if (!$payment) {
|
||||||
|
return $this->getCurrentInvoiceBalance($invoiceId);
|
||||||
$db = $this->db;
|
|
||||||
$table = $this->paymentModel->table;
|
|
||||||
$hasStatus = $db->fieldExists('status', $table);
|
|
||||||
$hasVoid = $db->fieldExists('is_void', $table);
|
|
||||||
|
|
||||||
$qb = $this->paymentModel
|
|
||||||
->select('COALESCE(SUM(paid_amount),0) AS total_paid')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->where('id !=', $excludePaymentId);
|
|
||||||
|
|
||||||
if ($hasStatus) {
|
|
||||||
$qb->groupStart()
|
|
||||||
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
|
||||||
->orWhere('status IS NULL', null, false)
|
|
||||||
->groupEnd();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($hasVoid) {
|
$currentBalance = $this->getCurrentInvoiceBalance($invoiceId);
|
||||||
$qb->groupStart()
|
$status = FinancialStatus::normalizePaymentStatus($payment['status'] ?? null);
|
||||||
->where('is_void', 0)
|
if (in_array($status, FinancialStatus::EXCLUDED_PAYMENT_STATUSES, true)) {
|
||||||
->orWhere('is_void IS NULL', null, false)
|
return $currentBalance;
|
||||||
->groupEnd();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$row = $qb->first();
|
return max(0.0, round($currentBalance + (float) ($payment['paid_amount'] ?? 0), 2));
|
||||||
$totalPaid = (float)($row['total_paid'] ?? 0);
|
|
||||||
|
|
||||||
// Discount sum on this invoice
|
|
||||||
$discRow = $this->db->table('discount_usages')
|
|
||||||
->select('COALESCE(SUM(discount_amount),0) AS total_disc')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->get()->getRowArray();
|
|
||||||
$totalDisc = (float)($discRow['total_disc'] ?? 0);
|
|
||||||
|
|
||||||
// Refunds paid
|
|
||||||
$refundRow = $this->db->table('refunds')
|
|
||||||
->select('COALESCE(SUM(refund_paid_amount),0) AS total_refund_paid')
|
|
||||||
->where('invoice_id', $invoiceId)
|
|
||||||
->whereIn('status', ['Partial','Paid'])
|
|
||||||
->get()->getRowArray();
|
|
||||||
$totalRefundPaid = (float)($refundRow['total_refund_paid'] ?? 0);
|
|
||||||
|
|
||||||
$total = (float)($invoice['total_amount'] ?? 0);
|
|
||||||
|
|
||||||
return max(0.0, round($total - $totalPaid - $totalDisc - $totalRefundPaid, 2));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -1655,9 +1272,11 @@ class PaymentController extends ResourceController
|
|||||||
$schoolYear = null,
|
$schoolYear = null,
|
||||||
$semester = null,
|
$semester = null,
|
||||||
$checkNumber = null,
|
$checkNumber = null,
|
||||||
?int $installmentSeq = null // <-- NOW: the installment sequence (1,2,3,...) for this invoice
|
?int $installmentSeq = null,
|
||||||
|
?array $invoice = null,
|
||||||
|
?float $currentBalance = null
|
||||||
) {
|
) {
|
||||||
$invoice = $this->invoiceModel->find($invoiceId);
|
$invoice = $invoice ?? $this->invoiceModel->find($invoiceId);
|
||||||
if (!$invoice) {
|
if (!$invoice) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -1678,49 +1297,26 @@ class PaymentController extends ResourceController
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Compute new totals
|
$preBalance = $currentBalance ?? $this->getCurrentInvoiceBalance((int) $invoiceId);
|
||||||
$newPaid = (float) $invoice['paid_amount'] + (float) $amount;
|
$newBalance = max(0.0, round($preBalance - (float) $amount, 2));
|
||||||
$newBalance = (float) $invoice['balance'] - (float) $amount;
|
|
||||||
if ($newBalance == $invoice['total_amount']) {
|
|
||||||
$paymentStatus = 'Unpaid';
|
|
||||||
} elseif ($newBalance > 0 && $newBalance < $invoice['total_amount']) {
|
|
||||||
$paymentStatus = 'Partially Paid';
|
|
||||||
} elseif ($newBalance <= 0.00001) {
|
|
||||||
$paymentStatus = 'Paid';
|
|
||||||
} else {
|
|
||||||
$paymentStatus = $invoice['status']; // fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update invoice
|
|
||||||
$invoiceUpdateData = [
|
|
||||||
'paid_amount' => $newPaid,
|
|
||||||
'balance' => $newBalance,
|
|
||||||
'status' => $paymentStatus,
|
|
||||||
'updated_by' => session()->get('user_id'),
|
|
||||||
];
|
|
||||||
if (!$this->invoiceModel->update($invoiceId, $invoiceUpdateData)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store the *sequence* in number_of_installments (kept for schema compatibility)
|
|
||||||
// Consider renaming the column to `installment_seq` in a future migration.
|
|
||||||
$paymentData = [
|
$paymentData = [
|
||||||
'parent_id' => $invoice['parent_id'],
|
'parent_id' => $invoice['parent_id'],
|
||||||
'invoice_id' => $invoiceId,
|
'invoice_id' => $invoiceId,
|
||||||
'total_amount' => $invoice['total_amount'],
|
'total_amount' => $invoice['total_amount'],
|
||||||
'paid_amount' => $amount,
|
'paid_amount' => $amount,
|
||||||
'balance' => $newBalance,
|
'balance' => $newBalance,
|
||||||
'number_of_installments' => $installmentSeq, // <-- installment sequence (1,2,3,...)
|
'number_of_installments' => $installmentSeq, // <-- installment sequence (1,2,3,...)
|
||||||
'transaction_id' => $transactionId,
|
'installment_seq' => $installmentSeq,
|
||||||
'payment_method' => strtolower($paymentMethod),
|
'transaction_id' => $transactionId,
|
||||||
'payment_date' => $paymentDate,
|
'payment_method' => strtolower($paymentMethod),
|
||||||
'status' => $paymentStatus,
|
'payment_date' => $paymentDate,
|
||||||
'check_file' => $checkFile,
|
'status' => FinancialStatus::PAYMENT_RECORDED,
|
||||||
'check_number' => (strtolower($paymentMethod) === 'check') ? $checkNumber : null,
|
'check_file' => $checkFile,
|
||||||
'updated_by' => session()->get('user_id'),
|
'check_number' => (strtolower($paymentMethod) === 'check') ? $checkNumber : null,
|
||||||
'school_year' => $schoolYear ?? $this->schoolYear,
|
'updated_by' => session()->get('user_id'),
|
||||||
'semester' => $semester ?? $this->semester,
|
'school_year' => $schoolYear ?? $this->schoolYear,
|
||||||
// 'installment_index' => $installmentSeq, // use if you add a dedicated column later
|
'semester' => $semester ?? $this->semester,
|
||||||
];
|
];
|
||||||
|
|
||||||
if (!$this->paymentModel->insert($paymentData)) {
|
if (!$this->paymentModel->insert($paymentData)) {
|
||||||
@@ -1741,35 +1337,53 @@ class PaymentController extends ResourceController
|
|||||||
->countAllResults();
|
->countAllResults();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function serveCheckFile($filename, $mode = 'download')
|
public function servePaymentFile(int $paymentId, string $mode = 'download')
|
||||||
{
|
{
|
||||||
$filename = basename($filename);
|
$payment = $this->paymentModel->find($paymentId);
|
||||||
$roots = [
|
if (!$payment || empty($payment['check_file'])) {
|
||||||
WRITEPATH . 'uploads/checks/' . $filename,
|
throw PageNotFoundException::forPageNotFound('Payment file not found.');
|
||||||
WRITEPATH . 'uploads/cards/' . $filename,
|
|
||||||
WRITEPATH . 'uploads/misc/' . $filename,
|
|
||||||
WRITEPATH . 'uploads/' . $filename, // final fallback
|
|
||||||
];
|
|
||||||
|
|
||||||
$path = null;
|
|
||||||
foreach ($roots as $candidate) {
|
|
||||||
if (is_file($candidate)) {
|
|
||||||
$path = $candidate;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$path) {
|
if (!$this->canViewPayment($payment)) {
|
||||||
throw new \CodeIgniter\Exceptions\PageNotFoundException('Payment file not found: ' . esc($filename));
|
return $this->response->setStatusCode(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$subdir = match (strtolower((string) ($payment['payment_method'] ?? ''))) {
|
||||||
|
'check' => 'checks',
|
||||||
|
'card', 'debit/credit card' => 'cards',
|
||||||
|
default => 'misc',
|
||||||
|
};
|
||||||
|
|
||||||
|
$path = $this->financialAttachmentService->resolvePath($subdir, (string) $payment['check_file']);
|
||||||
|
if ($path === null) {
|
||||||
|
throw PageNotFoundException::forPageNotFound('Payment file not found.');
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($mode === 'inline') {
|
if ($mode === 'inline') {
|
||||||
return $this->response
|
return $this->response
|
||||||
->setHeader('Content-Type', mime_content_type($path))
|
->setHeader('Content-Type', $this->financialAttachmentService->detectMime($path))
|
||||||
->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"')
|
->setHeader('Content-Disposition', 'inline; filename="' . basename($path) . '"')
|
||||||
->setBody(file_get_contents($path));
|
->setBody(file_get_contents($path));
|
||||||
}
|
}
|
||||||
|
|
||||||
return $this->response->download($path, null);
|
return $this->response->download($path, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function canViewPayment(array $payment): bool
|
||||||
|
{
|
||||||
|
$roles = array_map('strtolower', (array) (session()->get('roles') ?? []));
|
||||||
|
$activeRole = strtolower((string) (session()->get('role') ?? ''));
|
||||||
|
if ($activeRole !== '' && !in_array($activeRole, $roles, true)) {
|
||||||
|
$roles[] = $activeRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
$staffRoles = ['administrator', 'administrative staff', 'principal', 'teacher', 'teacher_assistant'];
|
||||||
|
foreach ($staffRoles as $role) {
|
||||||
|
if (in_array($role, $roles, true)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return in_array('parent', $roles, true) && (int) ($payment['parent_id'] ?? 0) === (int) session()->get('user_id');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,99 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Controllers\View;
|
|
||||||
|
|
||||||
use App\Controllers\BaseController;
|
|
||||||
use App\Models\PayPalPaymentModel;
|
|
||||||
use App\Models\PaymentModel;
|
|
||||||
use App\Models\UserModel;
|
|
||||||
use App\Models\ConfigurationModel;
|
|
||||||
use App\Models\InvoiceModel;
|
|
||||||
|
|
||||||
class PaypalTransactionsController extends BaseController
|
|
||||||
{
|
|
||||||
public function index()
|
|
||||||
{
|
|
||||||
$model = new PayPalPaymentModel();
|
|
||||||
|
|
||||||
$keyword = $this->request->getGet('q');
|
|
||||||
$perPage = 10;
|
|
||||||
|
|
||||||
if ($keyword) {
|
|
||||||
$transactions = $model
|
|
||||||
->groupStart()
|
|
||||||
->like('transaction_id', $keyword)
|
|
||||||
->orLike('payer_email', $keyword)
|
|
||||||
->orLike('event_type', $keyword)
|
|
||||||
->orLike('order_id', $keyword)
|
|
||||||
->orLike('parent_school_id', $keyword)
|
|
||||||
->groupEnd()
|
|
||||||
->orderBy('created_at', 'DESC')
|
|
||||||
->paginate($perPage);
|
|
||||||
} else {
|
|
||||||
$transactions = $model
|
|
||||||
->orderBy('created_at', 'DESC')
|
|
||||||
->paginate($perPage);
|
|
||||||
}
|
|
||||||
|
|
||||||
return view('administrator/paypal_transactions', [
|
|
||||||
'transactions' => $transactions,
|
|
||||||
'pager' => $model->pager,
|
|
||||||
'keyword' => $keyword
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function exportCsv()
|
|
||||||
{
|
|
||||||
$model = new PayPalPaymentModel();
|
|
||||||
$keyword = $this->request->getGet('q');
|
|
||||||
|
|
||||||
if ($keyword) {
|
|
||||||
$transactions = $model
|
|
||||||
->groupStart()
|
|
||||||
->like('transaction_id', $keyword)
|
|
||||||
->orLike('payer_email', $keyword)
|
|
||||||
->orLike('event_type', $keyword)
|
|
||||||
->orLike('order_id', $keyword)
|
|
||||||
->orLike('parent_school_id', $keyword)
|
|
||||||
->groupEnd()
|
|
||||||
->orderBy('created_at', 'DESC')
|
|
||||||
->findAll();
|
|
||||||
} else {
|
|
||||||
$transactions = $model->orderBy('created_at', 'DESC')->findAll();
|
|
||||||
}
|
|
||||||
|
|
||||||
$filename = 'paypal_transactions_' . date('Ymd_His') . '.csv';
|
|
||||||
|
|
||||||
header('Content-Type: text/csv');
|
|
||||||
header("Content-Disposition: attachment; filename=\"$filename\"");
|
|
||||||
|
|
||||||
$output = fopen('php://output', 'w');
|
|
||||||
|
|
||||||
// CSV headers
|
|
||||||
fputcsv($output, [
|
|
||||||
'ID', 'Transaction ID', 'Order ID', 'Parent School ID',
|
|
||||||
'Email', 'Amount', 'Net Amount', 'Currency',
|
|
||||||
'Status', 'Event Type', 'Created At'
|
|
||||||
]);
|
|
||||||
|
|
||||||
foreach ($transactions as $t) {
|
|
||||||
fputcsv($output, [
|
|
||||||
$t['id'],
|
|
||||||
$t['transaction_id'],
|
|
||||||
$t['order_id'],
|
|
||||||
$t['parent_school_id'],
|
|
||||||
$t['payer_email'],
|
|
||||||
$t['amount'],
|
|
||||||
$t['net_amount'],
|
|
||||||
$t['currency'],
|
|
||||||
$t['status'],
|
|
||||||
$t['event_type'],
|
|
||||||
$t['created_at'],
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
fclose($output);
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -3,12 +3,15 @@
|
|||||||
namespace App\Controllers\View;
|
namespace App\Controllers\View;
|
||||||
|
|
||||||
use App\Controllers\BaseController;
|
use App\Controllers\BaseController;
|
||||||
|
use App\Libraries\FinancialAttachmentService;
|
||||||
|
use App\Libraries\InvoiceLedgerService;
|
||||||
use App\Models\RefundModel;
|
use App\Models\RefundModel;
|
||||||
use App\Models\UserModel;
|
use App\Models\UserModel;
|
||||||
use App\Models\PaymentModel;
|
use App\Models\PaymentModel;
|
||||||
use App\Models\ConfigurationModel;
|
use App\Models\ConfigurationModel;
|
||||||
use App\Models\InvoiceModel;
|
use App\Models\InvoiceModel;
|
||||||
use App\Models\EnrollmentModel;
|
use App\Models\EnrollmentModel;
|
||||||
|
use CodeIgniter\Exceptions\PageNotFoundException;
|
||||||
|
|
||||||
class RefundController extends BaseController
|
class RefundController extends BaseController
|
||||||
{
|
{
|
||||||
@@ -18,6 +21,8 @@ class RefundController extends BaseController
|
|||||||
protected ConfigurationModel $configModel;
|
protected ConfigurationModel $configModel;
|
||||||
protected InvoiceModel $invoiceModel;
|
protected InvoiceModel $invoiceModel;
|
||||||
protected EnrollmentModel $enrollmentModel;
|
protected EnrollmentModel $enrollmentModel;
|
||||||
|
protected InvoiceLedgerService $invoiceLedgerService;
|
||||||
|
protected FinancialAttachmentService $financialAttachmentService;
|
||||||
protected $db;
|
protected $db;
|
||||||
|
|
||||||
// Allowed request types (mapped to your `refunds.request` column)
|
// Allowed request types (mapped to your `refunds.request` column)
|
||||||
@@ -33,6 +38,8 @@ class RefundController extends BaseController
|
|||||||
$this->configModel = new ConfigurationModel();
|
$this->configModel = new ConfigurationModel();
|
||||||
$this->invoiceModel = new InvoiceModel();
|
$this->invoiceModel = new InvoiceModel();
|
||||||
$this->enrollmentModel = new EnrollmentModel();
|
$this->enrollmentModel = new EnrollmentModel();
|
||||||
|
$this->invoiceLedgerService = new InvoiceLedgerService();
|
||||||
|
$this->financialAttachmentService = new FinancialAttachmentService();
|
||||||
$this->db = \Config\Database::connect();
|
$this->db = \Config\Database::connect();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -445,6 +452,14 @@ class RefundController extends BaseController
|
|||||||
return $this->response->setJSON(['error' => 'Failed to create refund request.']);
|
return $this->response->setJSON(['error' => 'Failed to create refund request.']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!empty($invoiceId)) {
|
||||||
|
try {
|
||||||
|
$this->invoiceLedgerService->recalculateInvoice((int) $invoiceId);
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
log_message('error', 'requestRefund recalc failed: ' . $e->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Fire refundPending notification/event for newly created refunds
|
// Fire refundPending notification/event for newly created refunds
|
||||||
try {
|
try {
|
||||||
$user = $this->userModel->select('id, email, firstname, lastname')->find($parentId) ?: [];
|
$user = $this->userModel->select('id, email, firstname, lastname')->find($parentId) ?: [];
|
||||||
@@ -467,13 +482,36 @@ class RefundController extends BaseController
|
|||||||
// Approve refund (no money movement)
|
// Approve refund (no money movement)
|
||||||
public function approveRefund(int $refundId)
|
public function approveRefund(int $refundId)
|
||||||
{
|
{
|
||||||
$ok = $this->refundModel->update($refundId, [
|
$refund = $this->refundModel->find($refundId);
|
||||||
'status' => 'Approved',
|
if (!$refund) {
|
||||||
'approved_at' => utc_now(),
|
return $this->response->setJSON(['error' => 'Refund not found']);
|
||||||
'approved_by' => session()->get('user_id'),
|
}
|
||||||
'updated_at' => utc_now(),
|
|
||||||
'updated_by' => session()->get('user_id'),
|
$this->db->transBegin();
|
||||||
]);
|
|
||||||
|
try {
|
||||||
|
if (!empty($refund['invoice_id'])) {
|
||||||
|
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $refund['invoice_id']]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$ok = $this->refundModel->update($refundId, [
|
||||||
|
'status' => 'Approved',
|
||||||
|
'approved_at' => utc_now(),
|
||||||
|
'approved_by' => session()->get('user_id'),
|
||||||
|
'updated_at' => utc_now(),
|
||||||
|
'updated_by' => session()->get('user_id'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!empty($refund['invoice_id'])) {
|
||||||
|
$this->invoiceLedgerService->recalculateInvoice((int) $refund['invoice_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->db->transCommit();
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$this->db->transRollback();
|
||||||
|
log_message('error', 'approveRefund failed: ' . $e->getMessage());
|
||||||
|
$ok = false;
|
||||||
|
}
|
||||||
|
|
||||||
return $this->response->setJSON($ok ? ['success' => 'Refund approved'] : ['error' => 'Approve failed']);
|
return $this->response->setJSON($ok ? ['success' => 'Refund approved'] : ['error' => 'Approve failed']);
|
||||||
}
|
}
|
||||||
@@ -481,13 +519,36 @@ class RefundController extends BaseController
|
|||||||
// Reject refund
|
// Reject refund
|
||||||
public function rejectRefund(int $refundId)
|
public function rejectRefund(int $refundId)
|
||||||
{
|
{
|
||||||
$ok = $this->refundModel->update($refundId, [
|
$refund = $this->refundModel->find($refundId);
|
||||||
'status' => 'Rejected',
|
if (!$refund) {
|
||||||
'approved_at' => utc_now(),
|
return $this->response->setJSON(['error' => 'Refund not found']);
|
||||||
'approved_by' => session()->get('user_id'),
|
}
|
||||||
'updated_at' => utc_now(),
|
|
||||||
'updated_by' => session()->get('user_id'),
|
$this->db->transBegin();
|
||||||
]);
|
|
||||||
|
try {
|
||||||
|
if (!empty($refund['invoice_id'])) {
|
||||||
|
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $refund['invoice_id']]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$ok = $this->refundModel->update($refundId, [
|
||||||
|
'status' => 'Rejected',
|
||||||
|
'approved_at' => utc_now(),
|
||||||
|
'approved_by' => session()->get('user_id'),
|
||||||
|
'updated_at' => utc_now(),
|
||||||
|
'updated_by' => session()->get('user_id'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!empty($refund['invoice_id'])) {
|
||||||
|
$this->invoiceLedgerService->recalculateInvoice((int) $refund['invoice_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->db->transCommit();
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$this->db->transRollback();
|
||||||
|
log_message('error', 'rejectRefund failed: ' . $e->getMessage());
|
||||||
|
$ok = false;
|
||||||
|
}
|
||||||
|
|
||||||
return $this->response->setJSON($ok ? ['success' => 'Refund rejected'] : ['error' => 'Reject failed']);
|
return $this->response->setJSON($ok ? ['success' => 'Refund rejected'] : ['error' => 'Reject failed']);
|
||||||
}
|
}
|
||||||
@@ -526,17 +587,21 @@ class RefundController extends BaseController
|
|||||||
// Optional file upload for Check
|
// Optional file upload for Check
|
||||||
$checkFileName = $refund['check_file'] ?? null;
|
$checkFileName = $refund['check_file'] ?? null;
|
||||||
if ($refundMethod === 'Check') {
|
if ($refundMethod === 'Check') {
|
||||||
$checkFile = $this->request->getFile('check_file');
|
try {
|
||||||
if ($checkFile && $checkFile->isValid() && !$checkFile->hasMoved()) {
|
$checkFile = $this->request->getFile('check_file');
|
||||||
$checkFileName = $checkFile->getRandomName();
|
$uploaded = $this->financialAttachmentService->saveUploadedFile($checkFile, 'checks');
|
||||||
$checkFile->move(WRITEPATH . 'uploads/checks/', $checkFileName);
|
if ($uploaded !== null) {
|
||||||
|
$checkFileName = $uploaded;
|
||||||
|
}
|
||||||
|
} catch (\RuntimeException $e) {
|
||||||
|
return $this->response->setJSON(['error' => $e->getMessage()]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$newStatus = ($total < $target) ? 'Partial' : 'Paid';
|
$newStatus = ($total < $target) ? 'Partial' : 'Paid';
|
||||||
|
|
||||||
$db = db_connect();
|
$db = db_connect();
|
||||||
$db->transStart();
|
$db->transBegin();
|
||||||
|
|
||||||
// 0) If this refund is not tied to an invoice yet, assign it to the most overpaid invoice
|
// 0) If this refund is not tied to an invoice yet, assign it to the most overpaid invoice
|
||||||
$assignInvoiceId = null;
|
$assignInvoiceId = null;
|
||||||
@@ -595,26 +660,32 @@ class RefundController extends BaseController
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1) Update refund row
|
try {
|
||||||
$this->refundModel->update($refundId, [
|
$affectedInvoiceId = (int) ($assignInvoiceId ?? $refund['invoice_id'] ?? 0);
|
||||||
'refund_paid_amount' => $total,
|
if ($affectedInvoiceId > 0) {
|
||||||
'status' => $newStatus,
|
$db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [$affectedInvoiceId]);
|
||||||
'refunded_at' => utc_now(),
|
}
|
||||||
'updated_at' => utc_now(),
|
|
||||||
'updated_by' => session()->get('user_id'),
|
|
||||||
'refund_method' => $refundMethod,
|
|
||||||
'check_nbr' => $checkNbr,
|
|
||||||
'check_file' => $checkFileName,
|
|
||||||
// tie to invoice if determined
|
|
||||||
'invoice_id' => $assignInvoiceId ?? $refund['invoice_id'],
|
|
||||||
]);
|
|
||||||
|
|
||||||
// 2) Optional: If you want an accounting journal entry for payouts, write to a dedicated table.
|
$this->refundModel->update($refundId, [
|
||||||
// We no longer insert a negative row into payments to avoid schema/validation conflicts.
|
'refund_paid_amount' => $total,
|
||||||
|
'status' => $newStatus,
|
||||||
|
'refunded_at' => utc_now(),
|
||||||
|
'updated_at' => utc_now(),
|
||||||
|
'updated_by' => session()->get('user_id'),
|
||||||
|
'refund_method' => $refundMethod,
|
||||||
|
'check_nbr' => $checkNbr,
|
||||||
|
'check_file' => $checkFileName,
|
||||||
|
'invoice_id' => $affectedInvoiceId ?: null,
|
||||||
|
]);
|
||||||
|
|
||||||
$db->transComplete();
|
if ($affectedInvoiceId > 0) {
|
||||||
|
$this->invoiceLedgerService->recalculateInvoice($affectedInvoiceId);
|
||||||
|
}
|
||||||
|
|
||||||
if ($db->transStatus() === false) {
|
$db->transCommit();
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$db->transRollback();
|
||||||
|
log_message('error', 'updatePayment failed: ' . $e->getMessage());
|
||||||
return $this->response->setJSON(['error' => 'Failed to update payment.']);
|
return $this->response->setJSON(['error' => 'Failed to update payment.']);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -770,16 +841,77 @@ class RefundController extends BaseController
|
|||||||
return $this->response->setJSON(['error' => 'Refund not found.']);
|
return $this->response->setJSON(['error' => 'Refund not found.']);
|
||||||
}
|
}
|
||||||
|
|
||||||
$ok = $this->refundModel->update($refundId, [
|
$this->db->transBegin();
|
||||||
'status' => $status,
|
|
||||||
'reason' => $reason,
|
try {
|
||||||
'approved_at' => utc_now(),
|
if (!empty($refund['invoice_id'])) {
|
||||||
'approved_by' => session()->get('user_id'),
|
$this->db->query('SELECT id FROM invoices WHERE id = ? FOR UPDATE', [(int) $refund['invoice_id']]);
|
||||||
'updated_at' => utc_now(),
|
}
|
||||||
'updated_by' => session()->get('user_id'),
|
|
||||||
]);
|
$ok = $this->refundModel->update($refundId, [
|
||||||
|
'status' => $status,
|
||||||
|
'reason' => $reason,
|
||||||
|
'approved_at' => utc_now(),
|
||||||
|
'approved_by' => session()->get('user_id'),
|
||||||
|
'updated_at' => utc_now(),
|
||||||
|
'updated_by' => session()->get('user_id'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!empty($refund['invoice_id'])) {
|
||||||
|
$this->invoiceLedgerService->recalculateInvoice((int) $refund['invoice_id']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->db->transCommit();
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$this->db->transRollback();
|
||||||
|
log_message('error', 'updateStatus failed: ' . $e->getMessage());
|
||||||
|
$ok = false;
|
||||||
|
}
|
||||||
|
|
||||||
return $this->response->setJSON($ok ? ['success' => 'Refund status updated successfully.']
|
return $this->response->setJSON($ok ? ['success' => 'Refund status updated successfully.']
|
||||||
: ['error' => 'Failed to update refund status.']);
|
: ['error' => 'Failed to update refund status.']);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function serveRefundFile(int $refundId, string $mode = 'download')
|
||||||
|
{
|
||||||
|
$refund = $this->refundModel->find($refundId);
|
||||||
|
if (!$refund || empty($refund['check_file'])) {
|
||||||
|
throw PageNotFoundException::forPageNotFound('Refund file not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$this->canViewRefund($refund)) {
|
||||||
|
return $this->response->setStatusCode(403);
|
||||||
|
}
|
||||||
|
|
||||||
|
$path = $this->financialAttachmentService->resolvePath('checks', (string) $refund['check_file']);
|
||||||
|
if ($path === null) {
|
||||||
|
throw PageNotFoundException::forPageNotFound('Refund file not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($mode === 'inline') {
|
||||||
|
return $this->response
|
||||||
|
->setHeader('Content-Type', $this->financialAttachmentService->detectMime($path))
|
||||||
|
->setHeader('Content-Disposition', 'inline; filename="' . basename($path) . '"')
|
||||||
|
->setBody(file_get_contents($path));
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->response->download($path, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function canViewRefund(array $refund): bool
|
||||||
|
{
|
||||||
|
$roles = array_map('strtolower', (array) (session()->get('roles') ?? []));
|
||||||
|
$activeRole = strtolower((string) (session()->get('role') ?? ''));
|
||||||
|
if ($activeRole !== '' && !in_array($activeRole, $roles, true)) {
|
||||||
|
$roles[] = $activeRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (['administrator', 'administrative staff', 'principal', 'teacher', 'teacher_assistant'] as $role) {
|
||||||
|
if (in_array($role, $roles, true)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return in_array('parent', $roles, true) && (int) ($refund['parent_id'] ?? 0) === (int) session()->get('user_id');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -601,153 +601,219 @@ class ReimbursementController extends BaseController
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function updateBatchAssignment()
|
public function updateBatchAssignment()
|
||||||
{
|
{
|
||||||
if (strtolower($this->request->getMethod()) !== 'post') {
|
if (strtolower($this->request->getMethod()) !== 'post') {
|
||||||
return $this->response->setStatusCode(405)->setJSON([
|
return $this->response->setStatusCode(405)->setJSON([
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'error' => 'Method not allowed',
|
'error' => 'Method not allowed',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$expenseId = (int) $this->request->getPost('expense_id');
|
$expenseId = (int) $this->request->getPost('expense_id');
|
||||||
$batchIdRaw = $this->request->getPost('batch_id');
|
|
||||||
$batchId = (int) $batchIdRaw;
|
|
||||||
$fallbackBatchNumber = $this->request->getPost('batch_number');
|
|
||||||
if ($batchId <= 0 && $fallbackBatchNumber !== null && trim((string) $fallbackBatchNumber) !== '') {
|
|
||||||
$batchId = (int) $fallbackBatchNumber;
|
|
||||||
}
|
|
||||||
$adminIdRaw = $this->request->getPost('admin_id');
|
|
||||||
$adminId = ($adminIdRaw === '' || $adminIdRaw === null) ? null : (int) $adminIdRaw;
|
|
||||||
$reimbursementId = (int) $this->request->getPost('reimbursement_id') ?: null;
|
|
||||||
|
|
||||||
if ($expenseId <= 0) {
|
$batchIdRaw = $this->request->getPost('batch_id');
|
||||||
return $this->response->setStatusCode(422)->setJSON([
|
$batchId = (int) $batchIdRaw;
|
||||||
'success' => false,
|
|
||||||
'error' => 'Invalid expense id.',
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
$now = date('Y-m-d H:i:s');
|
$fallbackBatchNumber = $this->request->getPost('batch_number');
|
||||||
|
if ($batchId <= 0 && $fallbackBatchNumber !== null && trim((string) $fallbackBatchNumber) !== '') {
|
||||||
|
$batchId = (int) $fallbackBatchNumber;
|
||||||
|
}
|
||||||
|
|
||||||
|
$adminIdRaw = $this->request->getPost('admin_id');
|
||||||
|
$adminId = ($adminIdRaw === '' || $adminIdRaw === null) ? null : (int) $adminIdRaw;
|
||||||
|
|
||||||
|
$reimbursementId = (int) $this->request->getPost('reimbursement_id') ?: null;
|
||||||
|
|
||||||
|
if ($expenseId <= 0) {
|
||||||
|
return $this->response->setStatusCode(422)->setJSON([
|
||||||
|
'success' => false,
|
||||||
|
'error' => 'Invalid expense id.',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$now = date('Y-m-d H:i:s');
|
||||||
|
|
||||||
|
$newHashResponse = function (array $payload = []) {
|
||||||
|
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
||||||
|
|
||||||
|
return $this->response
|
||||||
|
->setHeader('X-CSRF-HASH', (string) $newHash)
|
||||||
|
->setJSON(array_merge($payload, [
|
||||||
|
'csrf_hash' => $newHash,
|
||||||
|
]));
|
||||||
|
};
|
||||||
|
|
||||||
|
$this->db->transBegin();
|
||||||
|
|
||||||
|
try {
|
||||||
$activeItem = $this->batchItemModel
|
$activeItem = $this->batchItemModel
|
||||||
->where('expense_id', $expenseId)
|
->where('expense_id', $expenseId)
|
||||||
->where('unassigned_at IS NULL', null, false)
|
->where('unassigned_at IS NULL', null, false)
|
||||||
->first();
|
->first();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If no batch is provided, remove the item from active batch processing.
|
||||||
|
* This means "unassigned from batch", not "unassigned admin".
|
||||||
|
*/
|
||||||
if ($batchId <= 0) {
|
if ($batchId <= 0) {
|
||||||
if ($activeItem) {
|
if ($activeItem) {
|
||||||
$this->batchItemModel->update((int) $activeItem['id'], ['unassigned_at' => $now]);
|
$this->batchItemModel->update((int) $activeItem['id'], [
|
||||||
|
'unassigned_at' => $now,
|
||||||
|
]);
|
||||||
|
|
||||||
if (!$reimbursementId && !empty($activeItem['reimbursement_id'])) {
|
if (!$reimbursementId && !empty($activeItem['reimbursement_id'])) {
|
||||||
$reimbursementId = (int) $activeItem['reimbursement_id'];
|
$reimbursementId = (int) $activeItem['reimbursement_id'];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
if (!$this->db->transStatus()) {
|
||||||
return $this->response
|
throw new \RuntimeException('Transaction failed while unassigning batch item.');
|
||||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
}
|
||||||
->setJSON([
|
|
||||||
'success' => true,
|
$this->db->transCommit();
|
||||||
'batch_id' => 0,
|
|
||||||
'admin_id' => null,
|
return $newHashResponse([
|
||||||
'reimbursement_id' => $reimbursementId,
|
'success' => true,
|
||||||
'csrf_hash' => $newHash,
|
'batch_id' => 0,
|
||||||
]);
|
'admin_id' => null,
|
||||||
|
'reimbursement_id' => $reimbursementId,
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$batch = $this->batchModel->find($batchId);
|
$batch = $this->batchModel->find($batchId);
|
||||||
if (!$batch || strtolower((string) ($batch['status'] ?? 'open')) !== 'open') {
|
if (!$batch || strtolower((string) ($batch['status'] ?? 'open')) !== 'open') {
|
||||||
|
$this->db->transRollback();
|
||||||
|
|
||||||
return $this->response->setStatusCode(404)->setJSON([
|
return $this->response->setStatusCode(404)->setJSON([
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'error' => 'Batch not found or already closed.',
|
'error' => 'Batch not found or already closed.',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$currentAdmin = $activeItem ? (int) ($activeItem['admin_id'] ?? 0) : null;
|
if (!$reimbursementId) {
|
||||||
$activeSameBatch = $activeItem && (int) ($activeItem['batch_id'] ?? 0) === $batchId;
|
if ($activeItem && !empty($activeItem['reimbursement_id'])) {
|
||||||
if ($activeSameBatch && ($currentAdmin === ($adminId ?? 0))) {
|
$reimbursementId = (int) $activeItem['reimbursement_id'];
|
||||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
} else {
|
||||||
return $this->response
|
$reimbursementId = $this->lookupReimbursementId($expenseId);
|
||||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
}
|
||||||
->setJSON([
|
|
||||||
'success' => true,
|
|
||||||
'batch_id' => $batchId,
|
|
||||||
'admin_id' => $adminId,
|
|
||||||
'reimbursement_id' => $activeItem['reimbursement_id'] ?? null,
|
|
||||||
'csrf_hash' => $newHash,
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($activeSameBatch) {
|
$activeSameBatch = $activeItem && (int) ($activeItem['batch_id'] ?? 0) === $batchId;
|
||||||
if (!$reimbursementId) {
|
$currentAdmin = $activeItem ? (int) ($activeItem['admin_id'] ?? 0) : null;
|
||||||
$reimbursementId = $activeItem['reimbursement_id'] ? (int) $activeItem['reimbursement_id'] : $this->lookupReimbursementId($expenseId);
|
$requestedAdmin = $adminId ?? 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the item is already active in the same batch/admin slot, just return success.
|
||||||
|
*/
|
||||||
|
if ($activeSameBatch && $currentAdmin === $requestedAdmin) {
|
||||||
|
if (!$this->db->transStatus()) {
|
||||||
|
throw new \RuntimeException('Transaction failed while checking existing assignment.');
|
||||||
}
|
}
|
||||||
$updatePayload = [
|
|
||||||
|
$this->db->transCommit();
|
||||||
|
|
||||||
|
return $newHashResponse([
|
||||||
|
'success' => true,
|
||||||
|
'batch_id' => $batchId,
|
||||||
|
'admin_id' => $adminId,
|
||||||
|
'reimbursement_id' => $activeItem['reimbursement_id'] ?? $reimbursementId,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If same batch but different admin, update the existing active row.
|
||||||
|
*
|
||||||
|
* Important:
|
||||||
|
* admin_id = null means active in the batch but not assigned to an admin.
|
||||||
|
* unassigned_at != null means removed from active batch processing.
|
||||||
|
*/
|
||||||
|
if ($activeSameBatch) {
|
||||||
|
$this->batchItemModel->update((int) $activeItem['id'], [
|
||||||
'admin_id' => $adminId,
|
'admin_id' => $adminId,
|
||||||
'assigned_at' => $now,
|
'assigned_at' => $now,
|
||||||
'reimbursement_id' => $reimbursementId,
|
'reimbursement_id' => $reimbursementId,
|
||||||
'unassigned_at' => $adminId === null ? $now : null,
|
'unassigned_at' => null,
|
||||||
];
|
]);
|
||||||
$this->batchItemModel->update((int) $activeItem['id'], $updatePayload);
|
|
||||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
|
||||||
return $this->response
|
|
||||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
|
||||||
->setJSON([
|
|
||||||
'success' => true,
|
|
||||||
'batch_id' => $batchId,
|
|
||||||
'admin_id' => $adminId,
|
|
||||||
'reimbursement_id' => $reimbursementId,
|
|
||||||
'csrf_hash' => $newHash,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($activeItem) {
|
if (!$this->db->transStatus()) {
|
||||||
$this->batchItemModel->update((int) $activeItem['id'], ['unassigned_at' => $now]);
|
throw new \RuntimeException('Transaction failed while updating existing assignment.');
|
||||||
if (!$reimbursementId && !empty($activeItem['reimbursement_id'])) {
|
|
||||||
$reimbursementId = (int) $activeItem['reimbursement_id'];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$this->db->transCommit();
|
||||||
|
|
||||||
|
return $newHashResponse([
|
||||||
|
'success' => true,
|
||||||
|
'batch_id' => $batchId,
|
||||||
|
'admin_id' => $adminId,
|
||||||
|
'reimbursement_id' => $reimbursementId,
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$reimbursementId) {
|
/**
|
||||||
$reimbursementId = $this->lookupReimbursementId($expenseId);
|
* If the item is active in another batch, soft-unassign that row first.
|
||||||
|
*/
|
||||||
|
if ($activeItem) {
|
||||||
|
$this->batchItemModel->update((int) $activeItem['id'], [
|
||||||
|
'unassigned_at' => $now,
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
$insertData = [
|
/**
|
||||||
|
* Critical fix:
|
||||||
|
* Check whether this expense was previously assigned to this batch.
|
||||||
|
* Because uq_batch_expense(batch_id, expense_id) blocks duplicate rows,
|
||||||
|
* we must reactivate/update the old row instead of inserting again.
|
||||||
|
*/
|
||||||
|
$existingBatchItem = $this->batchItemModel
|
||||||
|
->where('batch_id', $batchId)
|
||||||
|
->where('expense_id', $expenseId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
$assignmentData = [
|
||||||
'batch_id' => $batchId,
|
'batch_id' => $batchId,
|
||||||
'expense_id' => $expenseId,
|
'expense_id' => $expenseId,
|
||||||
'reimbursement_id' => $reimbursementId,
|
'reimbursement_id' => $reimbursementId,
|
||||||
'admin_id' => $adminId,
|
'admin_id' => $adminId,
|
||||||
'assigned_at' => $now,
|
'assigned_at' => $now,
|
||||||
|
'unassigned_at' => null,
|
||||||
'school_year' => $this->schoolYear,
|
'school_year' => $this->schoolYear,
|
||||||
'semester' => $this->semester,
|
'semester' => $this->semester,
|
||||||
];
|
];
|
||||||
|
|
||||||
try {
|
if ($existingBatchItem) {
|
||||||
$this->batchItemModel->insert($insertData);
|
$this->batchItemModel->update((int) $existingBatchItem['id'], $assignmentData);
|
||||||
} catch (\Throwable $e) {
|
} else {
|
||||||
log_message('error', 'Failed to assign expense #{expense} to batch #{batch}: {msg}', [
|
$this->batchItemModel->insert($assignmentData);
|
||||||
'expense' => $expenseId,
|
|
||||||
'batch' => $batchId,
|
|
||||||
'msg' => $e->getMessage(),
|
|
||||||
]);
|
|
||||||
return $this->response->setStatusCode(500)->setJSON([
|
|
||||||
'success' => false,
|
|
||||||
'error' => 'Unable to update batch assignment right now.',
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$newHash = function_exists('csrf_hash') ? csrf_hash() : null;
|
if (!$this->db->transStatus()) {
|
||||||
|
throw new \RuntimeException('Transaction failed while saving assignment.');
|
||||||
|
}
|
||||||
|
|
||||||
return $this->response
|
$this->db->transCommit();
|
||||||
->setHeader('X-CSRF-HASH', (string) $newHash)
|
|
||||||
->setJSON([
|
return $newHashResponse([
|
||||||
'success' => true,
|
'success' => true,
|
||||||
'batch_id' => $batchId,
|
'batch_id' => $batchId,
|
||||||
'admin_id' => $adminId,
|
'admin_id' => $adminId,
|
||||||
'reimbursement_id' => $reimbursementId,
|
'reimbursement_id' => $reimbursementId,
|
||||||
'csrf_hash' => $newHash,
|
]);
|
||||||
]);
|
} catch (\Throwable $e) {
|
||||||
|
$this->db->transRollback();
|
||||||
|
|
||||||
|
log_message('error', 'Failed to update batch assignment for expense #{expense}, batch #{batch}: {msg}', [
|
||||||
|
'expense' => $expenseId,
|
||||||
|
'batch' => $batchId,
|
||||||
|
'msg' => $e->getMessage(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return $this->response->setStatusCode(500)->setJSON([
|
||||||
|
'success' => false,
|
||||||
|
'error' => 'Unable to update batch assignment right now.',
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public function lockBatch()
|
public function lockBatch()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -317,18 +317,27 @@ class ReportCardsController extends PrintablesBaseController
|
|||||||
$examCommentTypes = $isSecond
|
$examCommentTypes = $isSecond
|
||||||
? ['final']
|
? ['final']
|
||||||
: ($isFirst ? ['midterm'] : ['midterm', 'final']);
|
: ($isFirst ? ['midterm'] : ['midterm', 'final']);
|
||||||
$commentTypes = array_merge($examCommentTypes, ['ptap', 'attendance', 'attendance_comment']);
|
$wantedCommentTypes = array_merge($examCommentTypes, ['ptap', 'attendance']);
|
||||||
$hasCommentReview = $this->db->fieldExists('comment_review', 'score_comments');
|
$hasCommentReview = $this->db->fieldExists('comment_review', 'score_comments');
|
||||||
$commentSelect = $hasCommentReview
|
$hasCommentSemester = $this->db->fieldExists('semester', 'score_comments');
|
||||||
? 'student_id, score_type, comment, comment_review'
|
$hasCommentUpdatedAt = $this->db->fieldExists('updated_at', 'score_comments');
|
||||||
: 'student_id, score_type, comment';
|
$commentSelectParts = ['student_id', 'score_type', 'comment'];
|
||||||
|
if ($hasCommentReview) {
|
||||||
|
$commentSelectParts[] = 'comment_review';
|
||||||
|
}
|
||||||
|
if ($hasCommentSemester) {
|
||||||
|
$commentSelectParts[] = 'semester';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do NOT filter comments by score_type or semester here.
|
||||||
|
// A single bad row like "Attendance Comment", "attendance-comment", or a blank semester
|
||||||
|
// should not make one student look incomplete while the PDF can still print the comment.
|
||||||
$commentBuilder = $this->scoreCommentModel
|
$commentBuilder = $this->scoreCommentModel
|
||||||
->select($commentSelect)
|
->select(implode(', ', $commentSelectParts))
|
||||||
->whereIn('student_id', $studentIds)
|
->whereIn('student_id', $studentIds)
|
||||||
->where('school_year', $year)
|
->where('school_year', $year);
|
||||||
->whereIn('score_type', $commentTypes);
|
if ($hasCommentUpdatedAt) {
|
||||||
if ($sem !== '') {
|
$commentBuilder->orderBy('updated_at', 'DESC');
|
||||||
$this->applySemesterFilter($commentBuilder, $sem, 'semester');
|
|
||||||
}
|
}
|
||||||
$commentRows = [];
|
$commentRows = [];
|
||||||
try {
|
try {
|
||||||
@@ -336,25 +345,92 @@ class ReportCardsController extends PrintablesBaseController
|
|||||||
} catch (\Throwable $e) {
|
} catch (\Throwable $e) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$cleanComment = static function ($value): string {
|
||||||
|
$text = (string)($value ?? '');
|
||||||
|
$text = str_replace("\xc2\xa0", ' ', $text); // normalize non-breaking spaces
|
||||||
|
return trim($text);
|
||||||
|
};
|
||||||
|
|
||||||
|
$normalizeCommentType = static function ($value) use ($cleanComment): string {
|
||||||
|
$type = strtolower($cleanComment($value));
|
||||||
|
$type = preg_replace('/[^a-z0-9]+/', '_', $type);
|
||||||
|
$type = trim((string)$type, '_');
|
||||||
|
|
||||||
|
$map = [
|
||||||
|
'attendance_comment' => 'attendance',
|
||||||
|
'attendance_comments' => 'attendance',
|
||||||
|
'attendance' => 'attendance',
|
||||||
|
'attendence' => 'attendance',
|
||||||
|
'attendence_comment' => 'attendance',
|
||||||
|
'attendence_comments' => 'attendance',
|
||||||
|
'ptap_comment' => 'ptap',
|
||||||
|
'ptap_comments' => 'ptap',
|
||||||
|
'ptap' => 'ptap',
|
||||||
|
'midterm_comment' => 'midterm',
|
||||||
|
'midterm_comments' => 'midterm',
|
||||||
|
'midterm' => 'midterm',
|
||||||
|
'final_comment' => 'final',
|
||||||
|
'final_comments' => 'final',
|
||||||
|
'final' => 'final',
|
||||||
|
];
|
||||||
|
|
||||||
|
return $map[$type] ?? $type;
|
||||||
|
};
|
||||||
|
|
||||||
|
$normalizeSemester = static function ($value) use ($cleanComment): string {
|
||||||
|
$v = strtolower($cleanComment($value));
|
||||||
|
$v = preg_replace('/[^a-z0-9]+/', ' ', $v);
|
||||||
|
$v = trim((string)$v);
|
||||||
|
if (in_array($v, ['fall', 'first', 'first semester', 'semester 1', '1'], true)) {
|
||||||
|
return 'fall';
|
||||||
|
}
|
||||||
|
if (in_array($v, ['spring', 'second', 'second semester', 'semester 2', '2'], true)) {
|
||||||
|
return 'spring';
|
||||||
|
}
|
||||||
|
return $v;
|
||||||
|
};
|
||||||
|
$wantedSemester = $normalizeSemester($sem);
|
||||||
|
|
||||||
$commentsByStudent = [];
|
$commentsByStudent = [];
|
||||||
|
$commentPriorityByStudent = [];
|
||||||
foreach ($commentRows as $row) {
|
foreach ($commentRows as $row) {
|
||||||
$sid = (int)($row['student_id'] ?? 0);
|
$sid = (int)($row['student_id'] ?? 0);
|
||||||
if ($sid <= 0) {
|
if ($sid <= 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$typeRaw = strtolower(trim((string)($row['score_type'] ?? '')));
|
|
||||||
if ($typeRaw === '') {
|
$typeRaw = $normalizeCommentType($row['score_type'] ?? '');
|
||||||
|
if ($typeRaw === '' || !in_array($typeRaw, $wantedCommentTypes, true)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if ($typeRaw === 'attendance_comment') {
|
|
||||||
$typeRaw = 'attendance';
|
$rawVal = $cleanComment($row['comment'] ?? '');
|
||||||
|
if ($typeRaw === 'attendance') {
|
||||||
|
// Attendance comments are stored in score_comments.comment.
|
||||||
|
// Do not use comment_review here, because it can be blank while the PDF comment exists.
|
||||||
|
$commentVal = $rawVal;
|
||||||
|
} else {
|
||||||
|
// For non-attendance comments, prefer reviewed text but fall back to the saved comment.
|
||||||
|
$reviewVal = $hasCommentReview ? $cleanComment($row['comment_review'] ?? '') : '';
|
||||||
|
$commentVal = $reviewVal !== '' ? $reviewVal : $rawVal;
|
||||||
}
|
}
|
||||||
$reviewVal = $hasCommentReview ? trim((string)($row['comment_review'] ?? '')) : '';
|
|
||||||
$commentVal = $hasCommentReview ? $reviewVal : trim((string)($row['comment'] ?? ''));
|
|
||||||
if ($commentVal === '') {
|
if ($commentVal === '') {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$commentsByStudent[$sid][$typeRaw] = $commentVal;
|
|
||||||
|
$rowSemester = $hasCommentSemester ? $normalizeSemester($row['semester'] ?? '') : '';
|
||||||
|
$priority = 1;
|
||||||
|
if ($wantedSemester !== '' && $rowSemester === $wantedSemester) {
|
||||||
|
$priority = 3;
|
||||||
|
} elseif ($rowSemester === '') {
|
||||||
|
$priority = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
$existingPriority = $commentPriorityByStudent[$sid][$typeRaw] ?? 0;
|
||||||
|
if (!isset($commentsByStudent[$sid][$typeRaw]) || $priority >= $existingPriority) {
|
||||||
|
$commentsByStudent[$sid][$typeRaw] = $commentVal;
|
||||||
|
$commentPriorityByStudent[$sid][$typeRaw] = $priority;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$isNumeric = static fn($v) => $v !== null && $v !== '' && is_numeric($v);
|
$isNumeric = static fn($v) => $v !== null && $v !== '' && is_numeric($v);
|
||||||
@@ -467,6 +543,20 @@ class ReportCardsController extends PrintablesBaseController
|
|||||||
if (trim((string)($commentSet['ptap'] ?? '')) === '') {
|
if (trim((string)($commentSet['ptap'] ?? '')) === '') {
|
||||||
$missing[] = 'PTAP comment';
|
$missing[] = 'PTAP comment';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Keep completeness consistent with the PDF report generation:
|
||||||
|
// the report can auto-generate an attendance comment from attendance_score.
|
||||||
|
if (trim((string)($commentSet['attendance'] ?? '')) === '' && $isNumeric($attendanceScore)) {
|
||||||
|
$autoAttendance = attendance_comment_from_score(
|
||||||
|
(float)$attendanceScore,
|
||||||
|
trim((string)($student['firstname'] ?? ''))
|
||||||
|
);
|
||||||
|
if ($autoAttendance !== null && trim((string)$autoAttendance) !== '') {
|
||||||
|
$commentSet['attendance'] = $autoAttendance;
|
||||||
|
$warnings[] = 'Attendance comment computed from attendance score';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (trim((string)($commentSet['attendance'] ?? '')) === '') {
|
if (trim((string)($commentSet['attendance'] ?? '')) === '') {
|
||||||
$missing[] = 'Attendance comment';
|
$missing[] = 'Attendance comment';
|
||||||
}
|
}
|
||||||
@@ -1014,9 +1104,9 @@ $drawRankCell = static function (
|
|||||||
$pdf->Rect($x, $y, $w, $h);
|
$pdf->Rect($x, $y, $w, $h);
|
||||||
$pdf->SetXY($x + $pad, $y + 3);
|
$pdf->SetXY($x + $pad, $y + 3);
|
||||||
$pdf->SetFont('Helvetica', 'B', 11);
|
$pdf->SetFont('Helvetica', 'B', 11);
|
||||||
$pdf->Write(5, ' Ranking: ');
|
$pdf->Write(5, ' Class Rank: ');
|
||||||
|
|
||||||
$labelWidth = $pdf->GetStringWidth(' Ranking: ');
|
$labelWidth = $pdf->GetStringWidth(' Class Rank: ');
|
||||||
$pdf->SetFont('Helvetica', '', 12);
|
$pdf->SetFont('Helvetica', '', 12);
|
||||||
$pdf->SetXY($x + 2 + $labelWidth, $y + 3);
|
$pdf->SetXY($x + 2 + $labelWidth, $y + 3);
|
||||||
$pdf->Write(5, $rankValue);
|
$pdf->Write(5, $rankValue);
|
||||||
@@ -1531,10 +1621,16 @@ $scoresEndY = $pdf->GetY();
|
|||||||
if ($typeRaw === 'attendance_comment') {
|
if ($typeRaw === 'attendance_comment') {
|
||||||
$typeRaw = 'attendance';
|
$typeRaw = 'attendance';
|
||||||
}
|
}
|
||||||
$reviewVal = trim((string)($row['comment_review'] ?? ''));
|
$rawComment = trim((string)($row['comment'] ?? ''));
|
||||||
$commentVal = $this->db->fieldExists('comment_review', 'score_comments')
|
if ($typeRaw === 'attendance') {
|
||||||
? $reviewVal
|
// Attendance comments must come from score_comments.comment.
|
||||||
: trim((string)($row['comment'] ?? ''));
|
$commentVal = $rawComment;
|
||||||
|
} else {
|
||||||
|
$reviewVal = trim((string)($row['comment_review'] ?? ''));
|
||||||
|
$commentVal = $this->db->fieldExists('comment_review', 'score_comments') && $reviewVal !== ''
|
||||||
|
? $reviewVal
|
||||||
|
: $rawComment;
|
||||||
|
}
|
||||||
if ($commentVal === '') {
|
if ($commentVal === '') {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -1732,161 +1828,226 @@ $scoresEndY = $pdf->GetY();
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
private function calculateTermRanking(
|
private function calculateTermRanking(
|
||||||
int $studentId,
|
int $studentId,
|
||||||
int $sectionCode,
|
int $sectionCode,
|
||||||
?int $sectionId,
|
?int $sectionId,
|
||||||
string $schoolYear,
|
string $schoolYear,
|
||||||
?string $semester,
|
?string $semester,
|
||||||
?float $studentScore
|
?float $studentScore
|
||||||
): ?array {
|
): ?array {
|
||||||
if ($studentId <= 0 || $schoolYear === '' || $studentScore === null) {
|
if ($studentId <= 0 || $schoolYear === '' || $studentScore === null) {
|
||||||
return 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
$sectionIds = array_values(array_unique(array_filter([
|
$scoreVal = $row['semester_score'] ?? null;
|
||||||
$sectionCode > 0 ? $sectionCode : null,
|
|
||||||
$sectionId && $sectionId > 0 ? $sectionId : null,
|
|
||||||
])));
|
|
||||||
|
|
||||||
if (empty($sectionIds)) {
|
if (!is_numeric($scoreVal)) {
|
||||||
return null;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$semesterForRank = trim((string)$semester);
|
$rawScore = (float)$scoreVal;
|
||||||
$rankByFinalScore = $this->normalizeSemester($semesterForRank) === 'spring';
|
|
||||||
|
|
||||||
$builder = $this->db->table('semester_scores ss')
|
$scoresByStudent[$sid] = [
|
||||||
->select('ss.student_id, ss.semester, ss.semester_score, ss.updated_at, ss.id, s.firstname, s.lastname')
|
'student_id' => $sid,
|
||||||
->join('students s', 's.id = ss.student_id', 'inner')
|
'score' => $rawScore,
|
||||||
->where('s.is_active', 1)
|
'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)
|
->where('ss.school_year', $schoolYear)
|
||||||
->whereIn('ss.class_section_id', $sectionIds)
|
->whereIn('ss.student_id', $studentIds)
|
||||||
->orderBy('ss.updated_at', 'DESC')
|
->orderBy('ss.updated_at', 'DESC')
|
||||||
->orderBy('ss.id', 'DESC');
|
->orderBy('ss.id', 'DESC');
|
||||||
|
|
||||||
if ($semesterForRank !== '') {
|
if ($semesterForRank !== '') {
|
||||||
$this->applySemesterFilter($builder, $semesterForRank, 'ss.semester');
|
$this->applySemesterExclusion($firstRowsBuilder, $semesterForRank, 'ss.semester');
|
||||||
}
|
}
|
||||||
|
|
||||||
$rows = $builder->get()->getResultArray();
|
$firstRows = $firstRowsBuilder->get()->getResultArray();
|
||||||
if (empty($rows)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$scoresByStudent = [];
|
$firstScoresByStudent = [];
|
||||||
$studentIds = [];
|
|
||||||
foreach ($rows as $row) {
|
foreach ($firstRows as $row) {
|
||||||
$sid = (int)($row['student_id'] ?? 0);
|
$sid = (int)($row['student_id'] ?? 0);
|
||||||
if ($sid <= 0 || isset($scoresByStudent[$sid])) {
|
|
||||||
|
if ($sid <= 0 || !isset($rosterByStudent[$sid]) || isset($firstScoresByStudent[$sid])) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$scoreVal = $row['semester_score'] ?? null;
|
$scoreVal = $row['semester_score'] ?? null;
|
||||||
|
|
||||||
if (!is_numeric($scoreVal)) {
|
if (!is_numeric($scoreVal)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$scoresByStudent[$sid] = [
|
$firstScoresByStudent[$sid] = (float)$scoreVal;
|
||||||
'student_id' => $sid,
|
|
||||||
'score' => round((float)$scoreVal, 4),
|
|
||||||
'firstname' => trim((string)($row['firstname'] ?? '')),
|
|
||||||
'lastname' => trim((string)($row['lastname'] ?? '')),
|
|
||||||
];
|
|
||||||
$studentIds[] = $sid;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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])) {
|
if (empty($scoresByStudent) || !isset($scoresByStudent[$studentId])) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($rankByFinalScore) {
|
// Force the selected student to use the exact score already computed for the report.
|
||||||
$firstRowsBuilder = $this->db->table('semester_scores ss')
|
// Then rank using the displayed precision: one decimal.
|
||||||
->select('ss.student_id, ss.semester_score, ss.updated_at, ss.id')
|
$scoresByStudent[$studentId]['score'] = (float)$studentScore;
|
||||||
->where('ss.school_year', $schoolYear)
|
$scoresByStudent[$studentId]['rank_score'] = round((float)$studentScore, 1);
|
||||||
->whereIn('ss.class_section_id', $sectionIds)
|
} else {
|
||||||
->whereIn('ss.student_id', $studentIds)
|
// Fall: also force selected student to match the report-card computed score.
|
||||||
->orderBy('ss.updated_at', 'DESC')
|
$scoresByStudent[$studentId]['score'] = (float)$studentScore;
|
||||||
->orderBy('ss.id', 'DESC');
|
$scoresByStudent[$studentId]['rank_score'] = round((float)$studentScore, 1);
|
||||||
|
|
||||||
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($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;
|
|
||||||
}
|
|
||||||
|
|
||||||
$rankRow['score'] = round(((float)$firstScoresByStudent[$sid] + (float)$rankRow['score']) / 2, 4);
|
|
||||||
}
|
|
||||||
unset($rankRow);
|
|
||||||
|
|
||||||
if (empty($scoresByStudent) || !isset($scoresByStudent[$studentId])) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$scoresByStudent[$studentId]['score'] = round((float)$studentScore, 4);
|
|
||||||
}
|
|
||||||
|
|
||||||
$rankable = array_values($scoresByStudent);
|
|
||||||
usort($rankable, static function (array $a, array $b): int {
|
|
||||||
$scoreCmp = $b['score'] <=> $a['score'];
|
|
||||||
if ($scoreCmp !== 0) {
|
|
||||||
return $scoreCmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
$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) {
|
|
||||||
if ($previousScore === null || abs($row['score'] - $previousScore) > 0.0001) {
|
|
||||||
$position = $index + 1;
|
|
||||||
$previousScore = $row['score'];
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((int)$row['student_id'] === $studentId) {
|
|
||||||
$total = count($rankable);
|
|
||||||
return [
|
|
||||||
'position' => $position,
|
|
||||||
'total' => $total,
|
|
||||||
'display' => $this->formatOrdinal($position) . ' of ' . $total,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$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
|
private function formatOrdinal(?int $value): string
|
||||||
{
|
{
|
||||||
$n = (int)$value;
|
$n = (int)$value;
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Controllers\View;
|
||||||
|
|
||||||
|
use App\Controllers\BaseController;
|
||||||
|
use App\Libraries\Tuition\TuitionForecastService;
|
||||||
|
|
||||||
|
class TuitionForecastController extends BaseController
|
||||||
|
{
|
||||||
|
protected TuitionForecastService $forecastService;
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->forecastService = new TuitionForecastService();
|
||||||
|
helper(['url']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function index()
|
||||||
|
{
|
||||||
|
$schoolYear = trim((string) ($this->request->getGet('school_year') ?? ''));
|
||||||
|
$semester = trim((string) ($this->request->getGet('semester') ?? ''));
|
||||||
|
$mode = (string) ($this->request->getGet('calculator_mode') ?? 'compare');
|
||||||
|
$filters = $this->buildOptionsFromRequest('get');
|
||||||
|
$result = $this->forecastService->calculate($schoolYear, $semester, $mode, $filters);
|
||||||
|
|
||||||
|
return view('administrator/tuition_forecast', [
|
||||||
|
'title' => 'Tuition Collection Forecast',
|
||||||
|
'schoolYears' => $this->forecastService->getAvailableSchoolYears(),
|
||||||
|
'semesters' => $this->forecastService->getAvailableSemesters(),
|
||||||
|
'filters' => [
|
||||||
|
'school_year' => $result['school_year'],
|
||||||
|
'semester' => $result['semester'],
|
||||||
|
'calculator_mode' => $result['calculator_mode'],
|
||||||
|
] + $result['options'],
|
||||||
|
'result' => $result,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function calculate()
|
||||||
|
{
|
||||||
|
$schoolYear = trim((string) ($this->request->getPost('school_year') ?? ''));
|
||||||
|
$semester = trim((string) ($this->request->getPost('semester') ?? ''));
|
||||||
|
$mode = (string) ($this->request->getPost('calculator_mode') ?? 'compare');
|
||||||
|
|
||||||
|
return $this->response->setJSON(
|
||||||
|
$this->forecastService->calculate($schoolYear, $semester, $mode, $this->buildOptionsFromRequest('post'))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function exportCsv()
|
||||||
|
{
|
||||||
|
$schoolYear = trim((string) ($this->request->getGet('school_year') ?? ''));
|
||||||
|
$semester = trim((string) ($this->request->getGet('semester') ?? ''));
|
||||||
|
$mode = (string) ($this->request->getGet('calculator_mode') ?? 'compare');
|
||||||
|
$result = $this->forecastService->calculate($schoolYear, $semester, $mode, $this->buildOptionsFromRequest('get'));
|
||||||
|
|
||||||
|
$filename = sprintf(
|
||||||
|
'tuition_forecast_%s_%s_%s.csv',
|
||||||
|
preg_replace('/[^A-Za-z0-9_-]+/', '-', $result['school_year']) ?: 'school-year',
|
||||||
|
preg_replace('/[^A-Za-z0-9_-]+/', '-', $result['semester']) ?: 'all-year',
|
||||||
|
$result['calculator_mode']
|
||||||
|
);
|
||||||
|
|
||||||
|
$handle = fopen('php://temp', 'w+');
|
||||||
|
if ($handle === false) {
|
||||||
|
throw new \RuntimeException('Unable to create CSV export.');
|
||||||
|
}
|
||||||
|
|
||||||
|
fputcsv($handle, ['School Year', $result['school_year']]);
|
||||||
|
fputcsv($handle, ['Semester', $result['semester'] !== '' ? $result['semester'] : 'All Year']);
|
||||||
|
fputcsv($handle, ['Calculator Mode', $result['calculator_mode']]);
|
||||||
|
fputcsv($handle, []);
|
||||||
|
fputcsv($handle, ['Summary']);
|
||||||
|
fputcsv($handle, ['Families', 'Students', 'Billable Students', 'Grade Unit Price', 'Youth Unit Price', 'Old Projected Income', 'New Projected Income', 'Difference']);
|
||||||
|
fputcsv($handle, [
|
||||||
|
$result['summary']['family_count'],
|
||||||
|
$result['summary']['student_count'],
|
||||||
|
$result['summary']['billable_student_count'],
|
||||||
|
$result['summary']['unit_price'],
|
||||||
|
$result['summary']['youth_unit_price'],
|
||||||
|
$result['summary']['old_projected_income'] ?? $result['summary']['old_projected_tuition'],
|
||||||
|
$result['summary']['new_projected_income'] ?? $result['summary']['new_projected_tuition'],
|
||||||
|
$result['summary']['difference'],
|
||||||
|
]);
|
||||||
|
fputcsv($handle, []);
|
||||||
|
fputcsv($handle, ['Families']);
|
||||||
|
fputcsv($handle, ['Parent/Family', 'Student Count', 'Billable Student Count', 'Old Tuition Total', 'New Tuition Total', 'Difference', 'Warnings']);
|
||||||
|
|
||||||
|
foreach ($result['families'] as $family) {
|
||||||
|
fputcsv($handle, [
|
||||||
|
$family['parent_name'] ?? '',
|
||||||
|
$family['student_count'] ?? 0,
|
||||||
|
$family['billable_student_count'] ?? 0,
|
||||||
|
$family['old_total'] ?? '0.00',
|
||||||
|
$family['new_total'] ?? '0.00',
|
||||||
|
$family['difference'] ?? '0.00',
|
||||||
|
implode(' | ', $family['warnings'] ?? []),
|
||||||
|
]);
|
||||||
|
|
||||||
|
fputcsv($handle, ['Student Name', 'Grade', 'Billable', 'Excluded Reason', 'Old Rule', 'Old Amount', 'New Rule', 'New Amount']);
|
||||||
|
foreach ($family['student_details'] as $detail) {
|
||||||
|
fputcsv($handle, [
|
||||||
|
$detail['student_name'] ?? '',
|
||||||
|
$detail['grade_level'] ?? '',
|
||||||
|
!empty($detail['billable']) ? 'Yes' : 'No',
|
||||||
|
$detail['excluded_reason'] ?? '',
|
||||||
|
$detail['old_rule'] ?? '',
|
||||||
|
$detail['old_amount'] ?? '0.00',
|
||||||
|
$detail['new_rule'] ?? '',
|
||||||
|
$detail['new_amount'] ?? '0.00',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
fputcsv($handle, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
rewind($handle);
|
||||||
|
$csv = stream_get_contents($handle) ?: '';
|
||||||
|
fclose($handle);
|
||||||
|
|
||||||
|
return $this->response
|
||||||
|
->setHeader('Content-Type', 'text/csv; charset=UTF-8')
|
||||||
|
->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"')
|
||||||
|
->setBody($csv);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function buildOptionsFromRequest(string $method): array
|
||||||
|
{
|
||||||
|
$source = $method === 'post' ? 'getPost' : 'getGet';
|
||||||
|
|
||||||
|
return [
|
||||||
|
'include_withdrawn_mode' => (string) ($this->request->{$source}('include_withdrawn_mode') ?? 'refund_deadline'),
|
||||||
|
'include_payment_pending' => $this->request->{$source}('include_payment_pending') ?? '0',
|
||||||
|
'include_event_only' => $this->request->{$source}('include_event_only') ?? '0',
|
||||||
|
'include_paid_invoices' => $this->request->{$source}('include_paid_invoices') ?? '0',
|
||||||
|
'unit_price' => $this->request->{$source}('unit_price') ?? '',
|
||||||
|
'youth_unit_price' => $this->request->{$source}('youth_unit_price') ?? '',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Database\Migrations;
|
||||||
|
|
||||||
|
use CodeIgniter\Database\Migration;
|
||||||
|
|
||||||
|
class FinancialSystemLedgerCleanup extends Migration
|
||||||
|
{
|
||||||
|
public function up()
|
||||||
|
{
|
||||||
|
$this->addInstallmentSequenceColumn();
|
||||||
|
$this->ensureIndexes();
|
||||||
|
$this->ensureConfigurationDefaults();
|
||||||
|
$this->archivePaypalTables();
|
||||||
|
$this->refreshFinancialNavItems();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down()
|
||||||
|
{
|
||||||
|
$this->restorePaypalTables();
|
||||||
|
|
||||||
|
if ($this->db->tableExists('payments') && $this->db->fieldExists('installment_seq', 'payments')) {
|
||||||
|
$this->forge->dropColumn('payments', 'installment_seq');
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->dropIndexIfExists('payments', 'idx_payments_invoice_id');
|
||||||
|
$this->dropIndexIfExists('payments', 'idx_payments_parent_year_semester');
|
||||||
|
$this->dropIndexIfExists('payments', 'uniq_payments_transaction_id');
|
||||||
|
$this->dropIndexIfExists('invoices', 'idx_invoices_parent_year_semester');
|
||||||
|
$this->dropIndexIfExists('discount_usages', 'idx_discount_usages_invoice_id');
|
||||||
|
$this->dropIndexIfExists('discount_usages', 'idx_discount_usages_parent_year_semester');
|
||||||
|
$this->dropIndexIfExists('refunds', 'idx_refunds_invoice_id');
|
||||||
|
$this->dropIndexIfExists('refunds', 'idx_refunds_parent_year_semester_status');
|
||||||
|
$this->dropIndexIfExists('additional_charges', 'idx_additional_charges_invoice_id');
|
||||||
|
$this->dropIndexIfExists('additional_charges', 'idx_additional_charges_parent_year_semester_status');
|
||||||
|
$this->dropIndexIfExists('invoice_event', 'idx_invoice_event_invoice_id');
|
||||||
|
|
||||||
|
if ($this->db->tableExists('nav_items')) {
|
||||||
|
$forecastRow = $this->db->table('nav_items')
|
||||||
|
->select('id')
|
||||||
|
->where('url', 'administrator/tuition-forecast')
|
||||||
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
|
||||||
|
if ($forecastRow && $this->db->tableExists('role_nav_items')) {
|
||||||
|
$this->db->table('role_nav_items')
|
||||||
|
->where('nav_item_id', (int) $forecastRow['id'])
|
||||||
|
->delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->db->table('nav_items')
|
||||||
|
->where('url', 'administrator/tuition-forecast')
|
||||||
|
->delete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function addInstallmentSequenceColumn(): void
|
||||||
|
{
|
||||||
|
if ($this->db->tableExists('payments') && !$this->db->fieldExists('installment_seq', 'payments')) {
|
||||||
|
$this->forge->addColumn('payments', [
|
||||||
|
'installment_seq' => [
|
||||||
|
'type' => 'INT',
|
||||||
|
'constraint' => 11,
|
||||||
|
'null' => true,
|
||||||
|
'after' => 'number_of_installments',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function ensureIndexes(): void
|
||||||
|
{
|
||||||
|
$this->addIndexIfMissing('payments', 'idx_payments_invoice_id', ['invoice_id']);
|
||||||
|
$this->addIndexIfMissing('payments', 'idx_payments_parent_year_semester', ['parent_id', 'school_year', 'semester']);
|
||||||
|
$this->addIndexIfMissing('invoices', 'idx_invoices_parent_year_semester', ['parent_id', 'school_year', 'semester']);
|
||||||
|
$this->addIndexIfMissing('discount_usages', 'idx_discount_usages_invoice_id', ['invoice_id']);
|
||||||
|
$this->addIndexIfMissing('discount_usages', 'idx_discount_usages_parent_year_semester', ['parent_id', 'school_year', 'semester']);
|
||||||
|
$this->addIndexIfMissing('refunds', 'idx_refunds_invoice_id', ['invoice_id']);
|
||||||
|
$this->addIndexIfMissing('refunds', 'idx_refunds_parent_year_semester_status', ['parent_id', 'school_year', 'semester', 'status']);
|
||||||
|
$this->addIndexIfMissing('additional_charges', 'idx_additional_charges_invoice_id', ['invoice_id']);
|
||||||
|
$this->addIndexIfMissing('additional_charges', 'idx_additional_charges_parent_year_semester_status', ['parent_id', 'school_year', 'semester', 'status']);
|
||||||
|
$this->addIndexIfMissing('invoice_event', 'idx_invoice_event_invoice_id', ['invoice_id']);
|
||||||
|
|
||||||
|
if ($this->db->tableExists('payments') && $this->db->fieldExists('transaction_id', 'payments') && !$this->hasDuplicateTransactionIds()) {
|
||||||
|
$this->addIndexIfMissing('payments', 'uniq_payments_transaction_id', ['transaction_id'], true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function ensureConfigurationDefaults(): void
|
||||||
|
{
|
||||||
|
if (!$this->db->tableExists('configuration')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$defaults = [
|
||||||
|
'tuition_calculator_version' => 'old',
|
||||||
|
'youth_fee' => '200.00',
|
||||||
|
'new_tuition_full_amount' => '370.00',
|
||||||
|
'new_tuition_youth_amount' => '200.00',
|
||||||
|
'new_tuition_second_student_discount' => '50.00',
|
||||||
|
'new_tuition_third_student_discount' => '50.00',
|
||||||
|
'new_tuition_fourth_plus_discount' => '100.00',
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($defaults as $key => $value) {
|
||||||
|
$row = $this->db->table('configuration')
|
||||||
|
->select('id, config_value')
|
||||||
|
->where('config_key', $key)
|
||||||
|
->orderBy('id', 'ASC')
|
||||||
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
|
||||||
|
if (!$row) {
|
||||||
|
$this->db->table('configuration')->insert([
|
||||||
|
'config_key' => $key,
|
||||||
|
'config_value' => $value,
|
||||||
|
]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trim((string) ($row['config_value'] ?? '')) === '') {
|
||||||
|
$this->db->table('configuration')
|
||||||
|
->where('config_key', $key)
|
||||||
|
->update(['config_value' => $value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function archivePaypalTables(): void
|
||||||
|
{
|
||||||
|
$this->renameTableIfPresent('paypal_payments', 'archived_paypal_payments');
|
||||||
|
$this->renameTableIfPresent('paypal_transactions', 'archived_paypal_transactions');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function restorePaypalTables(): void
|
||||||
|
{
|
||||||
|
$this->renameTableIfPresent('archived_paypal_payments', 'paypal_payments');
|
||||||
|
$this->renameTableIfPresent('archived_paypal_transactions', 'paypal_transactions');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function refreshFinancialNavItems(): void
|
||||||
|
{
|
||||||
|
if (!$this->db->tableExists('nav_items')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$parentColumn = null;
|
||||||
|
if ($this->db->fieldExists('menu_parent_id', 'nav_items')) {
|
||||||
|
$parentColumn = 'menu_parent_id';
|
||||||
|
} elseif ($this->db->fieldExists('parent_id', 'nav_items')) {
|
||||||
|
$parentColumn = 'parent_id';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($parentColumn === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->db->table('nav_items')
|
||||||
|
->groupStart()
|
||||||
|
->where('url', 'administrator/paypal_transactions')
|
||||||
|
->orWhere('url', 'admin/paypal-transactions')
|
||||||
|
->orWhere('label', 'PaypalTransactions')
|
||||||
|
->orWhere('label', 'PayPal Transactions')
|
||||||
|
->groupEnd()
|
||||||
|
->delete();
|
||||||
|
|
||||||
|
$financialRow = $this->db->table('nav_items')
|
||||||
|
->select('id')
|
||||||
|
->where('label', 'Financial')
|
||||||
|
->where($parentColumn, null)
|
||||||
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
|
||||||
|
if (!$financialRow) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$forecastUrl = 'administrator/tuition-forecast';
|
||||||
|
$existing = $this->db->table('nav_items')
|
||||||
|
->select('id')
|
||||||
|
->where('url', $forecastUrl)
|
||||||
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
|
||||||
|
if ($existing) {
|
||||||
|
$forecastId = (int) $existing['id'];
|
||||||
|
} else {
|
||||||
|
$this->db->table('nav_items')->insert([
|
||||||
|
$parentColumn => (int) $financialRow['id'],
|
||||||
|
'label' => 'Tuition Forecast',
|
||||||
|
'url' => $forecastUrl,
|
||||||
|
'sort_order' => 4,
|
||||||
|
'is_enabled' => 1,
|
||||||
|
'created_at' => date('Y-m-d H:i:s'),
|
||||||
|
'updated_at' => date('Y-m-d H:i:s'),
|
||||||
|
]);
|
||||||
|
$forecastId = (int) $this->db->insertID();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($forecastId <= 0 || !$this->db->tableExists('role_nav_items') || !$this->db->tableExists('roles')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$roles = $this->db->table('roles')
|
||||||
|
->select('id')
|
||||||
|
->whereIn('name', ['administrator', 'administrative staff', 'principal', 'vice_principal', 'head of department (finance)'])
|
||||||
|
->get()
|
||||||
|
->getResultArray();
|
||||||
|
|
||||||
|
foreach ($roles as $role) {
|
||||||
|
$roleId = (int) ($role['id'] ?? 0);
|
||||||
|
if ($roleId <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$exists = $this->db->table('role_nav_items')
|
||||||
|
->where('role_id', $roleId)
|
||||||
|
->where('nav_item_id', $forecastId)
|
||||||
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
|
||||||
|
if ($exists) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->db->table('role_nav_items')->insert([
|
||||||
|
'role_id' => $roleId,
|
||||||
|
'nav_item_id' => $forecastId,
|
||||||
|
'created_at' => date('Y-m-d H:i:s'),
|
||||||
|
'updated_at' => date('Y-m-d H:i:s'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function renameTableIfPresent(string $from, string $to): void
|
||||||
|
{
|
||||||
|
if (!$this->db->tableExists($from) || $this->db->tableExists($to)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->db->query(sprintf('RENAME TABLE `%s` TO `%s`', $from, $to));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function addIndexIfMissing(string $table, string $indexName, array $columns, bool $unique = false): void
|
||||||
|
{
|
||||||
|
if (!$this->db->tableExists($table) || $this->indexExists($table, $indexName)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$quotedColumns = implode(', ', array_map(static fn (string $column): string => '`' . $column . '`', $columns));
|
||||||
|
$type = $unique ? 'UNIQUE INDEX' : 'INDEX';
|
||||||
|
$sql = sprintf('ALTER TABLE `%s` ADD %s `%s` (%s)', $table, $type, $indexName, $quotedColumns);
|
||||||
|
$this->db->query($sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function dropIndexIfExists(string $table, string $indexName): void
|
||||||
|
{
|
||||||
|
if (!$this->db->tableExists($table) || !$this->indexExists($table, $indexName)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->db->query(sprintf('ALTER TABLE `%s` DROP INDEX `%s`', $table, $indexName));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function indexExists(string $table, string $indexName): bool
|
||||||
|
{
|
||||||
|
if (!$this->db->tableExists($table)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows = $this->db->query(sprintf('SHOW INDEX FROM `%s`', $table))->getResultArray();
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
if (($row['Key_name'] ?? null) === $indexName) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function hasDuplicateTransactionIds(): bool
|
||||||
|
{
|
||||||
|
$row = $this->db->table('payments')
|
||||||
|
->select('transaction_id')
|
||||||
|
->where('transaction_id IS NOT NULL', null, false)
|
||||||
|
->where('transaction_id !=', '')
|
||||||
|
->groupBy('transaction_id')
|
||||||
|
->having('COUNT(*) >', 1, false)
|
||||||
|
->get(1)
|
||||||
|
->getRowArray();
|
||||||
|
|
||||||
|
return $row !== null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Database\Migrations;
|
||||||
|
|
||||||
|
use CodeIgniter\Database\Migration;
|
||||||
|
|
||||||
|
class UpdateYouthTuitionDefaults extends Migration
|
||||||
|
{
|
||||||
|
public function up()
|
||||||
|
{
|
||||||
|
if (!$this->db->tableExists('configuration')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->upsertConfig('youth_fee', '200.00', ['180', '180.00']);
|
||||||
|
$this->upsertConfig('new_tuition_youth_amount', '200.00', ['180', '180.00']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down()
|
||||||
|
{
|
||||||
|
if (!$this->db->tableExists('configuration')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->rollbackConfig('youth_fee', '180.00');
|
||||||
|
$this->rollbackConfig('new_tuition_youth_amount', '180.00');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function upsertConfig(string $key, string $value, array $legacyValues = []): void
|
||||||
|
{
|
||||||
|
$row = $this->db->table('configuration')
|
||||||
|
->select('id, config_value')
|
||||||
|
->where('config_key', $key)
|
||||||
|
->orderBy('id', 'ASC')
|
||||||
|
->get()
|
||||||
|
->getRowArray();
|
||||||
|
|
||||||
|
if (!$row) {
|
||||||
|
$this->db->table('configuration')->insert([
|
||||||
|
'config_key' => $key,
|
||||||
|
'config_value' => $value,
|
||||||
|
]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$current = trim((string) ($row['config_value'] ?? ''));
|
||||||
|
if ($current === '' || in_array($current, $legacyValues, true)) {
|
||||||
|
$this->db->table('configuration')
|
||||||
|
->where('config_key', $key)
|
||||||
|
->update(['config_value' => $value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function rollbackConfig(string $key, string $value): void
|
||||||
|
{
|
||||||
|
$this->db->table('configuration')
|
||||||
|
->where('config_key', $key)
|
||||||
|
->where('config_value', '200.00')
|
||||||
|
->update(['config_value' => $value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -86,9 +86,9 @@ class NavSeeder extends Seeder
|
|||||||
['parent'=>'Financial','label'=>'Discount Management','url'=>'discounts/list','sort_order'=>1],
|
['parent'=>'Financial','label'=>'Discount Management','url'=>'discounts/list','sort_order'=>1],
|
||||||
['parent'=>'Financial','label'=>'Expenses Management','url'=>'expenses/index','sort_order'=>2],
|
['parent'=>'Financial','label'=>'Expenses Management','url'=>'expenses/index','sort_order'=>2],
|
||||||
['parent'=>'Financial','label'=>'Financial Report','url'=>'payment/financial_report','sort_order'=>3],
|
['parent'=>'Financial','label'=>'Financial Report','url'=>'payment/financial_report','sort_order'=>3],
|
||||||
['parent'=>'Financial','label'=>'Invoices Management','url'=>'invoice_payment/invoice_management','sort_order'=>4],
|
['parent'=>'Financial','label'=>'Tuition Forecast','url'=>'administrator/tuition-forecast','sort_order'=>4],
|
||||||
['parent'=>'Financial','label'=>'Manual Payment','url'=>'payment/manual_pay','sort_order'=>5],
|
['parent'=>'Financial','label'=>'Invoices Management','url'=>'invoice_payment/invoice_management','sort_order'=>5],
|
||||||
['parent'=>'Financial','label'=>'PaypalTransactions','url'=>'administrator/paypal_transactions','sort_order'=>6],
|
['parent'=>'Financial','label'=>'Manual Payment','url'=>'payment/manual_pay','sort_order'=>6],
|
||||||
['parent'=>'Financial','label'=>'Refund Management','url'=>'refunds/list','sort_order'=>7],
|
['parent'=>'Financial','label'=>'Refund Management','url'=>'refunds/list','sort_order'=>7],
|
||||||
['parent'=>'Financial','label'=>'Reimbursement Management','url'=>'reimbursements/index','sort_order'=>8],
|
['parent'=>'Financial','label'=>'Reimbursement Management','url'=>'reimbursements/index','sort_order'=>8],
|
||||||
|
|
||||||
|
|||||||
+79
-26
@@ -35,7 +35,7 @@ class AuthFilter implements FilterInterface
|
|||||||
public function before(RequestInterface $request, $arguments = null)
|
public function before(RequestInterface $request, $arguments = null)
|
||||||
{
|
{
|
||||||
$session = session();
|
$session = session();
|
||||||
$userRoles = $session->get('roles'); // not used here, but keep if other code expects it
|
$userRoles = $session->get('roles');
|
||||||
$userId = $session->get('user_id');
|
$userId = $session->get('user_id');
|
||||||
$loginTime = (int) $session->get('login_time');
|
$loginTime = (int) $session->get('login_time');
|
||||||
|
|
||||||
@@ -66,35 +66,16 @@ class AuthFilter implements FilterInterface
|
|||||||
return $this->deny($request, "You don't have permission to use this feature.");
|
return $this->deny($request, "You don't have permission to use this feature.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Route arguments: ['filter' => 'auth:permission_name|alt_permission,update']
|
[$requirements, $crudAction] = $this->parseRequirements($arguments);
|
||||||
// Route arguments patterns supported:
|
|
||||||
// auth -> default 'read'
|
|
||||||
// auth:read -> CRUD only
|
|
||||||
// auth:create -> CRUD only
|
|
||||||
// auth:update -> CRUD only
|
|
||||||
// auth:delete -> CRUD only
|
|
||||||
// auth:permA|permB,read -> permission + CRUD
|
|
||||||
$requiredPermission = null;
|
|
||||||
$crudAction = 'read';
|
|
||||||
|
|
||||||
if (!empty($arguments)) {
|
if (!empty($requirements)) {
|
||||||
$arg0 = strtolower((string) $arguments[0]);
|
if ($this->matchesAnyRequirement($requirements, $crudAction, $roleIds, (array) $userRoles)) {
|
||||||
|
return;
|
||||||
// If only one argument and it's a CRUD keyword, treat as CRUD-only
|
|
||||||
if (count($arguments) === 1 && in_array($arg0, ['create', 'read', 'update', 'delete'], true)) {
|
|
||||||
$crudAction = $arg0;
|
|
||||||
} else {
|
|
||||||
// Otherwise, first arg is permission(s); optional second is CRUD
|
|
||||||
$requiredPermission = $arguments[0]; // e.g., 'edit_student|manage_students'
|
|
||||||
$crudAction = isset($arguments[1]) ? strtolower((string) $arguments[1]) : 'read';
|
|
||||||
if (!in_array($crudAction, ['create', 'read', 'update', 'delete'], true)) {
|
|
||||||
$crudAction = 'read';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return $this->deny($request, "You don't have permission to use this feature.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// No explicit route permission: fall back to menu rules
|
|
||||||
if ($this->isAllowedByMenu($request, $roleIds)) {
|
if ($this->isAllowedByMenu($request, $roleIds)) {
|
||||||
return; // ✅ allowed
|
return; // ✅ allowed
|
||||||
}
|
}
|
||||||
@@ -126,6 +107,78 @@ class AuthFilter implements FilterInterface
|
|||||||
->with('error', 'Your session has expired. Please log in again.');
|
->with('error', 'Your session has expired. Please log in again.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function parseRequirements(?array $arguments): array
|
||||||
|
{
|
||||||
|
if (empty($arguments)) {
|
||||||
|
return [[], 'read'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$tokens = array_values(array_filter(array_map(static fn($value) => trim((string) $value), $arguments), static fn($value) => $value !== ''));
|
||||||
|
if (empty($tokens)) {
|
||||||
|
return [[], 'read'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$crudAction = 'read';
|
||||||
|
$last = strtolower((string) end($tokens));
|
||||||
|
if (in_array($last, ['create', 'read', 'update', 'delete'], true)) {
|
||||||
|
$crudAction = array_pop($tokens);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count($tokens) === 1 && in_array(strtolower($tokens[0]), ['create', 'read', 'update', 'delete'], true)) {
|
||||||
|
return [[], strtolower($tokens[0])];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [$tokens, strtolower((string) $crudAction)];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function matchesAnyRequirement(array $requirements, string $crudAction, array $roleIds, array $sessionRoles): bool
|
||||||
|
{
|
||||||
|
$normalizedRoles = array_map(static fn($role) => strtolower(trim((string) $role)), $sessionRoles);
|
||||||
|
|
||||||
|
foreach ($requirements as $requirement) {
|
||||||
|
$alternatives = array_values(array_filter(array_map(static fn($value) => trim((string) $value), explode('|', (string) $requirement))));
|
||||||
|
if (empty($alternatives)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($alternatives as $alternative) {
|
||||||
|
$candidate = strtolower($alternative);
|
||||||
|
if (in_array($candidate, $normalizedRoles, true)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->userHasNamedPermission($roleIds, $alternative, $crudAction)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function userHasNamedPermission(array $roleIds, string $permissionName, string $crudAction): bool
|
||||||
|
{
|
||||||
|
if (empty($roleIds)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows = $this->db->table('role_permissions rp')
|
||||||
|
->join('permissions p', 'p.id = rp.permission_id')
|
||||||
|
->select('rp.*')
|
||||||
|
->whereIn('rp.role_id', $roleIds)
|
||||||
|
->where('LOWER(p.name)', strtolower($permissionName))
|
||||||
|
->get()
|
||||||
|
->getResultArray();
|
||||||
|
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
if ($this->hasPermission($row, $crudAction)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
|
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
|
||||||
{
|
{
|
||||||
// No-op
|
// No-op
|
||||||
|
|||||||
@@ -47,6 +47,28 @@ if (!function_exists('attendance_comment_template_for_score')) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return attendance_comment_template_match($templates, $score);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!function_exists('attendance_comment_template_match')) {
|
||||||
|
function attendance_comment_template_match(array $templates, float $score): ?array
|
||||||
|
{
|
||||||
|
if ($templates === []) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attendance scores are percentage values; clamp to the expected domain
|
||||||
|
// so minor calculation drift above 100 or below 0 does not skip a template.
|
||||||
|
$score = max(0.0, min(100.0, $score));
|
||||||
|
|
||||||
|
usort($templates, static function (array $a, array $b): int {
|
||||||
|
$aMin = isset($a['min_score']) ? (float) $a['min_score'] : 0.0;
|
||||||
|
$bMin = isset($b['min_score']) ? (float) $b['min_score'] : 0.0;
|
||||||
|
|
||||||
|
return $aMin <=> $bMin;
|
||||||
|
});
|
||||||
|
|
||||||
foreach ($templates as $template) {
|
foreach ($templates as $template) {
|
||||||
$min = isset($template['min_score']) ? (float) $template['min_score'] : 0.0;
|
$min = isset($template['min_score']) ? (float) $template['min_score'] : 0.0;
|
||||||
$max = isset($template['max_score']) ? (float) $template['max_score'] : 100.0;
|
$max = isset($template['max_score']) ? (float) $template['max_score'] : 100.0;
|
||||||
@@ -55,6 +77,18 @@ if (!function_exists('attendance_comment_template_for_score')) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
// Some configured bands use integer boundaries like 60-69 and 70-79,
|
||||||
|
// while attendance scores contain decimals like 69.23. When the score
|
||||||
|
// lands in that fractional gap, fall back to the nearest lower band.
|
||||||
|
$candidate = null;
|
||||||
|
foreach ($templates as $template) {
|
||||||
|
$min = isset($template['min_score']) ? (float) $template['min_score'] : 0.0;
|
||||||
|
if ($score < $min) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
$candidate = $template;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $candidate;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Interfaces;
|
||||||
|
|
||||||
|
interface TuitionCalculatorInterface
|
||||||
|
{
|
||||||
|
public function calculateFamilyTuition(array $students, array $config): array;
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Libraries;
|
||||||
|
|
||||||
|
use CodeIgniter\Files\File;
|
||||||
|
use CodeIgniter\HTTP\Files\UploadedFile;
|
||||||
|
|
||||||
|
final class FinancialAttachmentService
|
||||||
|
{
|
||||||
|
private const MAX_BYTES = 5242880;
|
||||||
|
private const ALLOWED_MIMES = [
|
||||||
|
'application/pdf',
|
||||||
|
'image/jpeg',
|
||||||
|
'image/png',
|
||||||
|
];
|
||||||
|
private const ALLOWED_EXTENSIONS = [
|
||||||
|
'jpg',
|
||||||
|
'jpeg',
|
||||||
|
'pdf',
|
||||||
|
'png',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function saveUploadedFile($file, string $subdir): ?string
|
||||||
|
{
|
||||||
|
if (!$file instanceof UploadedFile) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$file->isValid() || $file->hasMoved()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$size = (int) ($file->getSize() ?? 0);
|
||||||
|
if ($size <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$mime = strtolower((string) $file->getMimeType());
|
||||||
|
$ext = strtolower((string) $file->getClientExtension());
|
||||||
|
|
||||||
|
if (!in_array($mime, self::ALLOWED_MIMES, true) || !in_array($ext, self::ALLOWED_EXTENSIONS, true)) {
|
||||||
|
throw new \RuntimeException('Unsupported file type. Use PDF, JPG, or PNG.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($size > self::MAX_BYTES) {
|
||||||
|
throw new \RuntimeException('File too large. Maximum size is 5 MB.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$dir = $this->ensureSubdir($subdir);
|
||||||
|
$name = $file->getRandomName();
|
||||||
|
$file->move($dir, $name);
|
||||||
|
|
||||||
|
return $name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function resolvePath(string $subdir, string $filename): ?string
|
||||||
|
{
|
||||||
|
$safeName = basename($filename);
|
||||||
|
if ($safeName === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$path = $this->ensureSubdir($subdir) . DIRECTORY_SEPARATOR . $safeName;
|
||||||
|
|
||||||
|
return is_file($path) ? $path : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function ensureSubdir(string $subdir): string
|
||||||
|
{
|
||||||
|
$path = WRITEPATH . 'uploads' . DIRECTORY_SEPARATOR . trim($subdir, '/');
|
||||||
|
if (!is_dir($path) && !mkdir($path, 0775, true) && !is_dir($path)) {
|
||||||
|
throw new \RuntimeException('Unable to prepare upload directory.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $path;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function detectMime(string $path): string
|
||||||
|
{
|
||||||
|
if (function_exists('finfo_open')) {
|
||||||
|
$handle = finfo_open(FILEINFO_MIME_TYPE);
|
||||||
|
if ($handle) {
|
||||||
|
$mime = finfo_file($handle, $path);
|
||||||
|
finfo_close($handle);
|
||||||
|
if (is_string($mime) && $mime !== '') {
|
||||||
|
return $mime;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (function_exists('mime_content_type')) {
|
||||||
|
$mime = mime_content_type($path);
|
||||||
|
if (is_string($mime) && $mime !== '') {
|
||||||
|
return $mime;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'application/octet-stream';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Libraries;
|
||||||
|
|
||||||
|
final class FinancialStatus
|
||||||
|
{
|
||||||
|
public const INVOICE_UNPAID = 'unpaid';
|
||||||
|
public const INVOICE_PARTIALLY_PAID = 'partially_paid';
|
||||||
|
public const INVOICE_PAID = 'paid';
|
||||||
|
|
||||||
|
public const PAYMENT_RECORDED = 'recorded';
|
||||||
|
public const PAYMENT_VOIDED = 'voided';
|
||||||
|
public const PAYMENT_FAILED = 'failed';
|
||||||
|
public const PAYMENT_REFUNDED = 'refunded';
|
||||||
|
public const PAYMENT_CHARGEBACK = 'chargeback';
|
||||||
|
public const PAYMENT_DECLINED = 'declined';
|
||||||
|
public const PAYMENT_REVERSED = 'reversed';
|
||||||
|
public const PAYMENT_CANCELED = 'canceled';
|
||||||
|
public const PAYMENT_CANCELLED = 'cancelled';
|
||||||
|
|
||||||
|
public const REFUND_PENDING = 'pending';
|
||||||
|
public const REFUND_APPROVED = 'approved';
|
||||||
|
public const REFUND_REJECTED = 'rejected';
|
||||||
|
public const REFUND_PARTIALLY_PAID = 'partially_paid';
|
||||||
|
public const REFUND_PAID = 'paid';
|
||||||
|
public const REFUND_VOIDED = 'voided';
|
||||||
|
|
||||||
|
public const ADDITIONAL_CHARGE_PENDING = 'pending';
|
||||||
|
public const ADDITIONAL_CHARGE_APPLIED = 'applied';
|
||||||
|
public const ADDITIONAL_CHARGE_VOIDED = 'voided';
|
||||||
|
|
||||||
|
public const EXCLUDED_PAYMENT_STATUSES = [
|
||||||
|
self::PAYMENT_VOIDED,
|
||||||
|
self::PAYMENT_FAILED,
|
||||||
|
self::PAYMENT_REFUNDED,
|
||||||
|
self::PAYMENT_CHARGEBACK,
|
||||||
|
self::PAYMENT_DECLINED,
|
||||||
|
self::PAYMENT_REVERSED,
|
||||||
|
self::PAYMENT_CANCELED,
|
||||||
|
self::PAYMENT_CANCELLED,
|
||||||
|
'void',
|
||||||
|
];
|
||||||
|
|
||||||
|
public const REFUND_REDUCES_INVOICE_STATUSES = [
|
||||||
|
self::REFUND_PARTIALLY_PAID,
|
||||||
|
self::REFUND_PAID,
|
||||||
|
'partial',
|
||||||
|
'paid',
|
||||||
|
'Partial',
|
||||||
|
'Paid',
|
||||||
|
];
|
||||||
|
|
||||||
|
public static function normalizeInvoiceStatus(?string $status): string
|
||||||
|
{
|
||||||
|
return match (self::normalize($status)) {
|
||||||
|
'paid', 'full' => self::INVOICE_PAID,
|
||||||
|
'partially paid', 'partially_paid', 'partial' => self::INVOICE_PARTIALLY_PAID,
|
||||||
|
default => self::INVOICE_UNPAID,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function normalizePaymentStatus(?string $status): string
|
||||||
|
{
|
||||||
|
return match (self::normalize($status)) {
|
||||||
|
'completed', 'paid', 'full', 'recorded' => self::PAYMENT_RECORDED,
|
||||||
|
'void', 'voided' => self::PAYMENT_VOIDED,
|
||||||
|
'failed' => self::PAYMENT_FAILED,
|
||||||
|
'refunded' => self::PAYMENT_REFUNDED,
|
||||||
|
'chargeback' => self::PAYMENT_CHARGEBACK,
|
||||||
|
'declined' => self::PAYMENT_DECLINED,
|
||||||
|
'reversed' => self::PAYMENT_REVERSED,
|
||||||
|
'cancelled' => self::PAYMENT_CANCELLED,
|
||||||
|
'canceled' => self::PAYMENT_CANCELED,
|
||||||
|
default => self::normalize($status),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function normalizeRefundStatus(?string $status): string
|
||||||
|
{
|
||||||
|
return match (self::normalize($status)) {
|
||||||
|
'approved' => self::REFUND_APPROVED,
|
||||||
|
'rejected' => self::REFUND_REJECTED,
|
||||||
|
'partial', 'partially paid', 'partially_paid' => self::REFUND_PARTIALLY_PAID,
|
||||||
|
'paid', 'full' => self::REFUND_PAID,
|
||||||
|
'void', 'voided' => self::REFUND_VOIDED,
|
||||||
|
default => self::REFUND_PENDING,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function normalize(?string $status): string
|
||||||
|
{
|
||||||
|
$value = strtolower(trim((string) $status));
|
||||||
|
$value = str_replace('_', ' ', $value);
|
||||||
|
$value = preg_replace('/\s+/', ' ', $value) ?? $value;
|
||||||
|
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Libraries;
|
||||||
|
|
||||||
|
use App\Interfaces\TuitionCalculatorInterface;
|
||||||
|
use App\Libraries\Tuition\NewTuitionCalculatorService;
|
||||||
|
use App\Libraries\Tuition\OldTuitionCalculatorService;
|
||||||
|
use App\Models\AdditionalChargeModel;
|
||||||
|
use App\Models\ClassSectionModel;
|
||||||
|
use App\Models\ConfigurationModel;
|
||||||
|
use App\Models\DiscountUsageModel;
|
||||||
|
use App\Models\EnrollmentModel;
|
||||||
|
use App\Models\EventChargesModel;
|
||||||
|
use App\Models\InvoiceEventModel;
|
||||||
|
use App\Models\InvoiceModel;
|
||||||
|
use App\Models\PaymentModel;
|
||||||
|
use App\Models\RefundModel;
|
||||||
|
use App\Models\StudentClassModel;
|
||||||
|
use App\Models\StudentModel;
|
||||||
|
|
||||||
|
class InvoiceLedgerService
|
||||||
|
{
|
||||||
|
protected InvoiceModel $invoiceModel;
|
||||||
|
protected PaymentModel $paymentModel;
|
||||||
|
protected RefundModel $refundModel;
|
||||||
|
protected DiscountUsageModel $discountUsageModel;
|
||||||
|
protected AdditionalChargeModel $additionalChargeModel;
|
||||||
|
protected ConfigurationModel $configurationModel;
|
||||||
|
protected EnrollmentModel $enrollmentModel;
|
||||||
|
protected StudentClassModel $studentClassModel;
|
||||||
|
protected ClassSectionModel $classSectionModel;
|
||||||
|
protected EventChargesModel $eventChargesModel;
|
||||||
|
protected InvoiceEventModel $invoiceEventModel;
|
||||||
|
protected StudentModel $studentModel;
|
||||||
|
protected TuitionCalculatorInterface $oldCalculator;
|
||||||
|
protected TuitionCalculatorInterface $newCalculator;
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->invoiceModel = new InvoiceModel();
|
||||||
|
$this->paymentModel = new PaymentModel();
|
||||||
|
$this->refundModel = new RefundModel();
|
||||||
|
$this->discountUsageModel = new DiscountUsageModel();
|
||||||
|
$this->additionalChargeModel = new AdditionalChargeModel();
|
||||||
|
$this->configurationModel = new ConfigurationModel();
|
||||||
|
$this->enrollmentModel = new EnrollmentModel();
|
||||||
|
$this->studentClassModel = new StudentClassModel();
|
||||||
|
$this->classSectionModel = new ClassSectionModel();
|
||||||
|
$this->eventChargesModel = new EventChargesModel();
|
||||||
|
$this->invoiceEventModel = new InvoiceEventModel();
|
||||||
|
$this->studentModel = new StudentModel();
|
||||||
|
$this->oldCalculator = new OldTuitionCalculatorService();
|
||||||
|
$this->newCalculator = new NewTuitionCalculatorService();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function calculateInvoice(int $invoiceId): array
|
||||||
|
{
|
||||||
|
$invoice = $this->loadInvoice($invoiceId);
|
||||||
|
if ($invoice === null) {
|
||||||
|
throw new \RuntimeException('Invoice not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
$tuitionTotal = $this->calculateTuitionTotal($invoice);
|
||||||
|
$eventTotal = $this->calculateEventTotal($invoice);
|
||||||
|
$additionalTotal = $this->calculateAdditionalCharges($invoiceId);
|
||||||
|
$discountRawTotal = $this->calculateDiscounts($invoiceId);
|
||||||
|
$paidTotal = $this->calculateValidPayments($invoiceId);
|
||||||
|
$refundPaidTotal = $this->calculatePaidRefunds($invoiceId);
|
||||||
|
|
||||||
|
$tuitionCents = $this->toCents($tuitionTotal);
|
||||||
|
$eventCents = $this->toCents($eventTotal);
|
||||||
|
$additionalCents = $this->toCents($additionalTotal);
|
||||||
|
$discountRawCents = $this->toCents($discountRawTotal);
|
||||||
|
$paidCents = $this->toCents($paidTotal);
|
||||||
|
$refundPaidCents = $this->toCents($refundPaidTotal);
|
||||||
|
|
||||||
|
$discountBaseCents = max(0, $tuitionCents + $additionalCents);
|
||||||
|
$discountCents = min($discountRawCents, $discountBaseCents);
|
||||||
|
$totalAmountCents = $tuitionCents + $eventCents + $additionalCents;
|
||||||
|
$balanceCents = max(0, $totalAmountCents - $discountCents - $paidCents - $refundPaidCents);
|
||||||
|
|
||||||
|
if ($balanceCents === 0) {
|
||||||
|
$status = FinancialStatus::INVOICE_PAID;
|
||||||
|
} elseif ($paidCents > 0 || $discountCents > 0 || $refundPaidCents > 0) {
|
||||||
|
$status = FinancialStatus::INVOICE_PARTIALLY_PAID;
|
||||||
|
} else {
|
||||||
|
$status = FinancialStatus::INVOICE_UNPAID;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'invoice_id' => $invoiceId,
|
||||||
|
'tuition_total' => $this->fromCents($tuitionCents),
|
||||||
|
'event_total' => $this->fromCents($eventCents),
|
||||||
|
'additional_total' => $this->fromCents($additionalCents),
|
||||||
|
'discount_total' => $this->fromCents($discountCents),
|
||||||
|
'discount_raw_total' => $this->fromCents($discountRawCents),
|
||||||
|
'paid_amount' => $this->fromCents($paidCents),
|
||||||
|
'refund_paid_total' => $this->fromCents($refundPaidCents),
|
||||||
|
'total_amount' => $this->fromCents($totalAmountCents),
|
||||||
|
'balance' => $this->fromCents($balanceCents),
|
||||||
|
'status' => $status,
|
||||||
|
'has_discount' => $discountCents > 0 ? 1 : 0,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function recalculateInvoice(int $invoiceId): array
|
||||||
|
{
|
||||||
|
$calculation = $this->calculateInvoice($invoiceId);
|
||||||
|
$payload = [
|
||||||
|
'total_amount' => $calculation['total_amount'],
|
||||||
|
'paid_amount' => $calculation['paid_amount'],
|
||||||
|
'balance' => $calculation['balance'],
|
||||||
|
'status' => $calculation['status'],
|
||||||
|
'has_discount' => $calculation['has_discount'],
|
||||||
|
'updated_at' => utc_now(),
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($this->invoiceModel->db->fieldExists('discount', $this->invoiceModel->table)) {
|
||||||
|
$payload['discount'] = $calculation['discount_total'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->invoiceModel->update($invoiceId, $payload);
|
||||||
|
|
||||||
|
return $calculation;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function loadInvoice(int $invoiceId): ?array
|
||||||
|
{
|
||||||
|
return $this->invoiceModel->find($invoiceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function calculateTuitionTotal(array $invoice): float
|
||||||
|
{
|
||||||
|
$parentId = (int) ($invoice['parent_id'] ?? 0);
|
||||||
|
$schoolYear = (string) ($invoice['school_year'] ?? '');
|
||||||
|
if ($parentId <= 0 || $schoolYear === '') {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
$students = $this->loadTuitionStudents($parentId, $schoolYear);
|
||||||
|
$config = $this->getTuitionConfig();
|
||||||
|
$calculator = $this->resolveActiveCalculator();
|
||||||
|
|
||||||
|
return (float) ($calculator->calculateFamilyTuition($students, $config)['total'] ?? 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function calculateEventTotal(array $invoice): float
|
||||||
|
{
|
||||||
|
$invoiceId = (int) ($invoice['id'] ?? 0);
|
||||||
|
$invoiceEventRows = $this->invoiceEventModel
|
||||||
|
->select('COALESCE(SUM(amount),0) AS total_amount')
|
||||||
|
->where('invoice_id', $invoiceId)
|
||||||
|
->findAll();
|
||||||
|
|
||||||
|
if (!empty($invoiceEventRows)) {
|
||||||
|
$total = (float) ($invoiceEventRows[0]['total_amount'] ?? 0);
|
||||||
|
if ($total > 0) {
|
||||||
|
return $total;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows = $this->eventChargesModel
|
||||||
|
->select('COALESCE(SUM(charged),0) AS total_amount')
|
||||||
|
->where('parent_id', (int) ($invoice['parent_id'] ?? 0))
|
||||||
|
->where('school_year', (string) ($invoice['school_year'] ?? ''))
|
||||||
|
->where('semester', (string) ($invoice['semester'] ?? ''))
|
||||||
|
->findAll();
|
||||||
|
|
||||||
|
return (float) ($rows[0]['total_amount'] ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function calculateAdditionalCharges(int $invoiceId): float
|
||||||
|
{
|
||||||
|
$rows = $this->additionalChargeModel
|
||||||
|
->select('COALESCE(SUM(amount),0) AS total_amount')
|
||||||
|
->where('invoice_id', $invoiceId)
|
||||||
|
->whereNotIn('status', ['void', FinancialStatus::ADDITIONAL_CHARGE_VOIDED, 'cancelled', 'canceled'])
|
||||||
|
->findAll();
|
||||||
|
|
||||||
|
return (float) ($rows[0]['total_amount'] ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function calculateDiscounts(int $invoiceId): float
|
||||||
|
{
|
||||||
|
$row = $this->discountUsageModel
|
||||||
|
->select('COALESCE(SUM(discount_amount),0) AS total_amount')
|
||||||
|
->where('invoice_id', $invoiceId)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
return (float) ($row['total_amount'] ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function calculateValidPayments(int $invoiceId): float
|
||||||
|
{
|
||||||
|
$query = $this->paymentModel
|
||||||
|
->select('COALESCE(SUM(paid_amount),0) AS total_amount')
|
||||||
|
->where('invoice_id', $invoiceId);
|
||||||
|
|
||||||
|
if ($this->paymentModel->db->fieldExists('status', $this->paymentModel->table)) {
|
||||||
|
$query->groupStart()
|
||||||
|
->whereNotIn('status', FinancialStatus::EXCLUDED_PAYMENT_STATUSES)
|
||||||
|
->orWhere('status IS NULL', null, false)
|
||||||
|
->groupEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->paymentModel->db->fieldExists('is_void', $this->paymentModel->table)) {
|
||||||
|
$query->groupStart()
|
||||||
|
->where('is_void', 0)
|
||||||
|
->orWhere('is_void IS NULL', null, false)
|
||||||
|
->groupEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
$row = $query->first();
|
||||||
|
|
||||||
|
return (float) ($row['total_amount'] ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function calculatePaidRefunds(int $invoiceId): float
|
||||||
|
{
|
||||||
|
$row = $this->refundModel
|
||||||
|
->select('COALESCE(SUM(refund_paid_amount),0) AS total_amount')
|
||||||
|
->where('invoice_id', $invoiceId)
|
||||||
|
->whereIn('status', FinancialStatus::REFUND_REDUCES_INVOICE_STATUSES)
|
||||||
|
->first();
|
||||||
|
|
||||||
|
return (float) ($row['total_amount'] ?? 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function loadTuitionStudents(int $parentId, string $schoolYear): array
|
||||||
|
{
|
||||||
|
$enrollments = $this->enrollmentModel
|
||||||
|
->where('parent_id', $parentId)
|
||||||
|
->where('school_year', $schoolYear)
|
||||||
|
->findAll();
|
||||||
|
|
||||||
|
if (empty($enrollments)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$refundDeadline = (string) ($this->configurationModel->getConfig('refund_deadline') ?? '');
|
||||||
|
$includeWithdrawn = !$this->isWithinRefundWindow($refundDeadline);
|
||||||
|
$eligibleStatuses = ['enrolled', 'payment pending'];
|
||||||
|
|
||||||
|
if ($includeWithdrawn) {
|
||||||
|
array_push($eligibleStatuses, 'withdrawn', 'refund pending', 'withdraw under review');
|
||||||
|
}
|
||||||
|
|
||||||
|
$students = [];
|
||||||
|
foreach ($enrollments as $enrollment) {
|
||||||
|
$status = strtolower(trim((string) ($enrollment['enrollment_status'] ?? '')));
|
||||||
|
$studentId = (int) ($enrollment['student_id'] ?? 0);
|
||||||
|
if ($studentId <= 0 || !in_array($status, $eligibleStatuses, true)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$this->studentClassModel->hasNonEventAssignment($studentId, $schoolYear)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$gradeName = $this->resolveGradeName($studentId, $schoolYear, $enrollment['class_section_id'] ?? null);
|
||||||
|
$student = $this->studentModel->find($studentId) ?? [];
|
||||||
|
|
||||||
|
$students[] = [
|
||||||
|
'student_id' => $studentId,
|
||||||
|
'student_name' => trim(((string) ($student['firstname'] ?? '')) . ' ' . ((string) ($student['lastname'] ?? ''))),
|
||||||
|
'grade_level' => $gradeName,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $students;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function resolveGradeName(int $studentId, string $schoolYear, $classSectionId = null): string
|
||||||
|
{
|
||||||
|
$sectionId = $classSectionId;
|
||||||
|
if (empty($sectionId)) {
|
||||||
|
$row = $this->studentClassModel
|
||||||
|
->select('class_section_id')
|
||||||
|
->where('student_id', $studentId)
|
||||||
|
->where('school_year', $schoolYear)
|
||||||
|
->orderBy('updated_at', 'DESC')
|
||||||
|
->first();
|
||||||
|
$sectionId = $row['class_section_id'] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($sectionId)) {
|
||||||
|
return 'N/A';
|
||||||
|
}
|
||||||
|
|
||||||
|
$name = $this->classSectionModel->getClassSectionNameBySectionId($sectionId);
|
||||||
|
|
||||||
|
return is_string($name) && $name !== '' ? strtoupper(trim($name)) : 'N/A';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function resolveActiveCalculator(): TuitionCalculatorInterface
|
||||||
|
{
|
||||||
|
$version = strtolower(trim((string) ($this->configurationModel->getConfig('tuition_calculator_version') ?? 'old')));
|
||||||
|
|
||||||
|
return $version === 'new' ? $this->newCalculator : $this->oldCalculator;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getTuitionConfig(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'grade_fee' => $this->configurationModel->getConfig('grade_fee'),
|
||||||
|
'first_student_fee' => $this->configurationModel->getConfig('first_student_fee'),
|
||||||
|
'second_student_fee' => $this->configurationModel->getConfig('second_student_fee'),
|
||||||
|
'youth_fee' => $this->configurationModel->getConfig('youth_fee'),
|
||||||
|
'new_tuition_full_amount' => $this->configurationModel->getConfig('new_tuition_full_amount'),
|
||||||
|
'new_tuition_youth_amount' => $this->configurationModel->getConfig('new_tuition_youth_amount'),
|
||||||
|
'new_tuition_second_student_discount' => $this->configurationModel->getConfig('new_tuition_second_student_discount'),
|
||||||
|
'new_tuition_third_student_discount' => $this->configurationModel->getConfig('new_tuition_third_student_discount'),
|
||||||
|
'new_tuition_fourth_plus_discount' => $this->configurationModel->getConfig('new_tuition_fourth_plus_discount'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function isWithinRefundWindow(string $refundDeadline): bool
|
||||||
|
{
|
||||||
|
if ($refundDeadline === '') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$timeZone = new \DateTimeZone((string) (config('School')->attendance['timezone'] ?? user_timezone()));
|
||||||
|
$today = new \DateTimeImmutable('today', $timeZone);
|
||||||
|
$deadline = new \DateTimeImmutable($refundDeadline, $timeZone);
|
||||||
|
|
||||||
|
return $today <= $deadline;
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function toCents($amount): int
|
||||||
|
{
|
||||||
|
return (int) round(((float) $amount) * 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function fromCents(int $cents): string
|
||||||
|
{
|
||||||
|
return number_format($cents / 100, 2, '.', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Libraries\Tuition;
|
||||||
|
|
||||||
|
final class GradeLevelParser
|
||||||
|
{
|
||||||
|
public static function parse($grade, int $gradeFee = 9): int
|
||||||
|
{
|
||||||
|
if (is_numeric($grade)) {
|
||||||
|
return (int) $grade;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is_string($grade)) {
|
||||||
|
return 999;
|
||||||
|
}
|
||||||
|
|
||||||
|
$value = strtoupper(trim($grade));
|
||||||
|
$value = preg_replace('/\s+/', ' ', $value) ?? $value;
|
||||||
|
$value = str_replace(['.', '_', '-'], ['', '', ' '], $value);
|
||||||
|
|
||||||
|
if (in_array($value, ['K', 'KG', 'K G', 'KINDER', 'KINDERGARTEN'], true)) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_array($value, ['PK', 'P K', 'PREK', 'PRE K', 'PRE KINDER', 'PREKINDER'], true)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/^Y(?:OUTH)?\s*(\d+)?$/', $value, $matches)) {
|
||||||
|
$offset = isset($matches[1]) && $matches[1] !== '' ? max(1, (int) $matches[1]) : 1;
|
||||||
|
return $gradeFee + $offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preg_match('/^(?:GR?ADE\s*)?(\d{1,2})\s*([A-Z]*)$/', $value, $matches)) {
|
||||||
|
return (int) $matches[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
return 999;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Libraries\Tuition;
|
||||||
|
|
||||||
|
use App\Interfaces\TuitionCalculatorInterface;
|
||||||
|
|
||||||
|
final class NewTuitionCalculatorService implements TuitionCalculatorInterface
|
||||||
|
{
|
||||||
|
public function calculateFamilyTuition(array $students, array $config): array
|
||||||
|
{
|
||||||
|
$gradeFee = (int) ($config['grade_fee'] ?? 9);
|
||||||
|
$fullAmountCents = $this->toCents($config['new_tuition_full_amount'] ?? 370);
|
||||||
|
$youthAmountCents = $this->toCents($config['new_tuition_youth_amount'] ?? $config['youth_fee'] ?? 200);
|
||||||
|
$secondDiscountCents = $this->toCents($config['new_tuition_second_student_discount'] ?? 50);
|
||||||
|
$thirdDiscountCents = $this->toCents($config['new_tuition_third_student_discount'] ?? 50);
|
||||||
|
$fourthPlusDiscountCents = $this->toCents($config['new_tuition_fourth_plus_discount'] ?? 100);
|
||||||
|
|
||||||
|
usort($students, function (array $left, array $right) use ($gradeFee): int {
|
||||||
|
$leftLevel = GradeLevelParser::parse($left['grade_level'] ?? null, $gradeFee);
|
||||||
|
$rightLevel = GradeLevelParser::parse($right['grade_level'] ?? null, $gradeFee);
|
||||||
|
|
||||||
|
return [$leftLevel, (int) ($left['student_id'] ?? 0)] <=> [$rightLevel, (int) ($right['student_id'] ?? 0)];
|
||||||
|
});
|
||||||
|
|
||||||
|
$details = [];
|
||||||
|
$regularPosition = 0;
|
||||||
|
|
||||||
|
foreach (array_values($students) as $student) {
|
||||||
|
$level = GradeLevelParser::parse($student['grade_level'] ?? null, $gradeFee);
|
||||||
|
|
||||||
|
if ($level > $gradeFee) {
|
||||||
|
$position = null;
|
||||||
|
$discountCents = 0;
|
||||||
|
$rule = 'new_youth_unit_price';
|
||||||
|
$baseAmountCents = $youthAmountCents;
|
||||||
|
} else {
|
||||||
|
$regularPosition++;
|
||||||
|
$position = $regularPosition;
|
||||||
|
|
||||||
|
if ($position === 1) {
|
||||||
|
$discountCents = 0;
|
||||||
|
$rule = 'new_first_student_full_amount';
|
||||||
|
} elseif ($position === 2) {
|
||||||
|
$discountCents = $secondDiscountCents;
|
||||||
|
$rule = 'new_second_student_discount';
|
||||||
|
} elseif ($position === 3) {
|
||||||
|
$discountCents = $thirdDiscountCents;
|
||||||
|
$rule = 'new_third_student_discount';
|
||||||
|
} else {
|
||||||
|
$discountCents = $fourthPlusDiscountCents;
|
||||||
|
$rule = 'new_fourth_plus_student_discount';
|
||||||
|
}
|
||||||
|
|
||||||
|
$baseAmountCents = $fullAmountCents;
|
||||||
|
}
|
||||||
|
|
||||||
|
$amountCents = max(0, $baseAmountCents - $discountCents);
|
||||||
|
|
||||||
|
$details[] = [
|
||||||
|
'student_id' => (int) ($student['student_id'] ?? 0),
|
||||||
|
'student_name' => (string) ($student['student_name'] ?? ''),
|
||||||
|
'grade_level' => $student['grade_level'] ?? null,
|
||||||
|
'family_position' => $position,
|
||||||
|
'full_amount' => $this->fromCents($baseAmountCents),
|
||||||
|
'discount' => $this->fromCents($discountCents),
|
||||||
|
'rule' => $rule,
|
||||||
|
'amount' => $this->fromCents($amountCents),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$total = array_sum(array_map(fn (array $detail): int => $this->toCents($detail['amount']), $details));
|
||||||
|
|
||||||
|
return [
|
||||||
|
'calculator' => 'new',
|
||||||
|
'total' => $this->fromCents($total),
|
||||||
|
'details' => $details,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function toCents($amount): int
|
||||||
|
{
|
||||||
|
return (int) round(((float) $amount) * 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function fromCents(int $cents): string
|
||||||
|
{
|
||||||
|
return number_format($cents / 100, 2, '.', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Libraries\Tuition;
|
||||||
|
|
||||||
|
use App\Interfaces\TuitionCalculatorInterface;
|
||||||
|
|
||||||
|
final class OldTuitionCalculatorService implements TuitionCalculatorInterface
|
||||||
|
{
|
||||||
|
public function calculateFamilyTuition(array $students, array $config): array
|
||||||
|
{
|
||||||
|
$gradeFee = (int) ($config['grade_fee'] ?? 9);
|
||||||
|
$firstStudentFee = $this->toCents($config['first_student_fee'] ?? 370);
|
||||||
|
$secondStudentFee = $this->toCents($config['second_student_fee'] ?? 200);
|
||||||
|
$youthFee = $this->toCents($config['youth_fee'] ?? 200);
|
||||||
|
|
||||||
|
usort($students, function (array $left, array $right) use ($gradeFee): int {
|
||||||
|
$leftLevel = GradeLevelParser::parse($left['grade_level'] ?? null, $gradeFee);
|
||||||
|
$rightLevel = GradeLevelParser::parse($right['grade_level'] ?? null, $gradeFee);
|
||||||
|
|
||||||
|
return [$leftLevel, (int) ($left['student_id'] ?? 0)] <=> [$rightLevel, (int) ($right['student_id'] ?? 0)];
|
||||||
|
});
|
||||||
|
|
||||||
|
$regularCount = 0;
|
||||||
|
$details = [];
|
||||||
|
|
||||||
|
foreach ($students as $student) {
|
||||||
|
$level = GradeLevelParser::parse($student['grade_level'] ?? null, $gradeFee);
|
||||||
|
|
||||||
|
if ($level > $gradeFee) {
|
||||||
|
$amountCents = $youthFee;
|
||||||
|
$rule = 'old_youth_fee';
|
||||||
|
} else {
|
||||||
|
$regularCount++;
|
||||||
|
$amountCents = $regularCount === 1 ? $firstStudentFee : $secondStudentFee;
|
||||||
|
$rule = $regularCount === 1 ? 'old_first_student_fee' : 'old_second_student_fee';
|
||||||
|
}
|
||||||
|
|
||||||
|
$details[] = [
|
||||||
|
'student_id' => (int) ($student['student_id'] ?? 0),
|
||||||
|
'student_name' => (string) ($student['student_name'] ?? ''),
|
||||||
|
'grade_level' => $student['grade_level'] ?? null,
|
||||||
|
'rule' => $rule,
|
||||||
|
'amount' => $this->fromCents($amountCents),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$total = array_sum(array_map(fn (array $detail): int => $this->toCents($detail['amount']), $details));
|
||||||
|
|
||||||
|
return [
|
||||||
|
'calculator' => 'old',
|
||||||
|
'total' => $this->fromCents($total),
|
||||||
|
'details' => $details,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function toCents($amount): int
|
||||||
|
{
|
||||||
|
return (int) round(((float) $amount) * 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function fromCents(int $cents): string
|
||||||
|
{
|
||||||
|
return number_format($cents / 100, 2, '.', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,663 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Libraries\Tuition;
|
||||||
|
|
||||||
|
use App\Libraries\FinancialStatus;
|
||||||
|
use App\Models\ClassSectionModel;
|
||||||
|
use App\Models\ConfigurationModel;
|
||||||
|
use App\Models\EnrollmentModel;
|
||||||
|
use App\Models\PaymentModel;
|
||||||
|
use App\Models\RefundModel;
|
||||||
|
use App\Models\StudentClassModel;
|
||||||
|
use App\Models\UserModel;
|
||||||
|
|
||||||
|
class TuitionForecastService
|
||||||
|
{
|
||||||
|
protected ConfigurationModel $configurationModel;
|
||||||
|
protected EnrollmentModel $enrollmentModel;
|
||||||
|
protected StudentClassModel $studentClassModel;
|
||||||
|
protected ClassSectionModel $classSectionModel;
|
||||||
|
protected PaymentModel $paymentModel;
|
||||||
|
protected RefundModel $refundModel;
|
||||||
|
protected UserModel $userModel;
|
||||||
|
protected OldTuitionCalculatorService $oldCalculator;
|
||||||
|
protected NewTuitionCalculatorService $newCalculator;
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->configurationModel = new ConfigurationModel();
|
||||||
|
$this->enrollmentModel = new EnrollmentModel();
|
||||||
|
$this->studentClassModel = new StudentClassModel();
|
||||||
|
$this->classSectionModel = new ClassSectionModel();
|
||||||
|
$this->paymentModel = new PaymentModel();
|
||||||
|
$this->refundModel = new RefundModel();
|
||||||
|
$this->userModel = new UserModel();
|
||||||
|
$this->oldCalculator = new OldTuitionCalculatorService();
|
||||||
|
$this->newCalculator = new NewTuitionCalculatorService();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function calculate(string $schoolYear, string $semester, string $mode = 'compare', array $options = []): array
|
||||||
|
{
|
||||||
|
$schoolYear = trim($schoolYear) !== '' ? trim($schoolYear) : $this->getDefaultSchoolYear();
|
||||||
|
$semester = trim($semester) !== '' ? trim($semester) : $this->getDefaultSemester();
|
||||||
|
$mode = $this->normalizeMode($mode);
|
||||||
|
$options = $this->normalizeOptions($options);
|
||||||
|
$this->unitPriceOverride = $options['unit_price'];
|
||||||
|
$this->youthUnitPriceOverride = $options['youth_unit_price'];
|
||||||
|
$tuitionConfig = $this->getTuitionConfig();
|
||||||
|
$familyRows = [];
|
||||||
|
$summary = [
|
||||||
|
'family_count' => 0,
|
||||||
|
'student_count' => 0,
|
||||||
|
'billable_student_count' => 0,
|
||||||
|
'old_projected_tuition' => '0.00',
|
||||||
|
'new_projected_tuition' => '0.00',
|
||||||
|
'old_projected_income' => '0.00',
|
||||||
|
'new_projected_income' => '0.00',
|
||||||
|
'difference' => '0.00',
|
||||||
|
'projected_tuition' => '0.00',
|
||||||
|
'projected_income' => '0.00',
|
||||||
|
'unit_price' => '0.00',
|
||||||
|
'youth_unit_price' => '0.00',
|
||||||
|
];
|
||||||
|
|
||||||
|
$oldProjectedCents = 0;
|
||||||
|
$newProjectedCents = 0;
|
||||||
|
$studentCount = 0;
|
||||||
|
$billableStudentCount = 0;
|
||||||
|
|
||||||
|
foreach ($this->loadFamilies($schoolYear, $semester) as $family) {
|
||||||
|
$parentId = (int) ($family['parent_id'] ?? 0);
|
||||||
|
if ($parentId <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$studentContext = $this->loadFamilyStudents($parentId, $schoolYear, $semester, $options);
|
||||||
|
$students = $studentContext['students'];
|
||||||
|
$allStudents = $studentContext['all_students'];
|
||||||
|
$warnings = $studentContext['warnings'];
|
||||||
|
|
||||||
|
if (empty($allStudents)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$oldResult = $this->oldCalculator->calculateFamilyTuition($students, $tuitionConfig);
|
||||||
|
$newResult = $this->newCalculator->calculateFamilyTuition($students, $tuitionConfig);
|
||||||
|
|
||||||
|
$oldTotalCents = $this->toCents($oldResult['total'] ?? 0);
|
||||||
|
$newTotalCents = $this->toCents($newResult['total'] ?? 0);
|
||||||
|
|
||||||
|
$mergedDetails = $this->mergeStudentDetails($allStudents, $oldResult['details'] ?? [], $newResult['details'] ?? []);
|
||||||
|
$studentCount += count($allStudents);
|
||||||
|
$billableStudentCount += count($students);
|
||||||
|
$oldProjectedCents += $oldTotalCents;
|
||||||
|
$newProjectedCents += $newTotalCents;
|
||||||
|
|
||||||
|
$familyRows[] = [
|
||||||
|
'parent_id' => $parentId,
|
||||||
|
'parent_name' => $family['parent_name'] ?? ('Parent #' . $parentId),
|
||||||
|
'student_count' => count($allStudents),
|
||||||
|
'billable_student_count' => count($students),
|
||||||
|
'old_total' => $this->fromCents($oldTotalCents),
|
||||||
|
'new_total' => $this->fromCents($newTotalCents),
|
||||||
|
'difference' => $this->fromCents($newTotalCents - $oldTotalCents),
|
||||||
|
'warnings' => array_values(array_unique($warnings)),
|
||||||
|
'student_details' => $mergedDetails,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
usort($familyRows, static fn (array $left, array $right): int => strcmp((string) ($left['parent_name'] ?? ''), (string) ($right['parent_name'] ?? '')));
|
||||||
|
|
||||||
|
$summary['family_count'] = count($familyRows);
|
||||||
|
$summary['student_count'] = $studentCount;
|
||||||
|
$summary['billable_student_count'] = $billableStudentCount;
|
||||||
|
$summary['old_projected_tuition'] = $this->fromCents($oldProjectedCents);
|
||||||
|
$summary['new_projected_tuition'] = $this->fromCents($newProjectedCents);
|
||||||
|
$summary['old_projected_income'] = $summary['old_projected_tuition'];
|
||||||
|
$summary['new_projected_income'] = $summary['new_projected_tuition'];
|
||||||
|
$summary['difference'] = $this->fromCents($newProjectedCents - $oldProjectedCents);
|
||||||
|
$summary['projected_tuition'] = $mode === 'old' ? $summary['old_projected_tuition'] : $summary['new_projected_tuition'];
|
||||||
|
$summary['projected_income'] = $mode === 'old' ? $summary['old_projected_income'] : $summary['new_projected_income'];
|
||||||
|
$summary['unit_price'] = number_format((float) ($tuitionConfig['new_tuition_full_amount'] ?? 0), 2, '.', '');
|
||||||
|
$summary['youth_unit_price'] = number_format((float) ($tuitionConfig['new_tuition_youth_amount'] ?? 0), 2, '.', '');
|
||||||
|
|
||||||
|
return [
|
||||||
|
'school_year' => $schoolYear,
|
||||||
|
'semester' => $semester,
|
||||||
|
'calculator_mode' => $mode,
|
||||||
|
'options' => $options,
|
||||||
|
'summary' => $summary,
|
||||||
|
'families' => $familyRows,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getAvailableSchoolYears(): array
|
||||||
|
{
|
||||||
|
$values = [];
|
||||||
|
|
||||||
|
if ($this->enrollmentModel->db->tableExists('enrollments')) {
|
||||||
|
$rows = $this->enrollmentModel->db->table('enrollments')
|
||||||
|
->select('school_year')
|
||||||
|
->where('school_year IS NOT NULL', null, false)
|
||||||
|
->where('school_year !=', '')
|
||||||
|
->groupBy('school_year')
|
||||||
|
->orderBy('school_year', 'DESC')
|
||||||
|
->get()
|
||||||
|
->getResultArray();
|
||||||
|
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$value = trim((string) ($row['school_year'] ?? ''));
|
||||||
|
if ($value !== '') {
|
||||||
|
$values[$value] = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->paymentModel->db->tableExists('invoices')) {
|
||||||
|
$rows = $this->paymentModel->db->table('invoices')
|
||||||
|
->select('school_year')
|
||||||
|
->where('school_year IS NOT NULL', null, false)
|
||||||
|
->where('school_year !=', '')
|
||||||
|
->groupBy('school_year')
|
||||||
|
->orderBy('school_year', 'DESC')
|
||||||
|
->get()
|
||||||
|
->getResultArray();
|
||||||
|
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$value = trim((string) ($row['school_year'] ?? ''));
|
||||||
|
if ($value !== '') {
|
||||||
|
$values[$value] = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($values === []) {
|
||||||
|
$default = $this->getDefaultSchoolYear();
|
||||||
|
if ($default !== '') {
|
||||||
|
$values[$default] = $default;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
krsort($values);
|
||||||
|
|
||||||
|
return array_values($values);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getAvailableSemesters(): array
|
||||||
|
{
|
||||||
|
$values = [];
|
||||||
|
|
||||||
|
if ($this->enrollmentModel->db->tableExists('enrollments')) {
|
||||||
|
$rows = $this->enrollmentModel->db->table('enrollments')
|
||||||
|
->select('semester')
|
||||||
|
->where('semester IS NOT NULL', null, false)
|
||||||
|
->where('semester !=', '')
|
||||||
|
->groupBy('semester')
|
||||||
|
->orderBy('semester', 'ASC')
|
||||||
|
->get()
|
||||||
|
->getResultArray();
|
||||||
|
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$value = trim((string) ($row['semester'] ?? ''));
|
||||||
|
if ($value !== '') {
|
||||||
|
$values[$value] = $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($values === []) {
|
||||||
|
$default = $this->getDefaultSemester();
|
||||||
|
if ($default !== '') {
|
||||||
|
$values[$default] = $default;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_values($values);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function normalizeMode(string $mode): string
|
||||||
|
{
|
||||||
|
$value = strtolower(trim($mode));
|
||||||
|
|
||||||
|
return in_array($value, ['old', 'new'], true) ? $value : 'compare';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function normalizeOptions(array $options): array
|
||||||
|
{
|
||||||
|
$includeWithdrawnMode = strtolower(trim((string) ($options['include_withdrawn_mode'] ?? 'refund_deadline')));
|
||||||
|
if (!in_array($includeWithdrawnMode, ['refund_deadline', 'include', 'exclude'], true)) {
|
||||||
|
$includeWithdrawnMode = 'refund_deadline';
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'include_withdrawn_mode' => $includeWithdrawnMode,
|
||||||
|
'include_payment_pending' => $this->toBool($options['include_payment_pending'] ?? true),
|
||||||
|
'include_event_only' => $this->toBool($options['include_event_only'] ?? false),
|
||||||
|
'include_paid_invoices' => $this->toBool($options['include_paid_invoices'] ?? true),
|
||||||
|
'unit_price' => $this->normalizeMoney($options['unit_price'] ?? null),
|
||||||
|
'youth_unit_price' => $this->normalizeMoney($options['youth_unit_price'] ?? null),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function loadFamilies(string $schoolYear, string $semester): array
|
||||||
|
{
|
||||||
|
$builder = $this->enrollmentModel->db->table('enrollments e')
|
||||||
|
->select("e.parent_id, CONCAT(COALESCE(u.lastname, ''), ', ', COALESCE(u.firstname, '')) AS parent_name", false)
|
||||||
|
->join('users u', 'u.id = e.parent_id', 'left')
|
||||||
|
->where('e.school_year', $schoolYear)
|
||||||
|
->groupBy('e.parent_id')
|
||||||
|
->orderBy('parent_name', 'ASC');
|
||||||
|
|
||||||
|
$this->applyEnrollmentSemesterFilter($builder, 'e', $semester);
|
||||||
|
|
||||||
|
return $builder->get()->getResultArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function loadFamilyStudents(int $parentId, string $schoolYear, string $semester, array $options): array
|
||||||
|
{
|
||||||
|
$rows = $this->enrollmentModel->db->table('enrollments e')
|
||||||
|
->select('e.*, s.firstname, s.lastname, s.is_active')
|
||||||
|
->join('students s', 's.id = e.student_id', 'left')
|
||||||
|
->where('e.parent_id', $parentId)
|
||||||
|
->where('e.school_year', $schoolYear)
|
||||||
|
->orderBy('e.updated_at', 'DESC')
|
||||||
|
->orderBy('e.id', 'DESC')
|
||||||
|
->get()
|
||||||
|
->getResultArray();
|
||||||
|
|
||||||
|
$latestByStudent = [];
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$studentId = (int) ($row['student_id'] ?? 0);
|
||||||
|
if ($studentId <= 0 || isset($latestByStudent[$studentId])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$this->matchesEnrollmentSemester($row, $semester)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$latestByStudent[$studentId] = $row;
|
||||||
|
}
|
||||||
|
|
||||||
|
ksort($latestByStudent);
|
||||||
|
|
||||||
|
$withinRefundWindow = $this->isWithinRefundWindow((string) ($this->configurationModel->getConfig('refund_deadline') ?? ''));
|
||||||
|
$students = [];
|
||||||
|
$allStudents = [];
|
||||||
|
$warnings = [];
|
||||||
|
$eventOnlyCount = 0;
|
||||||
|
$missingClassCount = 0;
|
||||||
|
$inactiveCount = 0;
|
||||||
|
$pendingSkippedCount = 0;
|
||||||
|
|
||||||
|
foreach ($latestByStudent as $row) {
|
||||||
|
$studentId = (int) ($row['student_id'] ?? 0);
|
||||||
|
$studentName = trim(((string) ($row['firstname'] ?? '')) . ' ' . ((string) ($row['lastname'] ?? '')));
|
||||||
|
$studentLabel = $studentName !== '' ? $studentName : ('Student #' . $studentId);
|
||||||
|
|
||||||
|
if ((int) ($row['is_active'] ?? 1) === 0) {
|
||||||
|
$inactiveCount++;
|
||||||
|
$allStudents[] = [
|
||||||
|
'student_id' => $studentId,
|
||||||
|
'student_name' => $studentLabel,
|
||||||
|
'grade_level' => 'N/A',
|
||||||
|
'billable' => false,
|
||||||
|
'excluded_reason' => 'inactive',
|
||||||
|
];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$inclusion = $this->resolveEnrollmentInclusion($row, $options, $withinRefundWindow);
|
||||||
|
if (!$inclusion['include']) {
|
||||||
|
if (($inclusion['reason'] ?? '') === 'payment_pending_excluded') {
|
||||||
|
$pendingSkippedCount++;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$classFlags = $this->resolveStudentClassFlags($studentId, $schoolYear);
|
||||||
|
$gradeName = $this->resolveGradeName($studentId, $schoolYear, $row['class_section_id'] ?? null);
|
||||||
|
$studentBase = [
|
||||||
|
'student_id' => $studentId,
|
||||||
|
'student_name' => $studentLabel,
|
||||||
|
'grade_level' => $gradeName,
|
||||||
|
'billable' => false,
|
||||||
|
'excluded_reason' => null,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (!$classFlags['has_any_assignment']) {
|
||||||
|
$missingClassCount++;
|
||||||
|
$studentBase['excluded_reason'] = 'missing_class_assignment';
|
||||||
|
$allStudents[] = $studentBase;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!$classFlags['has_non_event_assignment']) {
|
||||||
|
$eventOnlyCount++;
|
||||||
|
$studentBase['excluded_reason'] = 'event_only';
|
||||||
|
$allStudents[] = $studentBase;
|
||||||
|
if ($options['include_event_only']) {
|
||||||
|
$warnings[] = $studentLabel . ' is event-only and excluded from tuition billing.';
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($gradeName === 'N/A') {
|
||||||
|
$warnings[] = $studentLabel . ' has no resolved class section grade.';
|
||||||
|
}
|
||||||
|
|
||||||
|
$studentBase['billable'] = true;
|
||||||
|
$allStudents[] = $studentBase;
|
||||||
|
$students[] = [
|
||||||
|
'student_id' => $studentId,
|
||||||
|
'student_name' => $studentLabel,
|
||||||
|
'grade_level' => $gradeName,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($eventOnlyCount > 0) {
|
||||||
|
$warnings[] = $eventOnlyCount . ' event-only student(s) excluded from tuition.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($missingClassCount > 0) {
|
||||||
|
$warnings[] = $missingClassCount . ' student(s) missing class assignments.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($inactiveCount > 0) {
|
||||||
|
$warnings[] = $inactiveCount . ' inactive student(s) skipped.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($pendingSkippedCount > 0) {
|
||||||
|
$warnings[] = $pendingSkippedCount . ' payment-pending student(s) skipped by filter.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->toCents($this->configurationModel->getConfig('new_tuition_full_amount') ?? 0) <= 0) {
|
||||||
|
$warnings[] = 'New tuition full amount is missing or zero.';
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'students' => $students,
|
||||||
|
'all_students' => $allStudents,
|
||||||
|
'warnings' => array_values(array_unique($warnings)),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function resolveEnrollmentInclusion(array $row, array $options, bool $withinRefundWindow): array
|
||||||
|
{
|
||||||
|
$admissionStatus = strtolower(trim((string) ($row['admission_status'] ?? '')));
|
||||||
|
$enrollmentStatus = strtolower(trim((string) ($row['enrollment_status'] ?? '')));
|
||||||
|
|
||||||
|
if ($admissionStatus === 'denied' || $enrollmentStatus === 'admission under review') {
|
||||||
|
return ['include' => false, 'reason' => 'not_admitted'];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($enrollmentStatus === 'payment pending') {
|
||||||
|
return ['include' => $options['include_payment_pending'], 'reason' => 'payment_pending_excluded'];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($enrollmentStatus === 'enrolled') {
|
||||||
|
return ['include' => true, 'reason' => null];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (in_array($enrollmentStatus, ['withdrawn', 'refund pending', 'withdraw under review'], true)) {
|
||||||
|
if ($options['include_withdrawn_mode'] === 'include') {
|
||||||
|
return ['include' => true, 'reason' => null];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($options['include_withdrawn_mode'] === 'exclude') {
|
||||||
|
return ['include' => false, 'reason' => 'withdrawn_excluded'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['include' => !$withinRefundWindow, 'reason' => 'refund_deadline_excluded'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['include' => $admissionStatus === 'accepted', 'reason' => 'accepted_only'];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function resolveStudentClassFlags(int $studentId, string $schoolYear): array
|
||||||
|
{
|
||||||
|
$rows = $this->studentClassModel->where('student_id', $studentId)
|
||||||
|
->where('school_year', $schoolYear)
|
||||||
|
->findAll();
|
||||||
|
|
||||||
|
$hasAnyAssignment = !empty($rows);
|
||||||
|
$hasNonEventAssignment = false;
|
||||||
|
$hasEventOnlyAssignment = false;
|
||||||
|
|
||||||
|
foreach ($rows as $row) {
|
||||||
|
$isEventOnly = (int) ($row['is_event_only'] ?? 0) === 1;
|
||||||
|
$hasEventOnlyAssignment = $hasEventOnlyAssignment || $isEventOnly;
|
||||||
|
$hasNonEventAssignment = $hasNonEventAssignment || !$isEventOnly;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'has_any_assignment' => $hasAnyAssignment,
|
||||||
|
'has_non_event_assignment' => $hasNonEventAssignment,
|
||||||
|
'has_event_only_assignment' => $hasEventOnlyAssignment,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function resolveGradeName(int $studentId, string $schoolYear, $classSectionId = null): string
|
||||||
|
{
|
||||||
|
$sectionId = $classSectionId;
|
||||||
|
|
||||||
|
if (empty($sectionId)) {
|
||||||
|
$row = $this->studentClassModel
|
||||||
|
->select('class_section_id')
|
||||||
|
->where('student_id', $studentId)
|
||||||
|
->where('school_year', $schoolYear)
|
||||||
|
->where('is_event_only', 0)
|
||||||
|
->orderBy('updated_at', 'DESC')
|
||||||
|
->first();
|
||||||
|
$sectionId = $row['class_section_id'] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($sectionId)) {
|
||||||
|
return 'N/A';
|
||||||
|
}
|
||||||
|
|
||||||
|
$name = $this->classSectionModel->getClassSectionNameBySectionId($sectionId);
|
||||||
|
|
||||||
|
return is_string($name) && trim($name) !== '' ? strtoupper(trim($name)) : 'N/A';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function calculateAlreadyCollected(int $parentId, string $schoolYear, string $semester): int
|
||||||
|
{
|
||||||
|
$paymentBuilder = $this->paymentModel->db->table('payments')
|
||||||
|
->select('COALESCE(SUM(paid_amount),0) AS total_amount')
|
||||||
|
->where('parent_id', $parentId)
|
||||||
|
->where('school_year', $schoolYear);
|
||||||
|
|
||||||
|
if ($semester !== '') {
|
||||||
|
$paymentBuilder->where('semester', $semester);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->paymentModel->db->fieldExists('status', 'payments')) {
|
||||||
|
$paymentBuilder->groupStart()
|
||||||
|
->whereNotIn('status', FinancialStatus::EXCLUDED_PAYMENT_STATUSES)
|
||||||
|
->orWhere('status IS NULL', null, false)
|
||||||
|
->groupEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->paymentModel->db->fieldExists('is_void', 'payments')) {
|
||||||
|
$paymentBuilder->groupStart()
|
||||||
|
->where('is_void', 0)
|
||||||
|
->orWhere('is_void IS NULL', null, false)
|
||||||
|
->groupEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
$paymentRow = $paymentBuilder->get()->getRowArray();
|
||||||
|
$paidCents = $this->toCents($paymentRow['total_amount'] ?? 0);
|
||||||
|
|
||||||
|
$refundBuilder = $this->refundModel->db->table('refunds')
|
||||||
|
->select('COALESCE(SUM(refund_paid_amount),0) AS total_amount')
|
||||||
|
->where('parent_id', $parentId)
|
||||||
|
->where('school_year', $schoolYear)
|
||||||
|
->whereIn('status', FinancialStatus::REFUND_REDUCES_INVOICE_STATUSES);
|
||||||
|
|
||||||
|
if ($semester !== '' && $this->refundModel->db->fieldExists('semester', 'refunds')) {
|
||||||
|
$refundBuilder->where('semester', $semester);
|
||||||
|
}
|
||||||
|
|
||||||
|
$refundRow = $refundBuilder->get()->getRowArray();
|
||||||
|
$refundCents = $this->toCents($refundRow['total_amount'] ?? 0);
|
||||||
|
|
||||||
|
return max(0, $paidCents - $refundCents);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function mergeStudentDetails(array $allStudents, array $oldDetails, array $newDetails): array
|
||||||
|
{
|
||||||
|
$oldMap = [];
|
||||||
|
foreach ($oldDetails as $detail) {
|
||||||
|
$oldMap[(int) ($detail['student_id'] ?? 0)] = $detail;
|
||||||
|
}
|
||||||
|
|
||||||
|
$newMap = [];
|
||||||
|
foreach ($newDetails as $detail) {
|
||||||
|
$newMap[(int) ($detail['student_id'] ?? 0)] = $detail;
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows = [];
|
||||||
|
foreach ($allStudents as $student) {
|
||||||
|
$studentId = (int) ($student['student_id'] ?? 0);
|
||||||
|
$old = $oldMap[$studentId] ?? null;
|
||||||
|
$new = $newMap[$studentId] ?? null;
|
||||||
|
|
||||||
|
$rows[] = [
|
||||||
|
'student_id' => $studentId,
|
||||||
|
'student_name' => $student['student_name'] ?? '',
|
||||||
|
'grade_level' => $student['grade_level'] ?? 'N/A',
|
||||||
|
'billable' => (bool) ($student['billable'] ?? false),
|
||||||
|
'excluded_reason' => $student['excluded_reason'] ?? null,
|
||||||
|
'old_rule' => $old['rule'] ?? null,
|
||||||
|
'old_amount' => $old['amount'] ?? '0.00',
|
||||||
|
'new_rule' => $new['rule'] ?? null,
|
||||||
|
'new_amount' => $new['amount'] ?? '0.00',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getTuitionConfig(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'grade_fee' => $this->configurationModel->getConfig('grade_fee'),
|
||||||
|
'first_student_fee' => $this->configurationModel->getConfig('first_student_fee'),
|
||||||
|
'second_student_fee' => $this->configurationModel->getConfig('second_student_fee'),
|
||||||
|
'youth_fee' => $this->configurationModel->getConfig('youth_fee') ?? '200.00',
|
||||||
|
'new_tuition_full_amount' => $this->normalizedUnitPriceOverride(),
|
||||||
|
'new_tuition_youth_amount' => $this->normalizedYouthUnitPriceOverride(),
|
||||||
|
'new_tuition_second_student_discount' => $this->configurationModel->getConfig('new_tuition_second_student_discount'),
|
||||||
|
'new_tuition_third_student_discount' => $this->configurationModel->getConfig('new_tuition_third_student_discount'),
|
||||||
|
'new_tuition_fourth_plus_discount' => $this->configurationModel->getConfig('new_tuition_fourth_plus_discount'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected ?string $unitPriceOverride = null;
|
||||||
|
protected ?string $youthUnitPriceOverride = null;
|
||||||
|
|
||||||
|
protected function normalizedUnitPriceOverride(): string
|
||||||
|
{
|
||||||
|
return $this->unitPriceOverride
|
||||||
|
?? (string) ($this->configurationModel->getConfig('new_tuition_full_amount') ?? '0.00');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function normalizedYouthUnitPriceOverride(): string
|
||||||
|
{
|
||||||
|
return $this->youthUnitPriceOverride
|
||||||
|
?? (string) (
|
||||||
|
$this->configurationModel->getConfig('new_tuition_youth_amount')
|
||||||
|
?? $this->configurationModel->getConfig('youth_fee')
|
||||||
|
?? '200.00'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function normalizeMoney($value): ?string
|
||||||
|
{
|
||||||
|
if ($value === null || trim((string) $value) === '') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$normalized = preg_replace('/[^0-9.]+/', '', (string) $value);
|
||||||
|
if ($normalized === '' || !is_numeric($normalized)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$amount = (float) $normalized;
|
||||||
|
|
||||||
|
return $amount > 0 ? number_format($amount, 2, '.', '') : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function isWithinRefundWindow(string $refundDeadline): bool
|
||||||
|
{
|
||||||
|
if ($refundDeadline === '') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$timeZone = new \DateTimeZone((string) (config('School')->attendance['timezone'] ?? user_timezone()));
|
||||||
|
$today = new \DateTimeImmutable('today', $timeZone);
|
||||||
|
$deadline = new \DateTimeImmutable($refundDeadline, $timeZone);
|
||||||
|
|
||||||
|
return $today <= $deadline;
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getDefaultSchoolYear(): string
|
||||||
|
{
|
||||||
|
return (string) ($this->configurationModel->getConfig('school_year') ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getDefaultSemester(): string
|
||||||
|
{
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function applyEnrollmentSemesterFilter($builder, string $alias, string $semester): void
|
||||||
|
{
|
||||||
|
if ($semester === '') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$builder->groupStart()
|
||||||
|
->where($alias . '.semester', $semester)
|
||||||
|
->orWhere($alias . '.semester', '')
|
||||||
|
->orWhere($alias . '.semester IS NULL', null, false)
|
||||||
|
->groupEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function matchesEnrollmentSemester(array $row, string $semester): bool
|
||||||
|
{
|
||||||
|
if ($semester === '') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$value = trim((string) ($row['semester'] ?? ''));
|
||||||
|
|
||||||
|
return $value === '' || strcasecmp($value, $semester) === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function toBool($value): bool
|
||||||
|
{
|
||||||
|
if (is_bool($value)) {
|
||||||
|
return $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
$normalized = strtolower(trim((string) $value));
|
||||||
|
|
||||||
|
return in_array($normalized, ['1', 'true', 'yes', 'on'], true);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function toCents($amount): int
|
||||||
|
{
|
||||||
|
return (int) round(((float) $amount) * 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function fromCents(int $cents): string
|
||||||
|
{
|
||||||
|
return number_format($cents / 100, 2, '.', '');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -65,7 +65,6 @@ class DecisionEmailListener
|
|||||||
'parent_name' => $parentName !== '' ? $parentName : 'Parent/Guardian',
|
'parent_name' => $parentName !== '' ? $parentName : 'Parent/Guardian',
|
||||||
'student_name' => $studentName !== '' ? $studentName : 'your student',
|
'student_name' => $studentName !== '' ? $studentName : 'your student',
|
||||||
'class_section_name' => $classSection,
|
'class_section_name' => $classSection,
|
||||||
'semester' => $semester,
|
|
||||||
'school_year' => $schoolYear,
|
'school_year' => $schoolYear,
|
||||||
'decision' => $decision,
|
'decision' => $decision,
|
||||||
'notes' => $notes,
|
'notes' => $notes,
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ class AdditionalChargeModel extends Model
|
|||||||
'description' => 'permit_empty|string',
|
'description' => 'permit_empty|string',
|
||||||
'amount' => 'required|decimal',
|
'amount' => 'required|decimal',
|
||||||
'due_date' => 'permit_empty|valid_date',
|
'due_date' => 'permit_empty|valid_date',
|
||||||
'status' => 'required|in_list[pending,applied]',
|
'status' => 'required|in_list[pending,applied,voided]',
|
||||||
'created_by' => 'permit_empty|integer',
|
'created_by' => 'permit_empty|integer',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use CodeIgniter\Model;
|
|
||||||
|
|
||||||
|
|
||||||
class PayPalPaymentModel extends Model
|
|
||||||
{
|
|
||||||
protected $table = 'paypal_payments';
|
|
||||||
protected $primaryKey = 'id';
|
|
||||||
protected $allowedFields = [
|
|
||||||
'webhook_id',
|
|
||||||
'parent_school_id',
|
|
||||||
'order_id',
|
|
||||||
'transaction_id',
|
|
||||||
'status',
|
|
||||||
'amount',
|
|
||||||
'currency',
|
|
||||||
'paypal_fee',
|
|
||||||
'net_amount',
|
|
||||||
'payer_email',
|
|
||||||
'merchant_id',
|
|
||||||
'event_type',
|
|
||||||
'summary',
|
|
||||||
'raw_payload',
|
|
||||||
'synced',
|
|
||||||
'semester',
|
|
||||||
'school_year',
|
|
||||||
'sync_attempts'
|
|
||||||
];
|
|
||||||
|
|
||||||
// Enable timestamps
|
|
||||||
protected $useTimestamps = true;
|
|
||||||
protected $createdField = 'created_at';
|
|
||||||
protected $updatedField = ''; // not used; leave empty if not needed
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -17,6 +17,7 @@ class PaymentModel extends Model
|
|||||||
'paid_amount',
|
'paid_amount',
|
||||||
'balance',
|
'balance',
|
||||||
'number_of_installments',
|
'number_of_installments',
|
||||||
|
'installment_seq',
|
||||||
'transaction_id',
|
'transaction_id',
|
||||||
'check_file',
|
'check_file',
|
||||||
'check_number',
|
'check_number',
|
||||||
@@ -114,6 +115,7 @@ class PaymentModel extends Model
|
|||||||
->selectSum('paid_amount', 'total_paid')
|
->selectSum('paid_amount', 'total_paid')
|
||||||
->where('parent_id', $parentId)
|
->where('parent_id', $parentId)
|
||||||
->where('school_year', $schoolYear)
|
->where('school_year', $schoolYear)
|
||||||
|
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
|
||||||
->get()
|
->get()
|
||||||
->getRowArray();
|
->getRowArray();
|
||||||
|
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace App\Models;
|
|
||||||
|
|
||||||
use CodeIgniter\Model;
|
|
||||||
|
|
||||||
class PaypalTransactionModel extends Model
|
|
||||||
{
|
|
||||||
protected $table = 'paypal_transactions';
|
|
||||||
protected $primaryKey = 'id';
|
|
||||||
|
|
||||||
protected $allowedFields = [
|
|
||||||
'transaction_id',
|
|
||||||
'payment_id',
|
|
||||||
'firstname',
|
|
||||||
'lastname',
|
|
||||||
'event_type',
|
|
||||||
'payer_email',
|
|
||||||
'amount',
|
|
||||||
'currency',
|
|
||||||
'status',
|
|
||||||
'payment_method',
|
|
||||||
'transaction_fee',
|
|
||||||
'semester',
|
|
||||||
'school_year',
|
|
||||||
'raw_data'
|
|
||||||
];
|
|
||||||
|
|
||||||
protected $useTimestamps = true;
|
|
||||||
}
|
|
||||||
@@ -11,10 +11,9 @@ class StudentDecisionModel extends Model
|
|||||||
|
|
||||||
protected $allowedFields = [
|
protected $allowedFields = [
|
||||||
'student_id',
|
'student_id',
|
||||||
'semester',
|
|
||||||
'school_year',
|
'school_year',
|
||||||
'class_section_name',
|
'class_section_name',
|
||||||
'semester_score',
|
'year_score',
|
||||||
'decision',
|
'decision',
|
||||||
'source',
|
'source',
|
||||||
'notes',
|
'notes',
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ class FeeCalculationService
|
|||||||
// Retrieve fee configs
|
// Retrieve fee configs
|
||||||
$firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350);
|
$firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350);
|
||||||
$secondStudentFee = (float) ($configModel->getConfig('second_student_fee') ?? 200);
|
$secondStudentFee = (float) ($configModel->getConfig('second_student_fee') ?? 200);
|
||||||
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 180);
|
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 200);
|
||||||
|
|
||||||
// Assign tuition_fee to all students (before filtering refunds)
|
// Assign tuition_fee to all students (before filtering refunds)
|
||||||
$regularCount = 0;
|
$regularCount = 0;
|
||||||
@@ -148,7 +148,7 @@ class FeeCalculationService
|
|||||||
|
|
||||||
$firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350);
|
$firstStudentFee = (float) ($configModel->getConfig('first_student_fee') ?? 350);
|
||||||
$secondStudentFee = (float) ($configModel->getConfig('second_student_fee') ?? 200);
|
$secondStudentFee = (float) ($configModel->getConfig('second_student_fee') ?? 200);
|
||||||
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 180);
|
$youthFee = (float) ($configModel->getConfig('youth_fee') ?? 200);
|
||||||
|
|
||||||
// ✅ Pre-fetch and assign grade/class section names before sorting
|
// ✅ Pre-fetch and assign grade/class section names before sorting
|
||||||
foreach ($students as &$student) {
|
foreach ($students as &$student) {
|
||||||
|
|||||||
@@ -38,11 +38,14 @@ foreach ($statsPerClass as $csid => $cs) {
|
|||||||
if (!isset($gradeGroups[$sortKey])) {
|
if (!isset($gradeGroups[$sortKey])) {
|
||||||
$gradeGroups[$sortKey] = ['label' => $label, 'slug' => $slug, 'csids' => []];
|
$gradeGroups[$sortKey] = ['label' => $label, 'slug' => $slug, 'csids' => []];
|
||||||
}
|
}
|
||||||
|
|
||||||
$gradeGroups[$sortKey]['csids'][] = $csid;
|
$gradeGroups[$sortKey]['csids'][] = $csid;
|
||||||
}
|
}
|
||||||
|
|
||||||
ksort($gradeGroups);
|
ksort($gradeGroups);
|
||||||
$gradeKeys = array_keys($gradeGroups);
|
|
||||||
$defaultKey = $gradeKeys[0] ?? null;
|
$gradeKeys = array_keys($gradeGroups);
|
||||||
|
$defaultKey = $gradeKeys[0] ?? null;
|
||||||
|
|
||||||
$decisionBadge = [
|
$decisionBadge = [
|
||||||
'Pass' => 'success',
|
'Pass' => 'success',
|
||||||
@@ -54,14 +57,20 @@ $decisionBadge = [
|
|||||||
];
|
];
|
||||||
?>
|
?>
|
||||||
|
|
||||||
<h2 class="text-center mt-4 mb-3"><i class="bi bi-award me-2"></i>Generate Certificates</h2>
|
<h2 class="text-center mt-4 mb-3">
|
||||||
|
<i class="bi bi-award me-2"></i>Generate Certificates
|
||||||
|
</h2>
|
||||||
|
|
||||||
<!-- School year filter -->
|
<!-- School year filter -->
|
||||||
<div class="d-flex justify-content-end mb-3">
|
<div class="d-flex justify-content-end mb-3">
|
||||||
<form method="get" action="<?= site_url('administrator/certificates') ?>" class="d-flex gap-2 align-items-center">
|
<form method="get" action="<?= site_url('administrator/certificates') ?>" class="d-flex gap-2 align-items-center">
|
||||||
<label class="form-label mb-0 me-1 text-muted small">School Year</label>
|
<label class="form-label mb-0 me-1 text-muted small">School Year</label>
|
||||||
<input type="text" name="school_year" class="form-control form-control-sm" style="width:130px;"
|
<input type="text"
|
||||||
value="<?= esc($schoolYear) ?>" placeholder="e.g. 2024-2025">
|
name="school_year"
|
||||||
|
class="form-control form-control-sm"
|
||||||
|
style="width:130px;"
|
||||||
|
value="<?= esc($schoolYear) ?>"
|
||||||
|
placeholder="e.g. 2024-2025">
|
||||||
<button type="submit" class="btn btn-sm btn-outline-primary">
|
<button type="submit" class="btn btn-sm btn-outline-primary">
|
||||||
<i class="bi bi-arrow-repeat me-1"></i>Reload
|
<i class="bi bi-arrow-repeat me-1"></i>Reload
|
||||||
</button>
|
</button>
|
||||||
@@ -82,167 +91,228 @@ $decisionBadge = [
|
|||||||
<!-- Grade tabs -->
|
<!-- Grade tabs -->
|
||||||
<ul class="nav nav-tabs justify-content-center" id="certTabs" role="tablist" style="flex-wrap:wrap;row-gap:.25rem;">
|
<ul class="nav nav-tabs justify-content-center" id="certTabs" role="tablist" style="flex-wrap:wrap;row-gap:.25rem;">
|
||||||
<?php foreach ($gradeGroups as $key => $group): ?>
|
<?php foreach ($gradeGroups as $key => $group): ?>
|
||||||
<?php
|
<?php
|
||||||
$slug = $group['slug'];
|
$slug = $group['slug'];
|
||||||
$label = $group['label'];
|
$label = $group['label'];
|
||||||
$total = array_sum(array_map(fn($id) => $statsPerClass[$id]['total'] ?? 0, $group['csids']));
|
$total = array_sum(array_map(fn($id) => $statsPerClass[$id]['total'] ?? 0, $group['csids']));
|
||||||
$grpPass = array_sum(array_map(fn($id) => $statsPerClass[$id]['pass'] ?? 0, $group['csids']));
|
$grpPass = array_sum(array_map(fn($id) => $statsPerClass[$id]['pass'] ?? 0, $group['csids']));
|
||||||
$grpCert = array_sum(array_map(fn($id) => $statsPerClass[$id]['cert'] ?? 0, $group['csids']));
|
$grpCert = array_sum(array_map(fn($id) => $statsPerClass[$id]['cert'] ?? 0, $group['csids']));
|
||||||
$fullyDone = $grpPass > 0 && $grpCert >= $grpPass;
|
$fullyDone = $grpPass > 0 && $grpCert >= $grpPass;
|
||||||
$hasPass = $grpPass > 0;
|
$hasPass = $grpPass > 0;
|
||||||
$isActive = ($key === $defaultKey);
|
$isActive = ($key === $defaultKey);
|
||||||
$statusTitle = $hasPass
|
|
||||||
? ($fullyDone ? 'Fully generated (' . $grpCert . '/' . $grpPass . ')' : 'Not fully generated (' . $grpCert . '/' . $grpPass . ')')
|
$statusTitle = $hasPass
|
||||||
: 'No eligible students';
|
? ($fullyDone ? 'Fully generated (' . $grpCert . '/' . $grpPass . ')' : 'Not fully generated (' . $grpCert . '/' . $grpPass . ')')
|
||||||
?>
|
: 'No eligible students';
|
||||||
<li class="nav-item" role="presentation">
|
?>
|
||||||
<a class="nav-link <?= $isActive ? 'active' : '' ?>"
|
|
||||||
id="cert-<?= esc($slug) ?>-tab"
|
<li class="nav-item" role="presentation">
|
||||||
data-bs-toggle="tab"
|
<a class="nav-link <?= $isActive ? 'active' : '' ?>"
|
||||||
href="#cert-<?= esc($slug) ?>"
|
id="cert-<?= esc($slug) ?>-tab"
|
||||||
role="tab"
|
data-bs-toggle="tab"
|
||||||
aria-controls="cert-<?= esc($slug) ?>"
|
href="#cert-<?= esc($slug) ?>"
|
||||||
aria-selected="<?= $isActive ? 'true' : 'false' ?>">
|
role="tab"
|
||||||
<span class="cert-status-dot <?= !$hasPass ? 'no-eligible' : ($fullyDone ? 'done' : 'pending') ?>"
|
aria-controls="cert-<?= esc($slug) ?>"
|
||||||
title="<?= esc($statusTitle) ?>"></span>
|
aria-selected="<?= $isActive ? 'true' : 'false' ?>">
|
||||||
<?= esc($label) ?>
|
<span class="cert-status-dot <?= !$hasPass ? 'no-eligible' : ($fullyDone ? 'done' : 'pending') ?>"
|
||||||
<span class="badge bg-secondary ms-1"><?= $total ?></span>
|
title="<?= esc($statusTitle) ?>"></span>
|
||||||
</a>
|
<?= esc($label) ?>
|
||||||
</li>
|
<span class="badge bg-secondary ms-1"><?= $total ?></span>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<!-- Tab content -->
|
<!-- Tab content -->
|
||||||
<div class="tab-content mt-3" id="certTabContent">
|
<div class="tab-content mt-3" id="certTabContent">
|
||||||
<?php foreach ($gradeGroups as $key => $group): ?>
|
<?php foreach ($gradeGroups as $key => $group): ?>
|
||||||
<?php $isActive = ($key === $defaultKey); ?>
|
<?php $isActive = ($key === $defaultKey); ?>
|
||||||
<div class="tab-pane fade <?= $isActive ? 'show active' : '' ?>"
|
|
||||||
id="cert-<?= esc($group['slug']) ?>"
|
|
||||||
role="tabpanel"
|
|
||||||
aria-labelledby="cert-<?= esc($group['slug']) ?>-tab">
|
|
||||||
|
|
||||||
<?php foreach ($group['csids'] as $csid): ?>
|
<div class="tab-pane fade <?= $isActive ? 'show active' : '' ?>"
|
||||||
<?php
|
id="cert-<?= esc($group['slug']) ?>"
|
||||||
$cs = $statsPerClass[$csid];
|
role="tabpanel"
|
||||||
$students = $studentsByClass[$csid] ?? [];
|
aria-labelledby="cert-<?= esc($group['slug']) ?>-tab">
|
||||||
$csPass = $cs['pass'];
|
|
||||||
$csCert = $cs['cert'];
|
|
||||||
$csRemain = max(0, $csPass - $csCert);
|
|
||||||
$formId = 'certForm-' . $csid;
|
|
||||||
$tableId = 'studentsTable-' . $csid;
|
|
||||||
?>
|
|
||||||
|
|
||||||
<h4 class="mt-4 mb-2 text-center"><?= esc($cs['name']) ?></h4>
|
<?php foreach ($group['csids'] as $csid): ?>
|
||||||
|
<?php
|
||||||
|
$cs = $statsPerClass[$csid];
|
||||||
|
$students = $studentsByClass[$csid] ?? [];
|
||||||
|
$csPass = $cs['pass'];
|
||||||
|
$csCert = $cs['cert'];
|
||||||
|
$csRemain = max(0, $csPass - $csCert);
|
||||||
|
$formId = 'certForm-' . $csid;
|
||||||
|
$tableId = 'studentsTable-' . $csid;
|
||||||
|
?>
|
||||||
|
|
||||||
<?php if (empty($students)): ?>
|
<h4 class="mt-4 mb-2 text-center"><?= esc($cs['name']) ?></h4>
|
||||||
<p class="text-muted text-center">No active students.</p>
|
|
||||||
<?php else: ?>
|
|
||||||
|
|
||||||
<form method="post" action="<?= site_url('administrator/certificates/generate') ?>"
|
<?php if (empty($students)): ?>
|
||||||
id="<?= esc($formId) ?>" class="cert-form mb-5">
|
<p class="text-muted text-center">No active students.</p>
|
||||||
<?= csrf_field() ?>
|
<?php else: ?>
|
||||||
<input type="hidden" name="class_section_id" value="<?= (int)$csid ?>">
|
|
||||||
<input type="hidden" name="school_year" value="<?= esc($schoolYear) ?>">
|
|
||||||
|
|
||||||
<!-- Stats + date picker -->
|
<form method="post"
|
||||||
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
|
action="<?= site_url('administrator/certificates/generate') ?>"
|
||||||
<div class="d-flex align-items-center gap-4 flex-wrap">
|
id="<?= esc($formId) ?>"
|
||||||
<span class="fw-semibold">
|
class="cert-form mb-5">
|
||||||
Students <span class="badge bg-secondary ms-1"><?= count($students) ?></span>
|
<?= csrf_field() ?>
|
||||||
</span>
|
|
||||||
<span class="text-muted small">
|
|
||||||
<strong class="text-success"><?= $csPass ?></strong> Pass
|
|
||||||
</span>
|
|
||||||
<span class="text-muted small">
|
|
||||||
<strong class="text-primary"><?= $csCert ?></strong> Generated
|
|
||||||
</span>
|
|
||||||
<span class="text-muted small">
|
|
||||||
<strong class="<?= $csRemain > 0 ? 'text-warning' : 'text-muted' ?>"><?= $csRemain ?></strong> Remaining
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="input-group input-group-sm" style="width:200px;">
|
|
||||||
<span class="input-group-text"><i class="bi bi-calendar3"></i></span>
|
|
||||||
<input type="date" class="form-control cert-date-picker"
|
|
||||||
value="<?= date('Y-m-d') ?>" title="Certificate date">
|
|
||||||
<input type="hidden" name="cert_date" class="cert-date-hidden" value="<?= esc($certDate) ?>">
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Student table -->
|
<input type="hidden" name="class_section_id" value="<?= (int)$csid ?>">
|
||||||
<div class="table-responsive">
|
<input type="hidden" name="school_year" value="<?= esc($schoolYear) ?>">
|
||||||
<table class="table table-hover table-striped align-middle mb-0 cert-students-table"
|
|
||||||
id="<?= esc($tableId) ?>">
|
<!-- Stats + date picker -->
|
||||||
<thead class="table-light">
|
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
|
||||||
<tr>
|
<div class="d-flex align-items-center gap-4 flex-wrap">
|
||||||
<th style="width:40px;" class="text-center">
|
<span class="fw-semibold">
|
||||||
<input class="form-check-input cert-select-all" type="checkbox">
|
Students <span class="badge bg-secondary ms-1"><?= count($students) ?></span>
|
||||||
</th>
|
</span>
|
||||||
<th>First Name</th>
|
<span class="text-muted small">
|
||||||
<th>Last Name</th>
|
<strong class="text-success"><?= $csPass ?></strong> Pass
|
||||||
<th>Decision</th>
|
</span>
|
||||||
<th>Certificate No.</th>
|
<span class="text-muted small">
|
||||||
</tr>
|
<strong class="text-primary"><?= $csCert ?></strong> Generated
|
||||||
</thead>
|
</span>
|
||||||
<tbody>
|
<span class="text-muted small">
|
||||||
<?php foreach ($students as $s): ?>
|
<strong class="<?= $csRemain > 0 ? 'text-warning' : 'text-muted' ?>">
|
||||||
<?php
|
<?= $csRemain ?>
|
||||||
$sid = (int)$s['student_id'];
|
</strong>
|
||||||
$stuDec = $decisionsByStudent[$sid] ?? [];
|
Remaining
|
||||||
$certNo = $certsByStudent[$sid] ?? null;
|
</span>
|
||||||
$allDecs = array_map(fn($d) => $d['decision'], $stuDec);
|
</div>
|
||||||
$hasPending = in_array('', $allDecs, true);
|
|
||||||
$unique = array_values(array_unique(array_filter($allDecs, fn($d) => $d !== '')));
|
<div class="input-group input-group-sm" style="width:200px;">
|
||||||
$isPass = !empty($stuDec) && !$hasPending && $unique === ['Pass'];
|
<span class="input-group-text"><i class="bi bi-calendar3"></i></span>
|
||||||
$displayDecs = $isPass ? ['Pass'] : array_values(array_filter($unique, fn($d) => $d !== 'Pass'));
|
<input type="date"
|
||||||
?>
|
class="form-control cert-date-picker"
|
||||||
<tr>
|
value="<?= date('Y-m-d') ?>"
|
||||||
<td class="text-center">
|
title="Certificate date">
|
||||||
<input class="form-check-input cert-student-check" type="checkbox"
|
<input type="hidden"
|
||||||
name="student_ids[]" value="<?= $sid ?>"
|
name="cert_date"
|
||||||
<?= $isPass ? '' : 'disabled' ?>>
|
class="cert-date-hidden"
|
||||||
</td>
|
value="<?= esc($certDate) ?>">
|
||||||
<td><?= esc($s['firstname']) ?></td>
|
</div>
|
||||||
<td><?= esc($s['lastname']) ?></td>
|
</div>
|
||||||
<td>
|
|
||||||
<?php if (empty($stuDec)): ?>
|
<!-- Student table -->
|
||||||
<span class="text-muted small">—</span>
|
<div class="table-responsive">
|
||||||
<?php elseif ($hasPending || empty($unique) || empty($displayDecs)): ?>
|
<table class="table table-hover table-striped align-middle mb-0 cert-students-table"
|
||||||
<span class="badge bg-warning text-dark">Pending</span>
|
id="<?= esc($tableId) ?>">
|
||||||
<?php else: ?>
|
<thead class="table-light">
|
||||||
<?php foreach ($displayDecs as $dec): $color = $decisionBadge[$dec] ?? 'secondary'; ?>
|
<tr>
|
||||||
<span class="badge bg-<?= esc($color) ?> me-1"><?= esc($dec) ?></span>
|
<th style="width:40px;" class="text-center">
|
||||||
|
<input class="form-check-input cert-select-all" type="checkbox">
|
||||||
|
</th>
|
||||||
|
<th>First Name</th>
|
||||||
|
<th>Last Name</th>
|
||||||
|
<th class="text-center">Year Score</th>
|
||||||
|
<th>Decision</th>
|
||||||
|
<th>Certificate No.</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
|
||||||
|
<tbody>
|
||||||
|
<?php foreach ($students as $s): ?>
|
||||||
|
<?php
|
||||||
|
$sid = (int)$s['student_id'];
|
||||||
|
$stuDec = $decisionsByStudent[$sid] ?? [];
|
||||||
|
$certNo = $certsByStudent[$sid] ?? null;
|
||||||
|
|
||||||
|
$allDecs = array_map(
|
||||||
|
fn($d) => trim((string)($d['decision'] ?? '')),
|
||||||
|
$stuDec
|
||||||
|
);
|
||||||
|
|
||||||
|
$hasPending = in_array('', $allDecs, true);
|
||||||
|
|
||||||
|
$unique = array_values(array_unique(array_filter(
|
||||||
|
$allDecs,
|
||||||
|
fn($d) => $d !== ''
|
||||||
|
)));
|
||||||
|
|
||||||
|
$isPass = !empty($stuDec) && !$hasPending && $unique === ['Pass'];
|
||||||
|
|
||||||
|
$displayDecs = $isPass
|
||||||
|
? ['Pass']
|
||||||
|
: array_values(array_filter($unique, fn($d) => $d !== 'Pass'));
|
||||||
|
|
||||||
|
$yearScore = null;
|
||||||
|
|
||||||
|
foreach ($stuDec as $d) {
|
||||||
|
if (
|
||||||
|
array_key_exists('year_score', $d)
|
||||||
|
&& $d['year_score'] !== null
|
||||||
|
&& $d['year_score'] !== ''
|
||||||
|
) {
|
||||||
|
$yearScore = $d['year_score'];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$fmtYearScore = is_numeric($yearScore)
|
||||||
|
? number_format((float)$yearScore, 2)
|
||||||
|
: '—';
|
||||||
|
?>
|
||||||
|
|
||||||
|
<tr>
|
||||||
|
<td class="text-center">
|
||||||
|
<input class="form-check-input cert-student-check"
|
||||||
|
type="checkbox"
|
||||||
|
name="student_ids[]"
|
||||||
|
value="<?= $sid ?>"
|
||||||
|
<?= $isPass ? '' : 'disabled' ?>>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
<td><?= esc($s['firstname']) ?></td>
|
||||||
|
<td><?= esc($s['lastname']) ?></td>
|
||||||
|
|
||||||
|
<td class="text-center fw-semibold">
|
||||||
|
<?= esc($fmtYearScore) ?>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
<td>
|
||||||
|
<?php if (empty($stuDec)): ?>
|
||||||
|
<span class="text-muted small">—</span>
|
||||||
|
<?php elseif ($hasPending || empty($unique) || empty($displayDecs)): ?>
|
||||||
|
<span class="badge bg-warning text-dark">Pending</span>
|
||||||
|
<?php else: ?>
|
||||||
|
<?php foreach ($displayDecs as $dec): ?>
|
||||||
|
<?php $color = $decisionBadge[$dec] ?? 'secondary'; ?>
|
||||||
|
<span class="badge bg-<?= esc($color) ?> me-1">
|
||||||
|
<?= esc($dec) ?>
|
||||||
|
</span>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
<?php endif; ?>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
<td>
|
||||||
|
<?php if ($certNo): ?>
|
||||||
|
<a href="<?= site_url('administrator/certificates/reprint/' . rawurlencode($certNo)) ?>"
|
||||||
|
target="_blank"
|
||||||
|
class="font-monospace small">
|
||||||
|
<?= esc($certNo) ?>
|
||||||
|
</a>
|
||||||
|
<?php else: ?>
|
||||||
|
<span class="text-muted">—</span>
|
||||||
|
<?php endif; ?>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
<?php endif; ?>
|
</tbody>
|
||||||
</td>
|
</table>
|
||||||
<td>
|
</div>
|
||||||
<?php if ($certNo): ?>
|
|
||||||
<a href="<?= site_url('administrator/certificates/reprint/' . rawurlencode($certNo)) ?>"
|
|
||||||
target="_blank" class="font-monospace small">
|
|
||||||
<?= esc($certNo) ?>
|
|
||||||
</a>
|
|
||||||
<?php else: ?>
|
|
||||||
<span class="text-muted">—</span>
|
|
||||||
<?php endif; ?>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
<?php endforeach; ?>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Footer -->
|
<!-- Footer -->
|
||||||
<div class="d-flex justify-content-between align-items-center mt-2">
|
<div class="d-flex justify-content-between align-items-center mt-2">
|
||||||
<span class="text-muted small cert-selected-count">0 students selected</span>
|
<span class="text-muted small cert-selected-count">0 students selected</span>
|
||||||
<button type="submit" class="btn btn-success cert-generate-btn" disabled>
|
<button type="submit" class="btn btn-success cert-generate-btn" disabled>
|
||||||
<i class="bi bi-printer me-1"></i>Generate & Print Certificates
|
<i class="bi bi-printer me-1"></i>Generate & Print Certificates
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -253,44 +323,102 @@ $decisionBadge = [
|
|||||||
|
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
const csrfRefreshUrl = <?= json_encode(site_url('administrator/certificates/csrf-token'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
|
const csrfRefreshUrl = <?= json_encode(site_url('administrator/certificates/csrf-token'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
|
||||||
let currentCsrfTokenName = <?= json_encode(csrf_token(), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
|
let currentCsrfTokenName = <?= json_encode(csrf_token(), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
|
||||||
|
|
||||||
function cssEscape(v) {
|
function cssEscape(v) {
|
||||||
return window.CSS?.escape ? window.CSS.escape(v) : String(v).replace(/(["\\.#:[\],= ])/g, '\\$1');
|
return window.CSS?.escape ? window.CSS.escape(v) : String(v).replace(/(["\\.#:[\],= ])/g, '\\$1');
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateCsrfInForm(form, name, hash) {
|
function updateCsrfInForm(form, name, hash) {
|
||||||
if (!form || !name || !hash) return;
|
if (!form || !name || !hash) return;
|
||||||
|
|
||||||
form.querySelectorAll('input[type="hidden"]').forEach(inp => {
|
form.querySelectorAll('input[type="hidden"]').forEach(inp => {
|
||||||
if (inp.name === name || inp.name === currentCsrfTokenName) { inp.name = name; inp.value = hash; }
|
if (inp.name === name || inp.name === currentCsrfTokenName) {
|
||||||
|
inp.name = name;
|
||||||
|
inp.value = hash;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let inp = form.querySelector(`input[name="${cssEscape(name)}"]`);
|
let inp = form.querySelector(`input[name="${cssEscape(name)}"]`);
|
||||||
if (!inp) { inp = document.createElement('input'); inp.type = 'hidden'; inp.name = name; form.appendChild(inp); }
|
|
||||||
|
if (!inp) {
|
||||||
|
inp = document.createElement('input');
|
||||||
|
inp.type = 'hidden';
|
||||||
|
inp.name = name;
|
||||||
|
form.appendChild(inp);
|
||||||
|
}
|
||||||
|
|
||||||
inp.value = hash;
|
inp.value = hash;
|
||||||
currentCsrfTokenName = name;
|
currentCsrfTokenName = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refreshCsrf(form) {
|
async function refreshCsrf(form) {
|
||||||
const r = await fetch(csrfRefreshUrl, { method: 'GET', credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest', 'Cache-Control': 'no-store' } });
|
const r = await fetch(csrfRefreshUrl, {
|
||||||
|
method: 'GET',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: {
|
||||||
|
'X-Requested-With': 'XMLHttpRequest',
|
||||||
|
'Cache-Control': 'no-store'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
if (!r.ok) throw new Error('CSRF refresh failed');
|
if (!r.ok) throw new Error('CSRF refresh failed');
|
||||||
|
|
||||||
const d = await r.json();
|
const d = await r.json();
|
||||||
if (d?.csrf_token && d?.csrf_hash) updateCsrfInForm(form, d.csrf_token, d.csrf_hash);
|
|
||||||
|
if (d?.csrf_token && d?.csrf_hash) {
|
||||||
|
updateCsrfInForm(form, d.csrf_token, d.csrf_hash);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let pdfWindow = null, activePdfBlobUrl = null;
|
let pdfWindow = null;
|
||||||
|
let activePdfBlobUrl = null;
|
||||||
|
|
||||||
function openPdfWindow() {
|
function openPdfWindow() {
|
||||||
if (!pdfWindow || pdfWindow.closed) pdfWindow = window.open('', 'certificatePdfWindow');
|
if (!pdfWindow || pdfWindow.closed) {
|
||||||
|
pdfWindow = window.open('', 'certificatePdfWindow');
|
||||||
|
}
|
||||||
|
|
||||||
if (!pdfWindow) return null;
|
if (!pdfWindow) return null;
|
||||||
|
|
||||||
pdfWindow.document.open();
|
pdfWindow.document.open();
|
||||||
pdfWindow.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Certificate PDF</title>
|
pdfWindow.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>Certificate PDF</title>
|
||||||
<style>html,body{margin:0;height:100%;background:#f3f4f6;font-family:Arial,sans-serif}.viewer-shell{display:flex;flex-direction:column;height:100%}.viewer-status{padding:12px 16px;background:#111827;color:#fff;font-size:14px}.viewer-frame{flex:1;width:100%;border:0;background:#cbd5e1}</style></head>
|
<style>
|
||||||
<body><div class="viewer-shell"><div class="viewer-status" id="viewerStatus">Preparing certificate PDF...</div><iframe class="viewer-frame" id="pdfFrame"></iframe></div>
|
html,body{margin:0;height:100%;background:#f3f4f6;font-family:Arial,sans-serif}
|
||||||
<script>window.showCertificatePdf=function(url,fn){const f=document.getElementById('pdfFrame'),s=document.getElementById('viewerStatus');if(s)s.textContent=fn?'Showing '+fn:'Certificate PDF ready';if(f)f.src=url;document.title=fn||'Certificate PDF'};<\/script></body></html>`);
|
.viewer-shell{display:flex;flex-direction:column;height:100%}
|
||||||
|
.viewer-status{padding:12px 16px;background:#111827;color:#fff;font-size:14px}
|
||||||
|
.viewer-frame{flex:1;width:100%;border:0;background:#cbd5e1}
|
||||||
|
</style></head>
|
||||||
|
<body>
|
||||||
|
<div class="viewer-shell">
|
||||||
|
<div class="viewer-status" id="viewerStatus">Preparing certificate PDF...</div>
|
||||||
|
<iframe class="viewer-frame" id="pdfFrame"></iframe>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
window.showCertificatePdf=function(url,fn){
|
||||||
|
const f=document.getElementById('pdfFrame'),s=document.getElementById('viewerStatus');
|
||||||
|
if(s)s.textContent=fn?'Showing '+fn:'Certificate PDF ready';
|
||||||
|
if(f)f.src=url;
|
||||||
|
document.title=fn||'Certificate PDF';
|
||||||
|
};
|
||||||
|
<\/script>
|
||||||
|
</body></html>`);
|
||||||
|
|
||||||
pdfWindow.document.close();
|
pdfWindow.document.close();
|
||||||
|
|
||||||
return pdfWindow;
|
return pdfWindow;
|
||||||
}
|
}
|
||||||
|
|
||||||
function showError(pane, msg) {
|
function showError(pane, msg) {
|
||||||
let el = pane.querySelector('.cert-inline-error');
|
let el = pane.querySelector('.cert-inline-error');
|
||||||
if (!el) { el = document.createElement('div'); el.className = 'alert alert-danger alert-dismissible fade show cert-inline-error'; pane.prepend(el); }
|
|
||||||
|
if (!el) {
|
||||||
|
el = document.createElement('div');
|
||||||
|
el.className = 'alert alert-danger alert-dismissible fade show cert-inline-error';
|
||||||
|
pane.prepend(el);
|
||||||
|
}
|
||||||
|
|
||||||
el.innerHTML = `${msg}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
|
el.innerHTML = `${msg}<button type="button" class="btn-close" data-bs-dismiss="alert"></button>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,62 +435,134 @@ $decisionBadge = [
|
|||||||
if (datePicker && dateHidden) {
|
if (datePicker && dateHidden) {
|
||||||
datePicker.addEventListener('change', function () {
|
datePicker.addEventListener('change', function () {
|
||||||
const d = new Date(this.value + 'T00:00:00');
|
const d = new Date(this.value + 'T00:00:00');
|
||||||
if (!isNaN(d)) dateHidden.value = String(d.getMonth()+1).padStart(2,'0')+'/'+String(d.getDate()).padStart(2,'0')+'/'+d.getFullYear();
|
|
||||||
|
if (!isNaN(d)) {
|
||||||
|
dateHidden.value =
|
||||||
|
String(d.getMonth() + 1).padStart(2, '0') + '/' +
|
||||||
|
String(d.getDate()).padStart(2, '0') + '/' +
|
||||||
|
d.getFullYear();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateState() {
|
function updateState() {
|
||||||
const chosen = form.querySelectorAll('.cert-student-check:checked').length;
|
const chosen = form.querySelectorAll('.cert-student-check:checked').length;
|
||||||
if (selectedCount) selectedCount.textContent = chosen + ' student' + (chosen !== 1 ? 's' : '') + ' selected';
|
|
||||||
if (generateBtn) generateBtn.disabled = chosen === 0;
|
if (selectedCount) {
|
||||||
|
selectedCount.textContent = chosen + ' student' + (chosen !== 1 ? 's' : '') + ' selected';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (generateBtn) {
|
||||||
|
generateBtn.disabled = chosen === 0;
|
||||||
|
}
|
||||||
|
|
||||||
if (selectAll) {
|
if (selectAll) {
|
||||||
const ec = eligibleChecks.length;
|
const ec = eligibleChecks.length;
|
||||||
selectAll.checked = ec > 0 && chosen === ec;
|
selectAll.checked = ec > 0 && chosen === ec;
|
||||||
selectAll.indeterminate = chosen > 0 && chosen < ec;
|
selectAll.indeterminate = chosen > 0 && chosen < ec;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (selectAll) {
|
if (selectAll) {
|
||||||
selectAll.addEventListener('change', function () {
|
selectAll.addEventListener('change', function () {
|
||||||
eligibleChecks.forEach(c => { c.checked = this.checked; });
|
eligibleChecks.forEach(c => {
|
||||||
|
c.checked = this.checked;
|
||||||
|
});
|
||||||
|
|
||||||
updateState();
|
updateState();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
checks.forEach(c => c.addEventListener('change', updateState));
|
checks.forEach(c => c.addEventListener('change', updateState));
|
||||||
updateState();
|
updateState();
|
||||||
|
|
||||||
form.addEventListener('submit', async function (e) {
|
form.addEventListener('submit', async function (e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
const chosen = form.querySelectorAll('.cert-student-check:checked').length;
|
const chosen = form.querySelectorAll('.cert-student-check:checked').length;
|
||||||
if (chosen === 0) { showError(pane, 'Please select at least one student.'); return; }
|
|
||||||
|
if (chosen === 0) {
|
||||||
|
showError(pane, 'Please select at least one student.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const win = openPdfWindow();
|
const win = openPdfWindow();
|
||||||
if (!win) { showError(pane, 'Unable to open PDF tab — please allow pop-ups.'); return; }
|
|
||||||
|
if (!win) {
|
||||||
|
showError(pane, 'Unable to open PDF tab — please allow pop-ups.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const origHtml = generateBtn.innerHTML;
|
const origHtml = generateBtn.innerHTML;
|
||||||
generateBtn.disabled = true;
|
generateBtn.disabled = true;
|
||||||
generateBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Generating...';
|
generateBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Generating...';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await refreshCsrf(form);
|
await refreshCsrf(form);
|
||||||
|
|
||||||
const csrfVal = form.querySelector(`input[name="${cssEscape(currentCsrfTokenName)}"]`)?.value || '';
|
const csrfVal = form.querySelector(`input[name="${cssEscape(currentCsrfTokenName)}"]`)?.value || '';
|
||||||
const fd = new FormData(form);
|
const fd = new FormData(form);
|
||||||
if (csrfVal) fd.set(currentCsrfTokenName, csrfVal);
|
|
||||||
const resp = await fetch(form.action, { method: 'POST', body: fd, credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } });
|
if (csrfVal) {
|
||||||
const nn = resp.headers.get('X-CSRF-TOKEN-NAME'), nh = resp.headers.get('X-CSRF-TOKEN');
|
fd.set(currentCsrfTokenName, csrfVal);
|
||||||
if (nn && nh) updateCsrfInForm(form, nn, nh);
|
}
|
||||||
|
|
||||||
|
const resp = await fetch(form.action, {
|
||||||
|
method: 'POST',
|
||||||
|
body: fd,
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: {
|
||||||
|
'X-Requested-With': 'XMLHttpRequest'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const nn = resp.headers.get('X-CSRF-TOKEN-NAME');
|
||||||
|
const nh = resp.headers.get('X-CSRF-TOKEN');
|
||||||
|
|
||||||
|
if (nn && nh) {
|
||||||
|
updateCsrfInForm(form, nn, nh);
|
||||||
|
}
|
||||||
|
|
||||||
const ct = resp.headers.get('Content-Type') || '';
|
const ct = resp.headers.get('Content-Type') || '';
|
||||||
|
|
||||||
if (!resp.ok || !ct.toLowerCase().includes('application/pdf')) {
|
if (!resp.ok || !ct.toLowerCase().includes('application/pdf')) {
|
||||||
let msg = 'Certificate generation failed.';
|
let msg = 'Certificate generation failed.';
|
||||||
try { const d = await resp.json(); if (d?.error) msg = d.error; } catch (_) { try { msg = await resp.text() || msg; } catch (_2) {} }
|
|
||||||
win.close(); showError(pane, msg);
|
try {
|
||||||
|
const d = await resp.json();
|
||||||
|
|
||||||
|
if (d?.error) {
|
||||||
|
msg = d.error;
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
try {
|
||||||
|
msg = await resp.text() || msg;
|
||||||
|
} catch (_2) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
win.close();
|
||||||
|
showError(pane, msg);
|
||||||
await refreshCsrf(form).catch(() => {});
|
await refreshCsrf(form).catch(() => {});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const disp = resp.headers.get('Content-Disposition') || '';
|
const disp = resp.headers.get('Content-Disposition') || '';
|
||||||
const fn = (disp.match(/filename="?([^"]+)"?/i) || [])[1] || 'Certificates.pdf';
|
const fn = (disp.match(/filename="?([^"]+)"?/i) || [])[1] || 'Certificates.pdf';
|
||||||
const url = URL.createObjectURL(await resp.blob());
|
const url = URL.createObjectURL(await resp.blob());
|
||||||
if (activePdfBlobUrl) URL.revokeObjectURL(activePdfBlobUrl);
|
|
||||||
|
if (activePdfBlobUrl) {
|
||||||
|
URL.revokeObjectURL(activePdfBlobUrl);
|
||||||
|
}
|
||||||
|
|
||||||
activePdfBlobUrl = url;
|
activePdfBlobUrl = url;
|
||||||
win.showCertificatePdf(url, fn);
|
win.showCertificatePdf(url, fn);
|
||||||
|
|
||||||
const activePane = form.closest('.tab-pane');
|
const activePane = form.closest('.tab-pane');
|
||||||
if (activePane?.id) window.location.hash = activePane.id;
|
|
||||||
|
if (activePane?.id) {
|
||||||
|
window.location.hash = activePane.id;
|
||||||
|
}
|
||||||
|
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
showError(pane, 'Certificate generation failed. Please try again.');
|
showError(pane, 'Certificate generation failed. Please try again.');
|
||||||
@@ -376,43 +576,64 @@ $decisionBadge = [
|
|||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<?= $this->endSection() ?>
|
||||||
|
|
||||||
<?= $this->section('scripts') ?>
|
<?= $this->section('scripts') ?>
|
||||||
<script>
|
<script>
|
||||||
// Restore tab from hash — runs after Bootstrap is loaded
|
// Restore tab from hash — runs after Bootstrap is loaded
|
||||||
(function () {
|
(function () {
|
||||||
const hash = window.location.hash;
|
const hash = window.location.hash;
|
||||||
|
|
||||||
if (!hash) return;
|
if (!hash) return;
|
||||||
|
|
||||||
const tabLink = document.querySelector('a[href="' + hash + '"][data-bs-toggle="tab"]');
|
const tabLink = document.querySelector('a[href="' + hash + '"][data-bs-toggle="tab"]');
|
||||||
|
|
||||||
if (tabLink && window.bootstrap?.Tab) {
|
if (tabLink && window.bootstrap?.Tab) {
|
||||||
new bootstrap.Tab(tabLink).show();
|
new bootstrap.Tab(tabLink).show();
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.cert-status-dot {
|
.cert-status-dot {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
width: 8px; height: 8px;
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
margin-right: 5px;
|
margin-right: 5px;
|
||||||
vertical-align: middle;
|
vertical-align: middle;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
.cert-status-dot.done { background-color: #198754; }
|
|
||||||
.cert-status-dot.pending { background-color: #dc3545; }
|
.cert-status-dot.done {
|
||||||
.cert-status-dot.no-eligible { background-color: #adb5bd; }
|
background-color: #198754;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cert-status-dot.pending {
|
||||||
|
background-color: #dc3545;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cert-status-dot.no-eligible {
|
||||||
|
background-color: #adb5bd;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
if (!window.$ || !$.fn?.DataTable) return;
|
if (!window.$ || !$.fn?.DataTable) return;
|
||||||
|
|
||||||
$(function () {
|
$(function () {
|
||||||
document.querySelectorAll('.cert-students-table').forEach(function (tbl) {
|
document.querySelectorAll('.cert-students-table').forEach(function (tbl) {
|
||||||
if ($.fn.DataTable.isDataTable(tbl)) return;
|
if ($.fn.DataTable.isDataTable(tbl)) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$(tbl).DataTable({
|
$(tbl).DataTable({
|
||||||
order: [[1, 'asc'], [2, 'asc']],
|
order: [[1, 'asc'], [2, 'asc']],
|
||||||
pageLength: 100,
|
pageLength: 100,
|
||||||
lengthMenu: [25, 50, 100, 200],
|
lengthMenu: [25, 50, 100, 200],
|
||||||
columnDefs: [{ orderable: false, targets: [0, 3, 4] }]
|
columnDefs: [
|
||||||
|
{ orderable: false, targets: [0, 4, 5] }
|
||||||
|
]
|
||||||
});
|
});
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
});
|
});
|
||||||
@@ -420,5 +641,3 @@ $decisionBadge = [
|
|||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
<?= $this->endSection() ?>
|
<?= $this->endSection() ?>
|
||||||
|
|
||||||
<?= $this->endSection() ?>
|
|
||||||
|
|||||||
@@ -1,84 +0,0 @@
|
|||||||
<?= $this->extend('layout/management_layout') ?>
|
|
||||||
<?= $this->section('content') ?>
|
|
||||||
<div class="container-fluid">
|
|
||||||
<div class="wrapper">
|
|
||||||
<div class="content"></div>
|
|
||||||
<h2 class="text-center mt-4 mb-3">PayPal Transactions</h2>
|
|
||||||
<?= $this->include('partials/academic_filter') ?>
|
|
||||||
<!-- Export Button -->
|
|
||||||
<div class="d-flex gap-2 mb-3 justify-content-end">
|
|
||||||
<a href="<?= base_url('admin/paypal-transactions/export') . ($keyword ? '?q=' . urlencode($keyword) : '') ?>"
|
|
||||||
class="btn btn-success">
|
|
||||||
Export CSV
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
<!-- Search Form -->
|
|
||||||
<!--
|
|
||||||
<form method="get" action="<?= base_url('admin/paypal-transactions') ?>" class="mb-3">
|
|
||||||
<?= csrf_field(); ?>
|
|
||||||
<div class="input-group">
|
|
||||||
<input type="text" name="q" value="<?= esc($keyword) ?>" class="form-control"
|
|
||||||
placeholder="Search by transaction ID, email, order ID, or event type">
|
|
||||||
<button type="submit" class="btn btn-primary">Search</button>
|
|
||||||
<?php if ($keyword): ?>
|
|
||||||
<a href="<?= base_url('admin/paypal-transactions') ?>" class="btn btn-secondary">Clear</a>
|
|
||||||
<?php endif; ?>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
-->
|
|
||||||
|
|
||||||
<!-- Transactions Table -->
|
|
||||||
<table id="myTable" class="display table table-striped">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>ID</th>
|
|
||||||
<th>Transaction ID</th>
|
|
||||||
<th>Order ID</th>
|
|
||||||
<th>Parent School ID</th>
|
|
||||||
<th>Email</th>
|
|
||||||
<th>Amount</th>
|
|
||||||
<th>Net Amount</th>
|
|
||||||
<th>Currency</th>
|
|
||||||
<th>Status</th>
|
|
||||||
<th>Event Type</th>
|
|
||||||
<th>Date</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<?php foreach ($transactions as $t): ?>
|
|
||||||
<tr>
|
|
||||||
<td><?= esc($t['id']) ?></td>
|
|
||||||
<td><?= esc($t['transaction_id']) ?></td>
|
|
||||||
<td><?= esc($t['order_id']) ?></td>
|
|
||||||
<td><?= esc($t['parent_school_id']) ?></td>
|
|
||||||
<td><?= esc($t['payer_email']) ?></td>
|
|
||||||
<td>$<?= esc(number_format($t['amount'], 2)) ?></td>
|
|
||||||
<td>$<?= esc(number_format($t['net_amount'], 2)) ?></td>
|
|
||||||
<td><?= esc($t['currency']) ?></td>
|
|
||||||
<td><?= esc($t['status']) ?></td>
|
|
||||||
<td><?= esc($t['event_type']) ?></td>
|
|
||||||
<td><?= esc(local_datetime($t['created_at'], 'm-d-Y H:i')) ?></td>
|
|
||||||
</tr>
|
|
||||||
<?php endforeach; ?>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
<!-- Pagination -->
|
|
||||||
<div class="d-flex justify-content-center">
|
|
||||||
<?= $pager->links() ?>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<?= $this->endSection() ?>
|
|
||||||
|
|
||||||
<?= $this->section('scripts') ?>
|
|
||||||
<script>
|
|
||||||
$(document).ready(function() {
|
|
||||||
$('#myTable').DataTable({
|
|
||||||
"order": [
|
|
||||||
[0, "desc"]
|
|
||||||
],
|
|
||||||
"pageLength": 10
|
|
||||||
});
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
<?= $this->endSection() ?>
|
|
||||||
@@ -14,6 +14,97 @@ $totalConfirmed = array_sum(array_column($classResults, 'confirmed'));
|
|||||||
$totalSurprise = array_sum(array_column($classResults, 'surprises'));
|
$totalSurprise = array_sum(array_column($classResults, 'surprises'));
|
||||||
$totalMissed = array_sum(array_column($classResults, 'missed'));
|
$totalMissed = array_sum(array_column($classResults, 'missed'));
|
||||||
$overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted * 100) : ($totalActual === 0 ? 100 : 0);
|
$overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted * 100) : ($totalActual === 0 ? 100 : 0);
|
||||||
|
|
||||||
|
$pct = static function (int $count, int $total): string {
|
||||||
|
return $total > 0 ? number_format(($count / $total) * 100, 1) . '%' : '0.0%';
|
||||||
|
};
|
||||||
|
|
||||||
|
$genderKey = static function (?string $gender): string {
|
||||||
|
$value = strtolower(trim((string)$gender));
|
||||||
|
|
||||||
|
return match (true) {
|
||||||
|
in_array($value, ['male', 'm', 'boy', 'boys'], true) => 'boys',
|
||||||
|
in_array($value, ['female', 'f', 'girl', 'girls'], true) => 'girls',
|
||||||
|
default => 'other',
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
$genderStats = static function (array $items) use ($genderKey): array {
|
||||||
|
$stats = ['boys' => 0, 'girls' => 0, 'other' => 0];
|
||||||
|
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$stats[$genderKey($item['gender'] ?? '')]++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $stats;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Winner gender breakdown.
|
||||||
|
// "Winner" means actual year-end trophy winner.
|
||||||
|
$totalWinnerBoys = 0;
|
||||||
|
$totalWinnerGirls = 0;
|
||||||
|
$totalWinnerOther = 0;
|
||||||
|
$allStudentsFlat = [];
|
||||||
|
$passStudents = [];
|
||||||
|
$trophyStudents = [];
|
||||||
|
|
||||||
|
// Sticker names.
|
||||||
|
// 2 columns x 7 rows = 14 stickers per page.
|
||||||
|
// Stickers print name and class section.
|
||||||
|
$stickerColumns = 2;
|
||||||
|
$stickerRows = 7;
|
||||||
|
$stickerWidthInches = 4.0;
|
||||||
|
$stickerHeightInches = 1.33;
|
||||||
|
$stickerPrintablePageWidthInches = 8.0;
|
||||||
|
$stickerPrintablePageHeightInches = 10.5;
|
||||||
|
$stickersPerPage = $stickerColumns * $stickerRows;
|
||||||
|
$winnerStickers = [];
|
||||||
|
|
||||||
|
foreach ($classResults as $cls) {
|
||||||
|
foreach (($cls['students'] ?? []) as $s) {
|
||||||
|
$allStudentsFlat[] = $s;
|
||||||
|
|
||||||
|
if (isset($s['year_score']) && is_numeric($s['year_score']) && (float)$s['year_score'] >= 60) {
|
||||||
|
$passStudents[] = $s;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (empty($s['actual'])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$trophyStudents[] = $s;
|
||||||
|
|
||||||
|
$gender = strtolower(trim((string)($s['gender'] ?? '')));
|
||||||
|
|
||||||
|
if (in_array($gender, ['male', 'm', 'boy', 'boys'], true)) {
|
||||||
|
$totalWinnerBoys++;
|
||||||
|
} elseif (in_array($gender, ['female', 'f', 'girl', 'girls'], true)) {
|
||||||
|
$totalWinnerGirls++;
|
||||||
|
} else {
|
||||||
|
$totalWinnerOther++;
|
||||||
|
}
|
||||||
|
|
||||||
|
$name = trim((string)($s['name'] ?? ''));
|
||||||
|
$sectionName = trim((string)($cls['section_name'] ?? ''));
|
||||||
|
|
||||||
|
if ($name !== '') {
|
||||||
|
$winnerStickers[] = [
|
||||||
|
'name' => $name,
|
||||||
|
'section' => $sectionName,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$totalWinners = $totalWinnerBoys + $totalWinnerGirls + $totalWinnerOther;
|
||||||
|
|
||||||
|
$winnerBoysPct = $totalWinners > 0 ? round(($totalWinnerBoys / $totalWinners) * 100, 1) : 0;
|
||||||
|
$winnerGirlsPct = $totalWinners > 0 ? round(($totalWinnerGirls / $totalWinners) * 100, 1) : 0;
|
||||||
|
$winnerOtherPct = $totalWinners > 0 ? round(($totalWinnerOther / $totalWinners) * 100, 1) : 0;
|
||||||
|
$allGenderStats = $genderStats($allStudentsFlat);
|
||||||
|
$passGenderStats = $genderStats($passStudents);
|
||||||
|
$trophyGenderStats = $genderStats($trophyStudents);
|
||||||
|
$totalPass = count($passStudents);
|
||||||
?>
|
?>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
@@ -23,23 +114,168 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
.status-none { color:#adb5bd; }
|
.status-none { color:#adb5bd; }
|
||||||
|
|
||||||
.print-only { display: none !important; }
|
.print-only { display: none !important; }
|
||||||
|
.winner-sticker-print-area { display: none; }
|
||||||
|
|
||||||
|
@page {
|
||||||
|
size: Letter portrait;
|
||||||
|
margin: 0.25in;
|
||||||
|
}
|
||||||
|
|
||||||
@media print {
|
@media print {
|
||||||
.no-print { display: none !important; }
|
.no-print { display: none !important; }
|
||||||
.print-only { display: block !important; }
|
.print-only { display: block !important; }
|
||||||
.screen-only { display: none !important; }
|
.screen-only { display: none !important; }
|
||||||
|
|
||||||
body { font-size: 11px; }
|
body { font-size: 11px; }
|
||||||
.container-fluid { padding: 0 !important; }
|
.container-fluid { padding: 0 !important; }
|
||||||
h2, h3 { font-size: 13px; margin-bottom: .3rem; }
|
h2, h3 { font-size: 13px; margin-bottom: .3rem; }
|
||||||
.print-page-break { break-before: page; }
|
.print-page-break { break-before: page; }
|
||||||
|
|
||||||
table { width: 100%; border-collapse: collapse; font-size: 10px; }
|
table { width: 100%; border-collapse: collapse; font-size: 10px; }
|
||||||
table th, table td { border: 1px solid #bbb; padding: 3px 5px; }
|
table th, table td { border: 1px solid #bbb; padding: 3px 5px; }
|
||||||
table thead { background: #333 !important; color: #fff !important;
|
table thead {
|
||||||
-webkit-print-color-adjust: exact; print-color-adjust: exact; }
|
background: #333 !important;
|
||||||
table thead th { position: static !important; top: auto !important; box-shadow: none !important; }
|
color: #fff !important;
|
||||||
|
-webkit-print-color-adjust: exact;
|
||||||
|
print-color-adjust: exact;
|
||||||
|
}
|
||||||
|
table thead th {
|
||||||
|
position: static !important;
|
||||||
|
top: auto !important;
|
||||||
|
box-shadow: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
.s-confirmed { color: #198754; font-weight: bold; }
|
.s-confirmed { color: #198754; font-weight: bold; }
|
||||||
.s-surprise { color: #0d6efd; font-weight: bold; }
|
.s-surprise { color: #0d6efd; font-weight: bold; }
|
||||||
.s-missed { color: #fd7e14; font-weight: bold; }
|
.s-missed { color: #fd7e14; font-weight: bold; }
|
||||||
|
|
||||||
|
body.print-stickers-mode {
|
||||||
|
margin: 0 !important;
|
||||||
|
padding: 0 !important;
|
||||||
|
background: #fff !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode * {
|
||||||
|
box-shadow: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode header,
|
||||||
|
body.print-stickers-mode nav,
|
||||||
|
body.print-stickers-mode aside,
|
||||||
|
body.print-stickers-mode footer,
|
||||||
|
body.print-stickers-mode .navbar,
|
||||||
|
body.print-stickers-mode .sidebar,
|
||||||
|
body.print-stickers-mode .topbar,
|
||||||
|
body.print-stickers-mode .app-header,
|
||||||
|
body.print-stickers-mode .main-header,
|
||||||
|
body.print-stickers-mode .layout-header,
|
||||||
|
body.print-stickers-mode .management-header,
|
||||||
|
body.print-stickers-mode .page-header,
|
||||||
|
body.print-stickers-mode .breadcrumb,
|
||||||
|
body.print-stickers-mode .brand,
|
||||||
|
body.print-stickers-mode .logo,
|
||||||
|
body.print-stickers-mode .header,
|
||||||
|
body.print-stickers-mode .no-print,
|
||||||
|
body.print-stickers-mode .screen-only,
|
||||||
|
body.print-stickers-mode .print-only {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode .container-fluid > *:not(#winnerStickerPrintArea) {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode .container-fluid {
|
||||||
|
display: block !important;
|
||||||
|
visibility: visible !important;
|
||||||
|
padding: 0 !important;
|
||||||
|
margin: 0 !important;
|
||||||
|
width: 100% !important;
|
||||||
|
max-width: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode #winnerStickerPrintArea {
|
||||||
|
display: block !important;
|
||||||
|
visibility: visible !important;
|
||||||
|
position: static !important;
|
||||||
|
width: 100% !important;
|
||||||
|
height: auto !important;
|
||||||
|
margin: 0 !important;
|
||||||
|
padding: 0 !important;
|
||||||
|
overflow: visible !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode #winnerStickerPrintArea,
|
||||||
|
body.print-stickers-mode #winnerStickerPrintArea * {
|
||||||
|
visibility: visible !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode .sticker-page {
|
||||||
|
display: grid !important;
|
||||||
|
grid-template-columns: repeat(<?= $stickerColumns ?>, <?= rtrim(rtrim(number_format($stickerWidthInches, 2, '.', ''), '0'), '.') ?>in);
|
||||||
|
grid-template-rows: repeat(<?= $stickerRows ?>, <?= rtrim(rtrim(number_format($stickerHeightInches, 2, '.', ''), '0'), '.') ?>in);
|
||||||
|
gap: 0;
|
||||||
|
width: <?= rtrim(rtrim(number_format($stickerPrintablePageWidthInches, 2, '.', ''), '0'), '.') ?>in;
|
||||||
|
height: <?= rtrim(rtrim(number_format($stickerPrintablePageHeightInches, 2, '.', ''), '0'), '.') ?>in;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
align-content: start;
|
||||||
|
justify-content: center;
|
||||||
|
page-break-inside: avoid;
|
||||||
|
break-inside: avoid-page;
|
||||||
|
page-break-after: always;
|
||||||
|
break-after: page;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode .sticker-page:last-child {
|
||||||
|
page-break-after: auto;
|
||||||
|
break-after: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode .sticker-cell {
|
||||||
|
display: flex !important;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
text-align: center;
|
||||||
|
border: none;
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
min-height: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
width: <?= rtrim(rtrim(number_format($stickerWidthInches, 2, '.', ''), '0'), '.') ?>in;
|
||||||
|
height: <?= rtrim(rtrim(number_format($stickerHeightInches, 2, '.', ''), '0'), '.') ?>in;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode .sticker-name {
|
||||||
|
display: block !important;
|
||||||
|
font-size: 18pt;
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.1;
|
||||||
|
color: #000 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode .sticker-content {
|
||||||
|
display: flex !important;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 100%;
|
||||||
|
transform: translateY(0.22in);
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode .sticker-section {
|
||||||
|
display: block !important;
|
||||||
|
margin-top: 0.08in;
|
||||||
|
font-size: 10pt;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.1;
|
||||||
|
color: #000 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
body.print-stickers-mode .sticker-empty {
|
||||||
|
visibility: hidden !important;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
@@ -57,10 +293,16 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
with the <strong>year-end result</strong> based on the average of Fall & Spring scores.
|
with the <strong>year-end result</strong> based on the average of Fall & Spring scores.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="d-flex gap-2">
|
|
||||||
|
<div class="d-flex gap-2 flex-wrap">
|
||||||
<button onclick="printWithCharts()" class="btn btn-outline-secondary btn-sm">
|
<button onclick="printWithCharts()" class="btn btn-outline-secondary btn-sm">
|
||||||
<i class="bi bi-printer-fill me-1"></i>Print
|
<i class="bi bi-printer-fill me-1"></i>Print Stats
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<button onclick="printWinnerStickers()" class="btn btn-warning btn-sm">
|
||||||
|
<i class="bi bi-tags-fill me-1"></i>Print Winner Stickers
|
||||||
|
</button>
|
||||||
|
|
||||||
<a href="<?= site_url('administrator/trophy?' . http_build_query(['school_year' => $selectedYear, 'percentile' => $selectedPercentile])) ?>"
|
<a href="<?= site_url('administrator/trophy?' . http_build_query(['school_year' => $selectedYear, 'percentile' => $selectedPercentile])) ?>"
|
||||||
class="btn btn-outline-secondary btn-sm">
|
class="btn btn-outline-secondary btn-sm">
|
||||||
<i class="bi bi-arrow-left me-1"></i>Back
|
<i class="bi bi-arrow-left me-1"></i>Back
|
||||||
@@ -75,18 +317,27 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<label class="form-label mb-1 small fw-semibold">School Year</label>
|
<label class="form-label mb-1 small fw-semibold">School Year</label>
|
||||||
<select name="school_year" class="form-select form-select-sm" style="min-width:130px;">
|
<select name="school_year" class="form-select form-select-sm" style="min-width:130px;">
|
||||||
<?php foreach ($years as $yr): ?>
|
<?php foreach ($years as $yr): ?>
|
||||||
<option value="<?= esc($yr) ?>" <?= $yr === $selectedYear ? 'selected' : '' ?>><?= esc($yr) ?></option>
|
<option value="<?= esc($yr) ?>" <?= $yr === $selectedYear ? 'selected' : '' ?>>
|
||||||
|
<?= esc($yr) ?>
|
||||||
|
</option>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="col-auto">
|
<div class="col-auto">
|
||||||
<label class="form-label mb-1 small fw-semibold">Percentile</label>
|
<label class="form-label mb-1 small fw-semibold">Percentile</label>
|
||||||
<div class="input-group input-group-sm" style="width:110px;">
|
<div class="input-group input-group-sm" style="width:110px;">
|
||||||
<input type="number" name="percentile" class="form-control"
|
<input type="number"
|
||||||
min="1" max="99" step="1" value="<?= (int)$selectedPercentile ?>">
|
name="percentile"
|
||||||
|
class="form-control"
|
||||||
|
min="1"
|
||||||
|
max="99"
|
||||||
|
step="1"
|
||||||
|
value="<?= (int)$selectedPercentile ?>">
|
||||||
<span class="input-group-text">%</span>
|
<span class="input-group-text">%</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="col-auto">
|
<div class="col-auto">
|
||||||
<button type="submit" class="btn btn-primary btn-sm">Apply</button>
|
<button type="submit" class="btn btn-primary btn-sm">Apply</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -111,7 +362,7 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<div class="row g-3 mb-4">
|
<div class="row g-3 mb-4">
|
||||||
<?php foreach ([
|
<?php foreach ([
|
||||||
[$totalPredicted, 'Predicted (Fall)', 'primary', null, $totalStudents > 0 ? round($totalPredicted / $totalStudents * 100) . '% of students' : '—'],
|
[$totalPredicted, 'Predicted (Fall)', 'primary', null, $totalStudents > 0 ? round($totalPredicted / $totalStudents * 100) . '% of students' : '—'],
|
||||||
[$totalActual, 'Actual (Year)', 'warning', 'dark', $totalStudents > 0 ? round($totalActual / $totalStudents * 100) . '% of students' : '—'],
|
[$totalActual, 'Actual (Year)', 'warning', 'dark', $totalStudents > 0 ? round($totalActual / $totalStudents * 100) . '% of students' : '—'],
|
||||||
[$totalConfirmed, 'Confirmed', 'success', null, $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted * 100) . '% of predicted' : '—'],
|
[$totalConfirmed, 'Confirmed', 'success', null, $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted * 100) . '% of predicted' : '—'],
|
||||||
[$totalSurprise, 'Surprises', 'info', 'dark', 'Not in prediction'],
|
[$totalSurprise, 'Surprises', 'info', 'dark', 'Not in prediction'],
|
||||||
[$totalMissed, 'Missed', 'orange', null, 'Were predicted'],
|
[$totalMissed, 'Missed', 'orange', null, 'Were predicted'],
|
||||||
@@ -147,19 +398,29 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<span class="fw-bold fs-6"><?= esc($cls['section_name']) ?></span>
|
<span class="fw-bold fs-6"><?= esc($cls['section_name']) ?></span>
|
||||||
<span class="badge bg-primary"><?= $cls['predicted_count'] ?> predicted</span>
|
<span class="badge bg-primary"><?= $cls['predicted_count'] ?> predicted</span>
|
||||||
<span class="badge bg-warning text-dark"><?= $cls['actual_count'] ?> actual</span>
|
<span class="badge bg-warning text-dark"><?= $cls['actual_count'] ?> actual</span>
|
||||||
|
|
||||||
<?php if ($cls['confirmed'] > 0): ?>
|
<?php if ($cls['confirmed'] > 0): ?>
|
||||||
<span class="badge bg-success"><?= $cls['confirmed'] ?> confirmed</span>
|
<span class="badge bg-success"><?= $cls['confirmed'] ?> confirmed</span>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
|
||||||
<?php if ($cls['surprises'] > 0): ?>
|
<?php if ($cls['surprises'] > 0): ?>
|
||||||
<span class="badge bg-info text-dark"><?= $cls['surprises'] ?> surprise<?= $cls['surprises'] > 1 ? 's' : '' ?></span>
|
<span class="badge bg-info text-dark"><?= $cls['surprises'] ?> surprise<?= $cls['surprises'] > 1 ? 's' : '' ?></span>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
|
||||||
<?php if ($cls['missed'] > 0): ?>
|
<?php if ($cls['missed'] > 0): ?>
|
||||||
<span class="badge" style="background:#fd7e14"><?= $cls['missed'] ?> missed</span>
|
<span class="badge" style="background:#fd7e14"><?= $cls['missed'] ?> missed</span>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="d-flex gap-3 small align-items-center">
|
<div class="d-flex gap-3 small align-items-center">
|
||||||
<span class="text-muted">Fall ≥ <strong><?= $cls['fall_threshold'] !== null ? number_format((float)$cls['fall_threshold'], 1) : '—' ?></strong></span>
|
<span class="text-muted">
|
||||||
<span class="text-muted">Year ≥ <strong><?= $cls['year_threshold'] !== null ? number_format((float)$cls['year_threshold'], 1) : '—' ?></strong></span>
|
Fall ≥
|
||||||
|
<strong><?= $cls['fall_threshold'] !== null ? number_format((float)$cls['fall_threshold'], 1) : '—' ?></strong>
|
||||||
|
</span>
|
||||||
|
<span class="text-muted">
|
||||||
|
Year ≥
|
||||||
|
<strong><?= $cls['year_threshold'] !== null ? number_format((float)$cls['year_threshold'], 1) : '—' ?></strong>
|
||||||
|
</span>
|
||||||
<span class="fw-semibold">
|
<span class="fw-semibold">
|
||||||
Accuracy:
|
Accuracy:
|
||||||
<span class="<?= $cls['accuracy'] >= 80 ? 'text-success' : ($cls['accuracy'] >= 50 ? 'text-warning' : 'text-danger') ?>">
|
<span class="<?= $cls['accuracy'] >= 80 ? 'text-success' : ($cls['accuracy'] >= 50 ? 'text-warning' : 'text-danger') ?>">
|
||||||
@@ -168,6 +429,7 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card-body p-0">
|
<div class="card-body p-0">
|
||||||
<table class="table table-sm table-hover mb-0 align-middle" data-no-mgmt-sticky>
|
<table class="table table-sm table-hover mb-0 align-middle" data-no-mgmt-sticky>
|
||||||
<thead class="table-light">
|
<thead class="table-light">
|
||||||
@@ -183,12 +445,16 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<th class="text-center">Status</th>
|
<th class="text-center">Status</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
|
|
||||||
<tbody>
|
<tbody>
|
||||||
<?php $rank = 0; foreach ($cls['students'] as $s):
|
<?php $rank = 0; foreach ($cls['students'] as $s):
|
||||||
if ($s['status'] === 'none') continue;
|
if ($s['status'] === 'none') continue;
|
||||||
$rank++;
|
$rank++;
|
||||||
$isMale = strtolower($s['gender'] ?? '') === 'male';
|
|
||||||
$rowBg = match ($s['status']) {
|
$genderNorm = strtolower(trim((string)($s['gender'] ?? '')));
|
||||||
|
$isMale = in_array($genderNorm, ['male', 'm', 'boy'], true);
|
||||||
|
|
||||||
|
$rowBg = match ($s['status']) {
|
||||||
'confirmed' => 'table-success',
|
'confirmed' => 'table-success',
|
||||||
'surprise' => 'table-primary',
|
'surprise' => 'table-primary',
|
||||||
'missed' => 'table-warning',
|
'missed' => 'table-warning',
|
||||||
@@ -203,9 +469,9 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<?= $isMale ? 'M' : 'F' ?>
|
<?= $isMale ? 'M' : 'F' ?>
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td class="text-end small"><?= $s['fall_score'] !== null ? number_format($s['fall_score'], 1) : '<span class="text-muted">—</span>' ?></td>
|
<td class="text-end small"><?= $s['fall_score'] !== null ? number_format($s['fall_score'], 1) : '<span class="text-muted">—</span>' ?></td>
|
||||||
<td class="text-end small"><?= $s['spring_score'] !== null ? number_format($s['spring_score'], 1) : '<span class="text-muted">—</span>' ?></td>
|
<td class="text-end small"><?= $s['spring_score'] !== null ? number_format($s['spring_score'], 1) : '<span class="text-muted">—</span>' ?></td>
|
||||||
<td class="text-end small fw-semibold"><?= $s['year_score'] !== null ? number_format($s['year_score'], 1) : '<span class="text-muted">—</span>' ?></td>
|
<td class="text-end small fw-semibold"><?= $s['year_score'] !== null ? number_format($s['year_score'], 1) : '<span class="text-muted">—</span>' ?></td>
|
||||||
<td class="text-center small">
|
<td class="text-center small">
|
||||||
<?= $s['predicted']
|
<?= $s['predicted']
|
||||||
? '<span class="badge bg-primary">Yes</span>'
|
? '<span class="badge bg-primary">Yes</span>'
|
||||||
@@ -237,6 +503,7 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<div class="card-header bg-dark text-white fw-semibold py-2">
|
<div class="card-header bg-dark text-white fw-semibold py-2">
|
||||||
<i class="bi bi-bar-chart-fill me-2"></i>Prediction Accuracy Summary — <?= esc($selectedYear) ?>
|
<i class="bi bi-bar-chart-fill me-2"></i>Prediction Accuracy Summary — <?= esc($selectedYear) ?>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card-body p-0">
|
<div class="card-body p-0">
|
||||||
<table class="table table-sm table-bordered mb-0 align-middle" data-no-mgmt-sticky>
|
<table class="table table-sm table-bordered mb-0 align-middle" data-no-mgmt-sticky>
|
||||||
<thead class="table-dark">
|
<thead class="table-dark">
|
||||||
@@ -253,6 +520,7 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<th class="text-end pe-2">Year ≥</th>
|
<th class="text-end pe-2">Year ≥</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
|
|
||||||
<tbody>
|
<tbody>
|
||||||
<?php foreach ($classResults as $cls): ?>
|
<?php foreach ($classResults as $cls): ?>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -271,6 +539,7 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
</tr>
|
</tr>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|
||||||
<tfoot class="table-secondary fw-semibold">
|
<tfoot class="table-secondary fw-semibold">
|
||||||
<tr>
|
<tr>
|
||||||
<td class="ps-2">Total</td>
|
<td class="ps-2">Total</td>
|
||||||
@@ -292,7 +561,6 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
|
|
||||||
<!-- Charts -->
|
<!-- Charts -->
|
||||||
<div class="row g-4 mt-1 mb-4">
|
<div class="row g-4 mt-1 mb-4">
|
||||||
<!-- Grouped bar: predicted / actual / confirmed / surprises / missed per class -->
|
|
||||||
<div class="col-12 col-lg-8">
|
<div class="col-12 col-lg-8">
|
||||||
<div class="border rounded p-3 h-100">
|
<div class="border rounded p-3 h-100">
|
||||||
<div class="small fw-semibold text-muted mb-2">
|
<div class="small fw-semibold text-muted mb-2">
|
||||||
@@ -301,7 +569,7 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<canvas id="chart-counts" style="max-height:280px;"></canvas>
|
<canvas id="chart-counts" style="max-height:280px;"></canvas>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- Bar: accuracy % per class + doughnut overall breakdown -->
|
|
||||||
<div class="col-12 col-lg-4">
|
<div class="col-12 col-lg-4">
|
||||||
<div class="row g-3 h-100">
|
<div class="row g-3 h-100">
|
||||||
<div class="col-12">
|
<div class="col-12">
|
||||||
@@ -312,6 +580,7 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<canvas id="chart-accuracy" style="max-height:130px;"></canvas>
|
<canvas id="chart-accuracy" style="max-height:130px;"></canvas>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="col-12">
|
<div class="col-12">
|
||||||
<div class="border rounded p-3">
|
<div class="border rounded p-3">
|
||||||
<div class="small fw-semibold text-muted mb-2">
|
<div class="small fw-semibold text-muted mb-2">
|
||||||
@@ -324,6 +593,75 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Winner gender summary -->
|
||||||
|
<div class="card shadow-sm mt-2 mb-4">
|
||||||
|
<div class="card-header bg-dark text-white fw-semibold py-2">
|
||||||
|
<i class="bi bi-gender-ambiguous me-2"></i>Winner Gender Breakdown
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="row g-3 align-items-stretch">
|
||||||
|
<div class="col-12 col-lg-3">
|
||||||
|
<div class="border rounded p-3 text-center h-100">
|
||||||
|
<div class="text-muted small mb-1">Total Winners</div>
|
||||||
|
<div class="display-6 fw-bold"><?= (int)$totalWinners ?></div>
|
||||||
|
<div class="small text-muted">Actual year-end trophy winners</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="col-6 col-lg-3">
|
||||||
|
<div class="border rounded p-3 text-center h-100">
|
||||||
|
<div class="text-muted small mb-1">Boys</div>
|
||||||
|
<div class="display-6 fw-bold text-primary"><?= (int)$totalWinnerBoys ?></div>
|
||||||
|
<div class="fw-semibold"><?= number_format($winnerBoysPct, 1) ?>%</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="col-6 col-lg-3">
|
||||||
|
<div class="border rounded p-3 text-center h-100">
|
||||||
|
<div class="text-muted small mb-1">Girls</div>
|
||||||
|
<div class="display-6 fw-bold" style="color:#E47AB0;"><?= (int)$totalWinnerGirls ?></div>
|
||||||
|
<div class="fw-semibold"><?= number_format($winnerGirlsPct, 1) ?>%</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-3">
|
||||||
|
<div class="progress" style="height:26px;">
|
||||||
|
<?php if ($totalWinners > 0): ?>
|
||||||
|
<div class="progress-bar bg-primary"
|
||||||
|
role="progressbar"
|
||||||
|
style="width: <?= $winnerBoysPct ?>%;"
|
||||||
|
aria-valuenow="<?= $winnerBoysPct ?>"
|
||||||
|
aria-valuemin="0"
|
||||||
|
aria-valuemax="100">
|
||||||
|
Boys <?= number_format($winnerBoysPct, 1) ?>%
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="progress-bar"
|
||||||
|
role="progressbar"
|
||||||
|
style="width: <?= $winnerGirlsPct ?>%; background:#E47AB0;"
|
||||||
|
aria-valuenow="<?= $winnerGirlsPct ?>"
|
||||||
|
aria-valuemin="0"
|
||||||
|
aria-valuemax="100">
|
||||||
|
Girls <?= number_format($winnerGirlsPct, 1) ?>%
|
||||||
|
</div>
|
||||||
|
<?php else: ?>
|
||||||
|
<div class="progress-bar bg-secondary"
|
||||||
|
role="progressbar"
|
||||||
|
style="width: 100%;"
|
||||||
|
aria-valuenow="0"
|
||||||
|
aria-valuemin="0"
|
||||||
|
aria-valuemax="100">
|
||||||
|
No winners
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
</div><!-- /screen-only -->
|
</div><!-- /screen-only -->
|
||||||
|
|
||||||
<!-- ══ PRINT VIEW ════════════════════════════════════════════════════════ -->
|
<!-- ══ PRINT VIEW ════════════════════════════════════════════════════════ -->
|
||||||
@@ -340,7 +678,50 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- All students flat table -->
|
<h3 style="margin-bottom:6px;">Print Stats</h3>
|
||||||
|
<table data-no-mgmt-sticky style="margin-bottom:12px;">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Metric</th>
|
||||||
|
<th style="text-align:center;">Count</th>
|
||||||
|
<th style="text-align:center;">Percent</th>
|
||||||
|
<th style="text-align:center;">Boys</th>
|
||||||
|
<th style="text-align:center;">Boys %</th>
|
||||||
|
<th style="text-align:center;">Girls</th>
|
||||||
|
<th style="text-align:center;">Girls %</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td>Total Students</td>
|
||||||
|
<td style="text-align:center;"><?= $totalStudents ?></td>
|
||||||
|
<td style="text-align:center;">100.0%</td>
|
||||||
|
<td style="text-align:center;"><?= $allGenderStats['boys'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($allGenderStats['boys'], $totalStudents) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $allGenderStats['girls'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($allGenderStats['girls'], $totalStudents) ?></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Pass</td>
|
||||||
|
<td style="text-align:center;"><?= $totalPass ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($totalPass, $totalStudents) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $passGenderStats['boys'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($passGenderStats['boys'], $totalPass) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $passGenderStats['girls'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($passGenderStats['girls'], $totalPass) ?></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Trophies</td>
|
||||||
|
<td style="text-align:center;"><?= $totalWinners ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($totalWinners, $totalStudents) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $trophyGenderStats['boys'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($trophyGenderStats['boys'], $totalWinners) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $trophyGenderStats['girls'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($trophyGenderStats['girls'], $totalWinners) ?></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
<h3 style="margin-bottom:4px;">Student Detail</h3>
|
<h3 style="margin-bottom:4px;">Student Detail</h3>
|
||||||
<table data-no-mgmt-sticky>
|
<table data-no-mgmt-sticky>
|
||||||
<thead>
|
<thead>
|
||||||
@@ -357,14 +738,20 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<th style="text-align:center;">Status</th>
|
<th style="text-align:center;">Status</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
|
|
||||||
<tbody>
|
<tbody>
|
||||||
<?php
|
<?php
|
||||||
$rank = 0;
|
|
||||||
foreach ($classResults as $cls):
|
foreach ($classResults as $cls):
|
||||||
foreach ($cls['students'] as $s):
|
$classPrintRows = array_values(array_filter(
|
||||||
if (!in_array($s['status'], ['confirmed', 'surprise'], true)) continue;
|
$cls['students'],
|
||||||
$rank++;
|
static fn (array $student): bool => in_array($student['status'], ['confirmed', 'surprise'], true)
|
||||||
$isMale = strtolower($s['gender'] ?? '') === 'male';
|
));
|
||||||
|
$classPrintRows = array_reverse($classPrintRows);
|
||||||
|
|
||||||
|
foreach ($classPrintRows as $idx => $s):
|
||||||
|
$rank = count($classPrintRows) - $idx;
|
||||||
|
$genderNorm = strtolower(trim((string)($s['gender'] ?? '')));
|
||||||
|
$isMale = in_array($genderNorm, ['male', 'm', 'boy'], true);
|
||||||
$statusLabel = match ($s['status']) {
|
$statusLabel = match ($s['status']) {
|
||||||
'confirmed' => '✓ Confirmed',
|
'confirmed' => '✓ Confirmed',
|
||||||
'surprise' => '↑ Surprise',
|
'surprise' => '↑ Surprise',
|
||||||
@@ -378,18 +765,17 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<td><?= esc($cls['section_name']) ?></td>
|
<td><?= esc($cls['section_name']) ?></td>
|
||||||
<td><strong><?= esc($s['name']) ?></strong></td>
|
<td><strong><?= esc($s['name']) ?></strong></td>
|
||||||
<td style="text-align:center;"><?= $isMale ? 'M' : 'F' ?></td>
|
<td style="text-align:center;"><?= $isMale ? 'M' : 'F' ?></td>
|
||||||
<td style="text-align:right;"><?= $s['fall_score'] !== null ? number_format($s['fall_score'], 1) : '—' ?></td>
|
<td style="text-align:right;"><?= $s['fall_score'] !== null ? number_format($s['fall_score'], 1) : '—' ?></td>
|
||||||
<td style="text-align:right;"><?= $s['spring_score'] !== null ? number_format($s['spring_score'], 1) : '—' ?></td>
|
<td style="text-align:right;"><?= $s['spring_score'] !== null ? number_format($s['spring_score'], 1) : '—' ?></td>
|
||||||
<td style="text-align:right;font-weight:bold;"><?= $s['year_score'] !== null ? number_format($s['year_score'], 1) : '—' ?></td>
|
<td style="text-align:right;font-weight:bold;"><?= $s['year_score'] !== null ? number_format($s['year_score'], 1) : '—' ?></td>
|
||||||
<td style="text-align:center;"><?= $s['predicted'] ? 'Yes' : 'No' ?></td>
|
<td style="text-align:center;"><?= $s['predicted'] ? 'Yes' : 'No' ?></td>
|
||||||
<td style="text-align:center;"><?= $s['actual'] ? 'Yes' : 'No' ?></td>
|
<td style="text-align:center;"><?= $s['actual'] ? 'Yes' : 'No' ?></td>
|
||||||
<td style="text-align:center;" class="<?= $statusClass ?>"><?= $statusLabel ?></td>
|
<td style="text-align:center;" class="<?= $statusClass ?>"><?= $statusLabel ?></td>
|
||||||
</tr>
|
</tr>
|
||||||
<?php endforeach; endforeach; ?>
|
<?php endforeach; endforeach; ?>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
<!-- Accuracy summary (new page) -->
|
|
||||||
<div class="print-page-break"></div>
|
<div class="print-page-break"></div>
|
||||||
<h3 style="margin-bottom:4px;">Prediction Accuracy Summary</h3>
|
<h3 style="margin-bottom:4px;">Prediction Accuracy Summary</h3>
|
||||||
<table data-no-mgmt-sticky style="margin-bottom:14px;">
|
<table data-no-mgmt-sticky style="margin-bottom:14px;">
|
||||||
@@ -407,6 +793,7 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
<th style="text-align:right;">Year ≥</th>
|
<th style="text-align:right;">Year ≥</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
|
|
||||||
<tbody>
|
<tbody>
|
||||||
<?php foreach ($classResults as $cls): ?>
|
<?php foreach ($classResults as $cls): ?>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -423,6 +810,7 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
</tr>
|
</tr>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|
||||||
<tfoot>
|
<tfoot>
|
||||||
<tr>
|
<tr>
|
||||||
<td style="font-weight:bold;">Total</td>
|
<td style="font-weight:bold;">Total</td>
|
||||||
@@ -438,17 +826,18 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
</tfoot>
|
</tfoot>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
<!-- Charts as images (populated by JS before printing) -->
|
|
||||||
<div class="print-page-break"></div>
|
<div class="print-page-break"></div>
|
||||||
<h3 style="margin-bottom:6px;">Charts</h3>
|
<h3 style="margin-bottom:6px;">Charts</h3>
|
||||||
|
|
||||||
<div style="margin-bottom:14px;">
|
<div style="margin-bottom:14px;">
|
||||||
<p style="font-size:10px;font-weight:bold;margin:0 0 4px;">Trophy Counts per Class</p>
|
<p style="font-size:10px;font-weight:bold;margin:0 0 4px;">Trophy Counts per Class</p>
|
||||||
<img id="print-chart-counts" style="width:100%;max-height:220px;object-fit:contain;" src="" alt="">
|
<img id="print-chart-counts" style="width:100%;max-height:220px;object-fit:contain;" src="" alt="">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div style="display:flex;gap:16px;margin-bottom:14px;">
|
<div style="display:flex;gap:16px;margin-bottom:14px;">
|
||||||
<div style="flex:1;">
|
<div style="flex:1;">
|
||||||
<p style="font-size:10px;font-weight:bold;margin:0 0 4px;">Prediction Accuracy per Class</p>
|
<p style="font-size:10px;font-weight:bold;margin:0 0 4px;">Prediction Accuracy per Class</p>
|
||||||
<img id="print-chart-accuracy" style="width:100%;max-height:160px;object-fit:contain;" src="" alt="">
|
<img id="print-chart-accuracy" style="width:100%;max-height:160px;object-fit:contain;" src="" alt="">
|
||||||
</div>
|
</div>
|
||||||
<div style="flex:1;">
|
<div style="flex:1;">
|
||||||
<p style="font-size:10px;font-weight:bold;margin:0 0 4px;">Overall Outcome Breakdown</p>
|
<p style="font-size:10px;font-weight:bold;margin:0 0 4px;">Overall Outcome Breakdown</p>
|
||||||
@@ -456,8 +845,65 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:10px;border:1px solid #bbb;padding:8px;">
|
||||||
|
<p style="font-size:11px;font-weight:bold;margin:0 0 6px;">Winner Gender Breakdown</p>
|
||||||
|
|
||||||
|
<table data-no-mgmt-sticky>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Group</th>
|
||||||
|
<th style="text-align:center;">Winners</th>
|
||||||
|
<th style="text-align:center;">Percentage</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td>Boys</td>
|
||||||
|
<td style="text-align:center;"><?= (int)$totalWinnerBoys ?></td>
|
||||||
|
<td style="text-align:center;"><?= number_format($winnerBoysPct, 1) ?>%</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Girls</td>
|
||||||
|
<td style="text-align:center;"><?= (int)$totalWinnerGirls ?></td>
|
||||||
|
<td style="text-align:center;"><?= number_format($winnerGirlsPct, 1) ?>%</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
|
||||||
|
<tfoot>
|
||||||
|
<tr>
|
||||||
|
<td style="font-weight:bold;">Total Winners</td>
|
||||||
|
<td style="text-align:center;font-weight:bold;"><?= (int)$totalWinners ?></td>
|
||||||
|
<td style="text-align:center;font-weight:bold;"><?= $totalWinners > 0 ? '100.0%' : '0.0%' ?></td>
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
</div><!-- /print-only -->
|
</div><!-- /print-only -->
|
||||||
|
|
||||||
|
<!-- Winner sticker print area: names only, no header, no score, no class -->
|
||||||
|
<div id="winnerStickerPrintArea" class="winner-sticker-print-area">
|
||||||
|
<?php if (!empty($winnerStickers)): ?>
|
||||||
|
<?php foreach (array_chunk($winnerStickers, $stickersPerPage) as $chunk): ?>
|
||||||
|
<div class="sticker-page">
|
||||||
|
<?php foreach ($chunk as $winnerSticker): ?>
|
||||||
|
<div class="sticker-cell">
|
||||||
|
<div class="sticker-content">
|
||||||
|
<div class="sticker-name"><?= esc($winnerSticker['name']) ?></div>
|
||||||
|
<div class="sticker-section"><?= esc($winnerSticker['section']) ?></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
|
||||||
|
<?php for ($i = 0, $remaining = $stickersPerPage - count($chunk); $i < $remaining; $i++): ?>
|
||||||
|
<div class="sticker-cell sticker-empty"></div>
|
||||||
|
<?php endfor; ?>
|
||||||
|
</div>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -473,6 +919,7 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
$cSurprise = [];
|
$cSurprise = [];
|
||||||
$cMissed = [];
|
$cMissed = [];
|
||||||
$cAccuracy = [];
|
$cAccuracy = [];
|
||||||
|
|
||||||
foreach ($classResults as $cls) {
|
foreach ($classResults as $cls) {
|
||||||
$cLabels[] = $cls['section_name'];
|
$cLabels[] = $cls['section_name'];
|
||||||
$cPredicted[] = $cls['predicted_count'];
|
$cPredicted[] = $cls['predicted_count'];
|
||||||
@@ -483,94 +930,105 @@ $overallAccuracy = $totalPredicted > 0 ? round($totalConfirmed / $totalPredicted
|
|||||||
$cAccuracy[] = $cls['accuracy'];
|
$cAccuracy[] = $cls['accuracy'];
|
||||||
}
|
}
|
||||||
?>
|
?>
|
||||||
var labels = <?= json_encode($cLabels) ?>;
|
|
||||||
|
var labels = <?= json_encode($cLabels) ?>;
|
||||||
var predicted = <?= json_encode($cPredicted) ?>;
|
var predicted = <?= json_encode($cPredicted) ?>;
|
||||||
var actual = <?= json_encode($cActual) ?>;
|
var actual = <?= json_encode($cActual) ?>;
|
||||||
var confirmed = <?= json_encode($cConfirmed) ?>;
|
var confirmed = <?= json_encode($cConfirmed) ?>;
|
||||||
var surprises = <?= json_encode($cSurprise) ?>;
|
var surprises = <?= json_encode($cSurprise) ?>;
|
||||||
var missed = <?= json_encode($cMissed) ?>;
|
var missed = <?= json_encode($cMissed) ?>;
|
||||||
var accuracy = <?= json_encode($cAccuracy) ?>;
|
var accuracy = <?= json_encode($cAccuracy) ?>;
|
||||||
|
|
||||||
/* ── Chart 1: grouped bar – counts per class ── */
|
if (document.getElementById('chart-counts')) {
|
||||||
new Chart(document.getElementById('chart-counts'), {
|
new Chart(document.getElementById('chart-counts'), {
|
||||||
type: 'bar',
|
type: 'bar',
|
||||||
data: {
|
data: {
|
||||||
labels: labels,
|
labels: labels,
|
||||||
datasets: [
|
datasets: [
|
||||||
{ label: 'Predicted', data: predicted, backgroundColor: '#4A90E2', borderRadius: 3 },
|
{ label: 'Predicted', data: predicted, backgroundColor: '#4A90E2', borderRadius: 3 },
|
||||||
{ label: 'Actual', data: actual, backgroundColor: '#f0a500', borderRadius: 3 },
|
{ label: 'Actual', data: actual, backgroundColor: '#f0a500', borderRadius: 3 },
|
||||||
{ label: 'Confirmed', data: confirmed, backgroundColor: '#28a745', borderRadius: 3 },
|
{ label: 'Confirmed', data: confirmed, backgroundColor: '#28a745', borderRadius: 3 },
|
||||||
{ label: 'Surprises', data: surprises, backgroundColor: '#17a2b8', borderRadius: 3 },
|
{ label: 'Surprises', data: surprises, backgroundColor: '#17a2b8', borderRadius: 3 },
|
||||||
{ label: 'Missed', data: missed, backgroundColor: '#fd7e14', borderRadius: 3 },
|
{ label: 'Missed', data: missed, backgroundColor: '#fd7e14', borderRadius: 3 },
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
options: {
|
options: {
|
||||||
responsive: true,
|
responsive: true,
|
||||||
maintainAspectRatio: true,
|
maintainAspectRatio: true,
|
||||||
plugins: { legend: { position: 'bottom' } },
|
plugins: { legend: { position: 'bottom' } },
|
||||||
scales: {
|
scales: {
|
||||||
x: { grid: { color: '#f0f0f0' } },
|
x: { grid: { color: '#f0f0f0' } },
|
||||||
y: { beginAtZero: true, ticks: { stepSize: 1 }, grid: { color: '#f0f0f0' } }
|
y: { beginAtZero: true, ticks: { stepSize: 1 }, grid: { color: '#f0f0f0' } }
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/* ── Chart 2: accuracy % per class ── */
|
|
||||||
new Chart(document.getElementById('chart-accuracy'), {
|
|
||||||
type: 'bar',
|
|
||||||
data: {
|
|
||||||
labels: labels,
|
|
||||||
datasets: [{
|
|
||||||
label: 'Accuracy %',
|
|
||||||
data: accuracy,
|
|
||||||
backgroundColor: accuracy.map(function(a) {
|
|
||||||
return a >= 80 ? '#28a745' : a >= 50 ? '#f0a500' : '#dc3545';
|
|
||||||
}),
|
|
||||||
borderRadius: 3
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
maintainAspectRatio: true,
|
|
||||||
plugins: { legend: { display: false } },
|
|
||||||
scales: {
|
|
||||||
y: {
|
|
||||||
beginAtZero: true, max: 100,
|
|
||||||
ticks: { callback: function(v) { return v + '%'; } },
|
|
||||||
grid: { color: '#f0f0f0' }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
});
|
}
|
||||||
|
|
||||||
/* ── Chart 3: doughnut overall outcome breakdown ── */
|
if (document.getElementById('chart-accuracy')) {
|
||||||
new Chart(document.getElementById('chart-breakdown'), {
|
new Chart(document.getElementById('chart-accuracy'), {
|
||||||
type: 'doughnut',
|
type: 'bar',
|
||||||
data: {
|
data: {
|
||||||
labels: ['Confirmed', 'Surprises', 'Missed'],
|
labels: labels,
|
||||||
datasets: [{
|
datasets: [{
|
||||||
data: [<?= $totalConfirmed ?>, <?= $totalSurprise ?>, <?= $totalMissed ?>],
|
label: 'Accuracy %',
|
||||||
backgroundColor: ['#28a745', '#17a2b8', '#fd7e14'],
|
data: accuracy,
|
||||||
borderWidth: 2
|
backgroundColor: accuracy.map(function(a) {
|
||||||
}]
|
return a >= 80 ? '#28a745' : a >= 50 ? '#f0a500' : '#dc3545';
|
||||||
},
|
}),
|
||||||
options: {
|
borderRadius: 3
|
||||||
responsive: true,
|
}]
|
||||||
maintainAspectRatio: true,
|
},
|
||||||
plugins: {
|
options: {
|
||||||
legend: { position: 'bottom' },
|
responsive: true,
|
||||||
tooltip: {
|
maintainAspectRatio: true,
|
||||||
callbacks: {
|
plugins: { legend: { display: false } },
|
||||||
label: function(ctx) {
|
scales: {
|
||||||
var total = ctx.dataset.data.reduce(function(a, b) { return a + b; }, 0);
|
y: {
|
||||||
var pct = total > 0 ? Math.round(ctx.parsed / total * 100) : 0;
|
beginAtZero: true,
|
||||||
return ctx.label + ': ' + ctx.parsed + ' (' + pct + '%)';
|
max: 100,
|
||||||
|
ticks: {
|
||||||
|
callback: function(v) {
|
||||||
|
return v + '%';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
grid: { color: '#f0f0f0' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (document.getElementById('chart-breakdown')) {
|
||||||
|
new Chart(document.getElementById('chart-breakdown'), {
|
||||||
|
type: 'doughnut',
|
||||||
|
data: {
|
||||||
|
labels: ['Confirmed', 'Surprises', 'Missed'],
|
||||||
|
datasets: [{
|
||||||
|
data: [<?= $totalConfirmed ?>, <?= $totalSurprise ?>, <?= $totalMissed ?>],
|
||||||
|
backgroundColor: ['#28a745', '#17a2b8', '#fd7e14'],
|
||||||
|
borderWidth: 2
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
maintainAspectRatio: true,
|
||||||
|
plugins: {
|
||||||
|
legend: { position: 'bottom' },
|
||||||
|
tooltip: {
|
||||||
|
callbacks: {
|
||||||
|
label: function(ctx) {
|
||||||
|
var total = ctx.dataset.data.reduce(function(a, b) {
|
||||||
|
return a + b;
|
||||||
|
}, 0);
|
||||||
|
var pct = total > 0 ? Math.round(ctx.parsed / total * 100) : 0;
|
||||||
|
return ctx.label + ': ' + ctx.parsed + ' (' + pct + '%)';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
});
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
function captureCharts() {
|
function captureCharts() {
|
||||||
@@ -579,19 +1037,40 @@ function captureCharts() {
|
|||||||
'chart-accuracy': 'print-chart-accuracy',
|
'chart-accuracy': 'print-chart-accuracy',
|
||||||
'chart-breakdown': 'print-chart-breakdown',
|
'chart-breakdown': 'print-chart-breakdown',
|
||||||
};
|
};
|
||||||
|
|
||||||
Object.keys(map).forEach(function(canvasId) {
|
Object.keys(map).forEach(function(canvasId) {
|
||||||
var canvas = document.getElementById(canvasId);
|
var canvas = document.getElementById(canvasId);
|
||||||
var img = document.getElementById(map[canvasId]);
|
var img = document.getElementById(map[canvasId]);
|
||||||
if (canvas && img) img.src = canvas.toDataURL('image/png');
|
|
||||||
|
if (canvas && img) {
|
||||||
|
img.src = canvas.toDataURL('image/png');
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function printWithCharts() {
|
function printWithCharts() {
|
||||||
|
document.body.classList.remove('print-stickers-mode');
|
||||||
captureCharts();
|
captureCharts();
|
||||||
window.print();
|
window.print();
|
||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener('beforeprint', captureCharts);
|
function printWinnerStickers() {
|
||||||
|
document.body.classList.add('print-stickers-mode');
|
||||||
|
|
||||||
|
setTimeout(function () {
|
||||||
|
window.print();
|
||||||
|
|
||||||
|
setTimeout(function () {
|
||||||
|
document.body.classList.remove('print-stickers-mode');
|
||||||
|
}, 1000);
|
||||||
|
}, 250);
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('beforeprint', function () {
|
||||||
|
if (!document.body.classList.contains('print-stickers-mode')) {
|
||||||
|
captureCharts();
|
||||||
|
}
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
<?= $this->endSection() ?>
|
<?= $this->endSection() ?>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,265 @@
|
|||||||
|
<?= $this->extend('layout/management_layout') ?>
|
||||||
|
<?= $this->section('content') ?>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
$filters = $filters ?? [];
|
||||||
|
$result = $result ?? null;
|
||||||
|
$summary = $result['summary'] ?? [];
|
||||||
|
$mode = $filters['calculator_mode'] ?? 'compare';
|
||||||
|
$fmtMoney = static fn($value): string => '$' . number_format((float) $value, 2);
|
||||||
|
$warningText = static function (array $warnings): string {
|
||||||
|
$warnings = array_values(array_filter(array_map('trim', $warnings), 'strlen'));
|
||||||
|
return $warnings === [] ? 'None' : implode(' | ', $warnings);
|
||||||
|
};
|
||||||
|
?>
|
||||||
|
|
||||||
|
<div class="container-fluid mt-4">
|
||||||
|
<div class="d-flex flex-wrap justify-content-between align-items-end gap-3 mb-4">
|
||||||
|
<div>
|
||||||
|
<h2 class="mt-4 mb-1">Tuition Collection Forecast</h2>
|
||||||
|
<p class="text-muted mb-0">Uses actual enrollment families from the selected school year to compare old and new projected tuition income.</p>
|
||||||
|
</div>
|
||||||
|
<?php if ($result): ?>
|
||||||
|
<?php
|
||||||
|
$exportQuery = http_build_query([
|
||||||
|
'school_year' => $result['school_year'] ?? '',
|
||||||
|
'semester' => $result['semester'] ?? '',
|
||||||
|
'calculator_mode' => $result['calculator_mode'] ?? 'compare',
|
||||||
|
'include_withdrawn_mode' => $filters['include_withdrawn_mode'] ?? 'refund_deadline',
|
||||||
|
'include_payment_pending' => !empty($filters['include_payment_pending']) ? '1' : '0',
|
||||||
|
'include_event_only' => !empty($filters['include_event_only']) ? '1' : '0',
|
||||||
|
'include_paid_invoices' => !empty($filters['include_paid_invoices']) ? '1' : '0',
|
||||||
|
'unit_price' => $filters['unit_price'] ?? '',
|
||||||
|
'youth_unit_price' => $filters['youth_unit_price'] ?? '',
|
||||||
|
]);
|
||||||
|
?>
|
||||||
|
<a href="<?= site_url('administrator/tuition-forecast/export?' . $exportQuery) ?>" class="btn btn-success">
|
||||||
|
Export CSV
|
||||||
|
</a>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card shadow-sm mb-4">
|
||||||
|
<div class="card-body">
|
||||||
|
<form method="get" action="<?= site_url('administrator/tuition-forecast') ?>" class="row g-3 align-items-end">
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="school_year" class="form-label">School Year</label>
|
||||||
|
<select id="school_year" name="school_year" class="form-select">
|
||||||
|
<?php foreach (($schoolYears ?? []) as $schoolYear): ?>
|
||||||
|
<option value="<?= esc($schoolYear) ?>" <?= ($filters['school_year'] ?? '') === $schoolYear ? 'selected' : '' ?>>
|
||||||
|
<?= esc($schoolYear) ?>
|
||||||
|
</option>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<label for="semester" class="form-label">Semester Filter</label>
|
||||||
|
<select id="semester" name="semester" class="form-select">
|
||||||
|
<option value="" <?= ($filters['semester'] ?? '') === '' ? 'selected' : '' ?>>All Year</option>
|
||||||
|
<?php foreach (($semesters ?? []) as $semester): ?>
|
||||||
|
<option value="<?= esc($semester) ?>" <?= ($filters['semester'] ?? '') === $semester ? 'selected' : '' ?>>
|
||||||
|
<?= esc($semester) ?>
|
||||||
|
</option>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<label for="calculator_mode" class="form-label">Calculator Mode</label>
|
||||||
|
<select id="calculator_mode" name="calculator_mode" class="form-select">
|
||||||
|
<option value="compare" <?= $mode === 'compare' ? 'selected' : '' ?>>Compare Both</option>
|
||||||
|
<option value="old" <?= $mode === 'old' ? 'selected' : '' ?>>Old Only</option>
|
||||||
|
<option value="new" <?= $mode === 'new' ? 'selected' : '' ?>>New Only</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<label for="include_withdrawn_mode" class="form-label">Withdrawn Students</label>
|
||||||
|
<select id="include_withdrawn_mode" name="include_withdrawn_mode" class="form-select">
|
||||||
|
<option value="refund_deadline" <?= ($filters['include_withdrawn_mode'] ?? 'refund_deadline') === 'refund_deadline' ? 'selected' : '' ?>>Use Refund Deadline Rule</option>
|
||||||
|
<option value="include" <?= ($filters['include_withdrawn_mode'] ?? '') === 'include' ? 'selected' : '' ?>>Always Include</option>
|
||||||
|
<option value="exclude" <?= ($filters['include_withdrawn_mode'] ?? '') === 'exclude' ? 'selected' : '' ?>>Always Exclude</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="unit_price" class="form-label">Grades Unit Price</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
id="unit_price"
|
||||||
|
name="unit_price"
|
||||||
|
class="form-control"
|
||||||
|
value="<?= esc((string) ($filters['unit_price'] ?? ($summary['unit_price'] ?? ''))) ?>"
|
||||||
|
placeholder="New tuition unit price for grades">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label for="youth_unit_price" class="form-label">Youth Unit Price</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
step="0.01"
|
||||||
|
id="youth_unit_price"
|
||||||
|
name="youth_unit_price"
|
||||||
|
class="form-control"
|
||||||
|
value="<?= esc((string) ($filters['youth_unit_price'] ?? ($summary['youth_unit_price'] ?? ''))) ?>"
|
||||||
|
placeholder="New tuition unit price for youth">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<div class="form-check">
|
||||||
|
<input class="form-check-input" type="checkbox" id="include_payment_pending" name="include_payment_pending" value="1" <?= !empty($filters['include_payment_pending']) ? 'checked' : '' ?>>
|
||||||
|
<label class="form-check-label" for="include_payment_pending">Include payment-pending students</label>
|
||||||
|
</div>
|
||||||
|
<div class="form-check">
|
||||||
|
<input class="form-check-input" type="checkbox" id="include_event_only" name="include_event_only" value="1" <?= !empty($filters['include_event_only']) ? 'checked' : '' ?>>
|
||||||
|
<label class="form-check-label" for="include_event_only">Show event-only students in warnings</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-12">
|
||||||
|
<button type="submit" class="btn btn-primary">Run Forecast</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<?php if ($result): ?>
|
||||||
|
<div class="row g-3 mb-4">
|
||||||
|
<div class="col-xl col-lg-3 col-md-4">
|
||||||
|
<div class="card border-0 shadow-sm h-100">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="text-muted small">Total Parents</div>
|
||||||
|
<div class="fs-4 fw-semibold"><?= esc((string) ($summary['family_count'] ?? 0)) ?></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-xl col-lg-3 col-md-4">
|
||||||
|
<div class="card border-0 shadow-sm h-100">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="text-muted small">Total Students</div>
|
||||||
|
<div class="fs-4 fw-semibold"><?= esc((string) ($summary['student_count'] ?? 0)) ?></div>
|
||||||
|
<div class="small text-muted">Billable: <?= esc((string) ($summary['billable_student_count'] ?? 0)) ?></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-xl col-lg-3 col-md-4">
|
||||||
|
<div class="card border-0 shadow-sm h-100">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="text-muted small">Old Projected Income</div>
|
||||||
|
<div class="fs-5 fw-semibold"><?= esc($fmtMoney($summary['old_projected_income'] ?? ($summary['old_projected_tuition'] ?? 0))) ?></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-xl col-lg-3 col-md-4">
|
||||||
|
<div class="card border-0 shadow-sm h-100">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="text-muted small">New Projected Income</div>
|
||||||
|
<div class="fs-5 fw-semibold"><?= esc($fmtMoney($summary['new_projected_income'] ?? ($summary['new_projected_tuition'] ?? 0))) ?></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-xl col-lg-3 col-md-4">
|
||||||
|
<div class="card border-0 shadow-sm h-100">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="text-muted small">Grades Unit Price</div>
|
||||||
|
<div class="fs-5 fw-semibold"><?= esc($fmtMoney($summary['unit_price'] ?? 0)) ?></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-xl col-lg-3 col-md-4">
|
||||||
|
<div class="card border-0 shadow-sm h-100">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="text-muted small">Youth Unit Price</div>
|
||||||
|
<div class="fs-5 fw-semibold"><?= esc($fmtMoney($summary['youth_unit_price'] ?? 0)) ?></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-xl col-lg-3 col-md-4">
|
||||||
|
<div class="card border-0 shadow-sm h-100">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="text-muted small">Difference</div>
|
||||||
|
<div class="fs-5 fw-semibold <?= ((float) ($summary['difference'] ?? 0)) >= 0 ? 'text-success' : 'text-danger' ?>">
|
||||||
|
<?= esc($fmtMoney($summary['difference'] ?? 0)) ?>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card shadow-sm">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="table-responsive">
|
||||||
|
<table class="table table-bordered align-middle">
|
||||||
|
<thead class="table-light">
|
||||||
|
<tr>
|
||||||
|
<th>Parent / Family</th>
|
||||||
|
<th>Student Count</th>
|
||||||
|
<th>Billable Student Count</th>
|
||||||
|
<th>Old Tuition Total</th>
|
||||||
|
<th>New Tuition Total</th>
|
||||||
|
<th>Difference</th>
|
||||||
|
<th>Warnings</th>
|
||||||
|
<th>Details</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<?php if (!empty($result['families'])): ?>
|
||||||
|
<?php foreach ($result['families'] as $family): ?>
|
||||||
|
<tr>
|
||||||
|
<td><?= esc($family['parent_name'] ?? '') ?></td>
|
||||||
|
<td><?= esc((string) ($family['student_count'] ?? 0)) ?></td>
|
||||||
|
<td><?= esc((string) ($family['billable_student_count'] ?? 0)) ?></td>
|
||||||
|
<td><?= esc($fmtMoney($family['old_total'] ?? 0)) ?></td>
|
||||||
|
<td><?= esc($fmtMoney($family['new_total'] ?? 0)) ?></td>
|
||||||
|
<td class="<?= ((float) ($family['difference'] ?? 0)) >= 0 ? 'text-success' : 'text-danger' ?>">
|
||||||
|
<?= esc($fmtMoney($family['difference'] ?? 0)) ?>
|
||||||
|
</td>
|
||||||
|
<td class="small"><?= esc($warningText($family['warnings'] ?? [])) ?></td>
|
||||||
|
<td>
|
||||||
|
<details>
|
||||||
|
<summary>Students</summary>
|
||||||
|
<div class="table-responsive mt-2">
|
||||||
|
<table class="table table-sm table-striped mb-0">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Student</th>
|
||||||
|
<th>Grade</th>
|
||||||
|
<th>Billable</th>
|
||||||
|
<th>Excluded Reason</th>
|
||||||
|
<th>Old Rule</th>
|
||||||
|
<th>Old Amount</th>
|
||||||
|
<th>New Rule</th>
|
||||||
|
<th>New Amount</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<?php foreach (($family['student_details'] ?? []) as $detail): ?>
|
||||||
|
<tr>
|
||||||
|
<td><?= esc($detail['student_name'] ?? '') ?></td>
|
||||||
|
<td><?= esc($detail['grade_level'] ?? '') ?></td>
|
||||||
|
<td><?= !empty($detail['billable']) ? 'Yes' : 'No' ?></td>
|
||||||
|
<td><?= esc((string) ($detail['excluded_reason'] ?? '')) ?></td>
|
||||||
|
<td><?= esc((string) ($detail['old_rule'] ?? '')) ?></td>
|
||||||
|
<td><?= esc($fmtMoney($detail['old_amount'] ?? 0)) ?></td>
|
||||||
|
<td><?= esc((string) ($detail['new_rule'] ?? '')) ?></td>
|
||||||
|
<td><?= esc($fmtMoney($detail['new_amount'] ?? 0)) ?></td>
|
||||||
|
</tr>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
<?php else: ?>
|
||||||
|
<tr>
|
||||||
|
<td colspan="8" class="text-center text-muted">No forecastable families matched the selected filters.</td>
|
||||||
|
</tr>
|
||||||
|
<?php endif; ?>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<?= $this->endSection() ?>
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
<h2 class="text-center mt-4 mb-4">Student Decisions — All Students</h2>
|
<h2 class="text-center mt-4 mb-4">Student Decisions — All Students</h2>
|
||||||
|
|
||||||
<!-- School Year filter only -->
|
<!-- School Year filter only -->
|
||||||
<form method="get" class="row g-2 align-items-center justify-content-center mb-3">
|
<form method="get" class="row g-2 align-items-center justify-content-center mb-3 no-print">
|
||||||
<div class="col-auto"><label class="form-label mb-0">School year</label></div>
|
<div class="col-auto"><label class="form-label mb-0">School year</label></div>
|
||||||
<div class="col-auto">
|
<div class="col-auto">
|
||||||
<select name="school_year" class="form-select form-select-sm" style="min-width: 180px;">
|
<select name="school_year" class="form-select form-select-sm" style="min-width: 180px;">
|
||||||
@@ -35,7 +35,10 @@
|
|||||||
<span class="badge bg-warning text-dark ms-2">Not yet generated</span>
|
<span class="badge bg-warning text-dark ms-2">Not yet generated</span>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</div>
|
</div>
|
||||||
<div class="d-flex gap-2 flex-wrap">
|
<div class="d-flex gap-2 flex-wrap no-print">
|
||||||
|
<button type="button" class="btn btn-outline-secondary btn-sm" onclick="window.print()">
|
||||||
|
Print Stats
|
||||||
|
</button>
|
||||||
<a class="btn btn-outline-secondary btn-sm" href="<?= base_url('grading') ?>">
|
<a class="btn btn-outline-secondary btn-sm" href="<?= base_url('grading') ?>">
|
||||||
Grading
|
Grading
|
||||||
</a>
|
</a>
|
||||||
@@ -56,7 +59,7 @@
|
|||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
|
||||||
<!-- Generate / Regenerate button -->
|
<!-- Generate / Regenerate button -->
|
||||||
<form method="post" action="<?= site_url('grading/decisions/generate') ?>" class="mb-3">
|
<form method="post" action="<?= site_url('grading/decisions/generate') ?>" class="mb-3 no-print">
|
||||||
<?= csrf_field() ?>
|
<?= csrf_field() ?>
|
||||||
<input type="hidden" name="school_year" value="<?= esc($schoolYear ?? '') ?>">
|
<input type="hidden" name="school_year" value="<?= esc($schoolYear ?? '') ?>">
|
||||||
<button type="submit" class="btn btn-primary">
|
<button type="submit" class="btn btn-primary">
|
||||||
@@ -93,10 +96,42 @@
|
|||||||
elseif ($r['decision'] === '' || $r['source'] === 'pending') $stats['Pending']++;
|
elseif ($r['decision'] === '' || $r['source'] === 'pending') $stats['Pending']++;
|
||||||
else $stats['Other']++;
|
else $stats['Other']++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$pct = static function (int $count, int $total): string {
|
||||||
|
return $total > 0 ? number_format(($count / $total) * 100, 1) . '%' : '0.0%';
|
||||||
|
};
|
||||||
|
|
||||||
|
$genderKey = static function (?string $gender): string {
|
||||||
|
$value = strtolower(trim((string)$gender));
|
||||||
|
|
||||||
|
return match (true) {
|
||||||
|
in_array($value, ['male', 'm', 'boy', 'boys'], true) => 'boys',
|
||||||
|
in_array($value, ['female', 'f', 'girl', 'girls'], true) => 'girls',
|
||||||
|
default => 'other',
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
$genderStats = static function (array $items) use ($genderKey): array {
|
||||||
|
$stats = ['boys' => 0, 'girls' => 0, 'other' => 0];
|
||||||
|
|
||||||
|
foreach ($items as $item) {
|
||||||
|
$stats[$genderKey($item['gender'] ?? '')]++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $stats;
|
||||||
|
};
|
||||||
|
|
||||||
|
$totalStudents = count($rows);
|
||||||
|
$passRows = array_values(array_filter($rows, static fn (array $row): bool => (string)($row['decision'] ?? '') === 'Pass'));
|
||||||
|
$trophyRows = array_values(array_filter($rows, static fn (array $row): bool => !empty($row['is_trophy'])));
|
||||||
|
|
||||||
|
$allGenderStats = $genderStats($rows);
|
||||||
|
$passGenderStats = $genderStats($passRows);
|
||||||
|
$trophyGenderStats = $genderStats($trophyRows);
|
||||||
?>
|
?>
|
||||||
|
|
||||||
<!-- Summary cards -->
|
<!-- Summary cards -->
|
||||||
<div class="d-flex gap-3 mb-3 flex-wrap">
|
<div class="d-flex gap-3 mb-3 flex-wrap no-print">
|
||||||
<div class="card text-center px-4 py-2 border-success">
|
<div class="card text-center px-4 py-2 border-success">
|
||||||
<div class="fs-4 fw-bold text-success"><?= $stats['Pass'] ?></div>
|
<div class="fs-4 fw-bold text-success"><?= $stats['Pass'] ?></div>
|
||||||
<div class="text-muted small">Pass</div>
|
<div class="text-muted small">Pass</div>
|
||||||
@@ -115,7 +150,60 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="table-responsive">
|
<div class="print-only" style="margin-bottom:14px;">
|
||||||
|
<div style="text-align:center;margin-bottom:10px;border-bottom:2px solid #333;padding-bottom:6px;">
|
||||||
|
<h2 style="margin:0;">Student Decisions Summary — <?= esc($schoolYear ?? '') ?></h2>
|
||||||
|
<p style="margin:3px 0 0;font-size:10px;color:#555;">
|
||||||
|
Trophy counts use the same year-score rule as the trophy final page.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h3 style="margin-bottom:6px;">Print Stats</h3>
|
||||||
|
<table data-no-mgmt-sticky style="margin-bottom:12px;">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Metric</th>
|
||||||
|
<th style="text-align:center;">Count</th>
|
||||||
|
<th style="text-align:center;">Percent</th>
|
||||||
|
<th style="text-align:center;">Boys</th>
|
||||||
|
<th style="text-align:center;">Boys %</th>
|
||||||
|
<th style="text-align:center;">Girls</th>
|
||||||
|
<th style="text-align:center;">Girls %</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td>Total Students</td>
|
||||||
|
<td style="text-align:center;"><?= $totalStudents ?></td>
|
||||||
|
<td style="text-align:center;">100.0%</td>
|
||||||
|
<td style="text-align:center;"><?= $allGenderStats['boys'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($allGenderStats['boys'], $totalStudents) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $allGenderStats['girls'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($allGenderStats['girls'], $totalStudents) ?></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Pass</td>
|
||||||
|
<td style="text-align:center;"><?= count($passRows) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct(count($passRows), $totalStudents) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $passGenderStats['boys'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($passGenderStats['boys'], count($passRows)) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $passGenderStats['girls'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($passGenderStats['girls'], count($passRows)) ?></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>Trophies</td>
|
||||||
|
<td style="text-align:center;"><?= count($trophyRows) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct(count($trophyRows), $totalStudents) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $trophyGenderStats['boys'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($trophyGenderStats['boys'], count($trophyRows)) ?></td>
|
||||||
|
<td style="text-align:center;"><?= $trophyGenderStats['girls'] ?></td>
|
||||||
|
<td style="text-align:center;"><?= $pct($trophyGenderStats['girls'], count($trophyRows)) ?></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-responsive no-print">
|
||||||
<table class="table table-bordered table-striped align-middle w-100 all-decisions-dt"
|
<table class="table table-bordered table-striped align-middle w-100 all-decisions-dt"
|
||||||
data-no-mgmt-sticky data-no-dt-fixedheader>
|
data-no-mgmt-sticky data-no-dt-fixedheader>
|
||||||
<thead class="table-light">
|
<thead class="table-light">
|
||||||
@@ -174,7 +262,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Legend -->
|
<!-- Legend -->
|
||||||
<div class="mt-2 mb-4 d-flex gap-2 flex-wrap align-items-center">
|
<div class="mt-2 mb-4 d-flex gap-2 flex-wrap align-items-center no-print">
|
||||||
<?php foreach ($decisionBadge as $label => $color): ?>
|
<?php foreach ($decisionBadge as $label => $color): ?>
|
||||||
<span class="badge bg-<?= esc($color) ?> px-2 py-1"><?= esc($label) ?></span>
|
<span class="badge bg-<?= esc($color) ?> px-2 py-1"><?= esc($label) ?></span>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
@@ -189,8 +277,29 @@
|
|||||||
|
|
||||||
<?= $this->section('scripts') ?>
|
<?= $this->section('scripts') ?>
|
||||||
<style>
|
<style>
|
||||||
|
.print-only { display: none !important; }
|
||||||
.grade-orange td { background: #fff3cd !important; color: #8a5d00; }
|
.grade-orange td { background: #fff3cd !important; color: #8a5d00; }
|
||||||
.grade-red td { background: #f8d7da !important; color: #842029; }
|
.grade-red td { background: #f8d7da !important; color: #842029; }
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
.no-print { display: none !important; }
|
||||||
|
.print-only { display: block !important; }
|
||||||
|
body { font-size: 11px; }
|
||||||
|
.container-fluid { padding: 0 !important; }
|
||||||
|
table { width: 100%; border-collapse: collapse; font-size: 10px; }
|
||||||
|
table th, table td { border: 1px solid #bbb; padding: 3px 5px; }
|
||||||
|
table thead {
|
||||||
|
background: #333 !important;
|
||||||
|
color: #fff !important;
|
||||||
|
-webkit-print-color-adjust: exact;
|
||||||
|
print-color-adjust: exact;
|
||||||
|
}
|
||||||
|
table thead th {
|
||||||
|
position: static !important;
|
||||||
|
top: auto !important;
|
||||||
|
box-shadow: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
|
|||||||
@@ -1,23 +1,71 @@
|
|||||||
<?= $this->extend('layout/management_layout') ?>
|
<?= $this->extend('layout/management_layout') ?>
|
||||||
<?= $this->section('content') ?>
|
<?= $this->section('content') ?>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
// This page is Fall semester only.
|
||||||
|
// Do not expose Whole Year mode here.
|
||||||
|
$semester = 'fall';
|
||||||
|
$actionSemester = 'fall';
|
||||||
|
|
||||||
|
$schoolYear = $schoolYear ?? '';
|
||||||
|
$schoolYears = $schoolYears ?? [];
|
||||||
|
|
||||||
|
if (empty($schoolYears) && $schoolYear !== '') {
|
||||||
|
$schoolYears = [$schoolYear];
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
|
||||||
<div class="container-fluid">
|
<div class="container-fluid">
|
||||||
<div class="wrapper below-sixty-wrapper">
|
<div class="wrapper below-sixty-wrapper">
|
||||||
<h2 class="text-center mt-4 mb-4 below-sixty-title">Below 60 Summary</h2>
|
<h2 class="text-center mt-4 mb-4 below-sixty-title">Below 60 Summary</h2>
|
||||||
|
|
||||||
<?= $this->include('partials/academic_filter') ?>
|
<!-- School year filter only -->
|
||||||
|
<div class="card shadow-sm mb-3">
|
||||||
|
<div class="card-body py-3">
|
||||||
|
<form method="get"
|
||||||
|
action="<?= site_url('grading/below-60') ?>"
|
||||||
|
class="row g-2 align-items-end justify-content-center">
|
||||||
|
|
||||||
|
<input type="hidden" name="semester" value="fall">
|
||||||
|
|
||||||
|
<div class="col-12 col-sm-auto">
|
||||||
|
<label class="form-label mb-1 small fw-semibold">School Year</label>
|
||||||
|
|
||||||
|
<?php if (!empty($schoolYears)): ?>
|
||||||
|
<select name="school_year"
|
||||||
|
class="form-select form-select-sm"
|
||||||
|
style="min-width:160px;">
|
||||||
|
<?php foreach ($schoolYears as $yr): ?>
|
||||||
|
<option value="<?= esc($yr) ?>" <?= (string)$yr === (string)$schoolYear ? 'selected' : '' ?>>
|
||||||
|
<?= esc($yr) ?>
|
||||||
|
</option>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</select>
|
||||||
|
<?php else: ?>
|
||||||
|
<input type="text"
|
||||||
|
name="school_year"
|
||||||
|
class="form-control form-control-sm"
|
||||||
|
style="min-width:160px;"
|
||||||
|
value="<?= esc($schoolYear) ?>"
|
||||||
|
placeholder="2025-2026">
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="col-12 col-sm-auto">
|
||||||
|
<button type="submit" class="btn btn-sm btn-primary">
|
||||||
|
<i class="bi bi-funnel me-1"></i>Apply
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
|
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
|
||||||
<div class="text-muted">
|
<div class="text-muted">
|
||||||
<?= !empty($isYearMode) ? 'Whole Year' : esc(ucfirst($semester ?? '')) ?> • <?= esc($schoolYear ?? '') ?>
|
Fall • <?= esc($schoolYear) ?>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="d-flex gap-2">
|
<div class="d-flex gap-2">
|
||||||
<?php if (empty($isYearMode)): ?>
|
|
||||||
<a class="btn btn-outline-primary btn-sm"
|
|
||||||
href="<?= site_url('grading/below-60/decisions?' . http_build_query(['semester' => $semester ?? '', 'school_year' => $schoolYear ?? ''])) ?>">
|
|
||||||
Decisions
|
|
||||||
</a>
|
|
||||||
<?php endif; ?>
|
|
||||||
<?php if (!empty($canViewGrading)): ?>
|
<?php if (!empty($canViewGrading)): ?>
|
||||||
<a class="btn btn-outline-secondary btn-sm" href="<?= base_url('grading') ?>">
|
<a class="btn btn-outline-secondary btn-sm" href="<?= base_url('grading') ?>">
|
||||||
Back to Grading
|
Back to Grading
|
||||||
@@ -31,46 +79,44 @@
|
|||||||
if ($value === null || $value === '') {
|
if ($value === null || $value === '') {
|
||||||
return '—';
|
return '—';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (is_numeric($value)) {
|
if (is_numeric($value)) {
|
||||||
return esc(number_format((float)$value, 2, '.', ''));
|
return esc(number_format((float)$value, 2, '.', ''));
|
||||||
}
|
}
|
||||||
|
|
||||||
return esc($value);
|
return esc($value);
|
||||||
};
|
};
|
||||||
?>
|
?>
|
||||||
|
|
||||||
<?php if (empty($rows)): ?>
|
<?php if (empty($rows)): ?>
|
||||||
<div class="alert alert-success text-center d-inline-block">
|
<div class="alert alert-success text-center d-inline-block">
|
||||||
No students below 60 for this selection.
|
No students below 60 for Fall in <?= esc($schoolYear) ?>.
|
||||||
</div>
|
</div>
|
||||||
<?php else: ?>
|
<?php else: ?>
|
||||||
<div class="table-responsive below-sixty-table">
|
<div class="table-responsive below-sixty-table">
|
||||||
<table class="table table-bordered table-striped align-middle w-100 no-mgmt-sticky below-sixty-dt" data-no-mgmt-sticky data-no-dt-fixedheader>
|
<table class="table table-bordered table-striped align-middle w-100 no-mgmt-sticky below-sixty-dt"
|
||||||
|
data-no-mgmt-sticky
|
||||||
|
data-no-dt-fixedheader>
|
||||||
<thead class="table-light">
|
<thead class="table-light">
|
||||||
<tr>
|
<tr>
|
||||||
<th>Student Name</th>
|
<th>Student Name</th>
|
||||||
<th>Section</th>
|
<th>Section</th>
|
||||||
<?php if (!empty($isYearMode)): ?><th>Semester</th><?php endif; ?>
|
<th class="text-center">Fall Score</th>
|
||||||
<th>Hwk Avg</th>
|
|
||||||
<th>Project Avg</th>
|
|
||||||
<th>Participation</th>
|
|
||||||
<th>Test Avg</th>
|
|
||||||
<th>PTAP Score</th>
|
|
||||||
<th>Attendance</th>
|
|
||||||
<th>Midterm Score</th>
|
|
||||||
<th><?= !empty($isYearMode) ? 'Semester Score' : (strcasecmp($semester ?? '', 'fall') === 0 ? '1st Semester Score' : 'Semester Score') ?></th>
|
|
||||||
<?php if (empty($isYearMode)): ?>
|
|
||||||
<th>Status</th>
|
<th>Status</th>
|
||||||
<th>Email Parent</th>
|
<th>Email Parent</th>
|
||||||
<th>Schedule Meeting</th>
|
<th>Schedule Meeting</th>
|
||||||
<?php endif; ?>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
|
|
||||||
<tbody>
|
<tbody>
|
||||||
<?php foreach ($rows as $row): ?>
|
<?php foreach ($rows as $row): ?>
|
||||||
<?php
|
<?php
|
||||||
|
// Fall-only page: use semester_score.
|
||||||
$scoreRaw = $row['semester_score'] ?? null;
|
$scoreRaw = $row['semester_score'] ?? null;
|
||||||
$scoreVal = is_numeric($scoreRaw) ? (float)$scoreRaw : null;
|
$scoreVal = is_numeric($scoreRaw) ? (float)$scoreRaw : null;
|
||||||
|
|
||||||
$scoreClass = '';
|
$scoreClass = '';
|
||||||
|
|
||||||
if ($scoreVal !== null) {
|
if ($scoreVal !== null) {
|
||||||
if ($scoreVal < 50) {
|
if ($scoreVal < 50) {
|
||||||
$scoreClass = 'grade-red';
|
$scoreClass = 'grade-red';
|
||||||
@@ -78,60 +124,104 @@
|
|||||||
$scoreClass = 'grade-orange';
|
$scoreClass = 'grade-orange';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$studentName = trim((string)($row['firstname'] ?? '') . ' ' . (string)($row['lastname'] ?? ''));
|
|
||||||
|
$studentName = trim((string)($row['firstname'] ?? '') . ' ' . (string)($row['lastname'] ?? ''));
|
||||||
|
$studentLabel = $studentName !== '' ? $studentName : 'N/A';
|
||||||
|
$isClosed = ($row['status'] ?? 'Open') === 'Closed';
|
||||||
?>
|
?>
|
||||||
<?php $isClosed = ($row['status'] ?? 'Open') === 'Closed'; ?>
|
|
||||||
<?php $rowSemester = ucfirst(strtolower(trim((string)($row['semester'] ?? ($semester ?? ''))))); ?>
|
|
||||||
<tr class="<?= esc($scoreClass) ?>">
|
<tr class="<?= esc($scoreClass) ?>">
|
||||||
<td><?= esc($studentName !== '' ? $studentName : 'N/A') ?></td>
|
<td><?= esc($studentLabel) ?></td>
|
||||||
<td><?= esc($row['class_section_name'] ?? '—') ?></td>
|
<td><?= esc($row['class_section_name'] ?? '—') ?></td>
|
||||||
<?php if (!empty($isYearMode)): ?>
|
|
||||||
<td class="text-center"><?= esc($rowSemester) ?></td>
|
|
||||||
<?php endif; ?>
|
|
||||||
<td class="text-center"><?= $displayScore($row['homework_avg'] ?? null) ?></td>
|
|
||||||
<td class="text-center"><?= $displayScore($row['project_avg'] ?? null) ?></td>
|
|
||||||
<td class="text-center"><?= $displayScore($row['participation_score'] ?? null) ?></td>
|
|
||||||
<td class="text-center"><?= $displayScore($row['test_avg'] ?? null) ?></td>
|
|
||||||
<td class="text-center"><?= $displayScore($row['ptap_score'] ?? null) ?></td>
|
|
||||||
<td class="text-center"><?= $displayScore($row['attendance_score'] ?? null) ?></td>
|
|
||||||
<td class="text-center"><?= $displayScore($row['midterm_exam_score'] ?? null) ?></td>
|
|
||||||
<td class="text-center"><?= $displayScore($row['semester_score'] ?? null) ?></td>
|
|
||||||
<?php if (empty($isYearMode)): ?>
|
|
||||||
<td class="text-center">
|
<td class="text-center">
|
||||||
<form method="post" action="<?= site_url('grading/below-60/status') ?>" class="d-flex align-items-center gap-2 justify-content-center">
|
<div class="fw-semibold"><?= $displayScore($scoreRaw) ?></div>
|
||||||
|
|
||||||
|
<button type="button"
|
||||||
|
class="btn btn-outline-secondary btn-xs mt-1 btn-show-details"
|
||||||
|
style="font-size:0.72rem;padding:1px 7px;"
|
||||||
|
data-student-id="<?= (int)($row['student_id'] ?? 0) ?>"
|
||||||
|
data-student-name="<?= esc($studentLabel) ?>"
|
||||||
|
data-school-year="<?= esc((string)$schoolYear) ?>">
|
||||||
|
Details
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
|
||||||
|
<td class="text-center">
|
||||||
|
<form method="post"
|
||||||
|
action="<?= site_url('grading/below-60/status') ?>"
|
||||||
|
class="d-flex align-items-center gap-2 justify-content-center">
|
||||||
<?= csrf_field() ?>
|
<?= csrf_field() ?>
|
||||||
<input type="hidden" name="student_id" value="<?= esc((string)($row['student_id'] ?? '')) ?>">
|
|
||||||
<input type="hidden" name="semester" value="<?= esc((string)($semester ?? '')) ?>">
|
<input type="hidden"
|
||||||
<input type="hidden" name="school_year" value="<?= esc((string)($schoolYear ?? '')) ?>">
|
name="student_id"
|
||||||
<select name="status" class="form-select form-select-sm" style="width: 110px;">
|
value="<?= esc((string)($row['student_id'] ?? '')) ?>">
|
||||||
<option value="Open" <?= ($row['status'] ?? 'Open') === 'Open' ? 'selected' : '' ?>>Open</option>
|
|
||||||
<option value="Closed" <?= ($row['status'] ?? '') === 'Closed' ? 'selected' : '' ?>>Closed</option>
|
<input type="hidden"
|
||||||
|
name="semester"
|
||||||
|
value="fall">
|
||||||
|
|
||||||
|
<input type="hidden"
|
||||||
|
name="school_year"
|
||||||
|
value="<?= esc((string)$schoolYear) ?>">
|
||||||
|
|
||||||
|
<select name="status"
|
||||||
|
class="form-select form-select-sm"
|
||||||
|
style="width:110px;">
|
||||||
|
<option value="Open" <?= ($row['status'] ?? 'Open') === 'Open' ? 'selected' : '' ?>>
|
||||||
|
Open
|
||||||
|
</option>
|
||||||
|
<option value="Closed" <?= ($row['status'] ?? '') === 'Closed' ? 'selected' : '' ?>>
|
||||||
|
Closed
|
||||||
|
</option>
|
||||||
</select>
|
</select>
|
||||||
<input type="text" name="note" class="form-control form-control-sm" style="width: 140px;" placeholder="Note (optional)" value="<?= esc((string)($row['note'] ?? '')) ?>">
|
|
||||||
<button type="submit" class="btn btn-sm btn-outline-secondary">Update</button>
|
<input type="text"
|
||||||
|
name="note"
|
||||||
|
class="form-control form-control-sm"
|
||||||
|
style="width:140px;"
|
||||||
|
placeholder="Note (optional)"
|
||||||
|
value="<?= esc((string)($row['note'] ?? '')) ?>">
|
||||||
|
|
||||||
|
<button type="submit" class="btn btn-sm btn-outline-secondary">
|
||||||
|
Update
|
||||||
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
<td class="text-center">
|
<td class="text-center">
|
||||||
<?php if ($isClosed): ?>
|
<?php if ($isClosed): ?>
|
||||||
<button type="button" class="btn btn-sm btn-secondary" disabled>Send Email</button>
|
<button type="button" class="btn btn-sm btn-secondary" disabled>
|
||||||
|
Send Email
|
||||||
|
</button>
|
||||||
<?php else: ?>
|
<?php else: ?>
|
||||||
<a class="btn btn-sm btn-outline-primary"
|
<a class="btn btn-sm btn-outline-primary"
|
||||||
href="<?= site_url('grading/below-60/email/edit?student_id=' . (int)($row['student_id'] ?? 0) . '&semester=' . rawurlencode((string)($semester ?? '')) . '&school_year=' . rawurlencode((string)($schoolYear ?? ''))) ?>">
|
href="<?= site_url('grading/below-60/email/edit?' . http_build_query([
|
||||||
|
'student_id' => (int)($row['student_id'] ?? 0),
|
||||||
|
'semester' => 'fall',
|
||||||
|
'school_year' => (string)$schoolYear,
|
||||||
|
])) ?>">
|
||||||
Send Email
|
Send Email
|
||||||
</a>
|
</a>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
<td class="text-center">
|
<td class="text-center">
|
||||||
<?php if ($isClosed): ?>
|
<?php if ($isClosed): ?>
|
||||||
<button class="btn btn-sm btn-secondary" disabled>Schedule</button>
|
<button class="btn btn-sm btn-secondary" disabled>
|
||||||
|
Schedule
|
||||||
|
</button>
|
||||||
<?php else: ?>
|
<?php else: ?>
|
||||||
<a class="btn btn-sm btn-outline-secondary"
|
<a class="btn btn-sm btn-outline-secondary"
|
||||||
href="<?= site_url('grading/below-60/schedule?student_id=' . (int)($row['student_id'] ?? 0) . '&semester=' . rawurlencode((string)($semester ?? '')) . '&school_year=' . rawurlencode((string)($schoolYear ?? ''))) ?>">
|
href="<?= site_url('grading/below-60/schedule?' . http_build_query([
|
||||||
|
'student_id' => (int)($row['student_id'] ?? 0),
|
||||||
|
'semester' => 'fall',
|
||||||
|
'school_year' => (string)$schoolYear,
|
||||||
|
])) ?>">
|
||||||
Schedule
|
Schedule
|
||||||
</a>
|
</a>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</td>
|
</td>
|
||||||
<?php endif; ?>
|
|
||||||
</tr>
|
</tr>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -141,31 +231,251 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Score details modal -->
|
||||||
|
<div class="modal fade" id="detailsModal" tabindex="-1" aria-labelledby="detailsModalLabel" aria-hidden="true">
|
||||||
|
<div class="modal-dialog modal-lg modal-dialog-scrollable">
|
||||||
|
<div class="modal-content">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h5 class="modal-title" id="detailsModalLabel">Score Details</h5>
|
||||||
|
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-body" id="detailsModalBody">
|
||||||
|
<div class="text-center py-4">
|
||||||
|
<div class="spinner-border text-primary" role="status"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button type="button"
|
||||||
|
class="btn btn-outline-secondary"
|
||||||
|
data-bs-dismiss="modal">
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<?= $this->endSection() ?>
|
<?= $this->endSection() ?>
|
||||||
|
|
||||||
<?= $this->section('scripts') ?>
|
<?= $this->section('scripts') ?>
|
||||||
<style>
|
<style>
|
||||||
.grade-orange td { background: #fff3cd !important; color: #8a5d00; font-weight: 600; }
|
.grade-orange td {
|
||||||
.grade-red td { background: #f8d7da !important; color: #842029; font-weight: 600; }
|
background: #fff3cd !important;
|
||||||
.below-sixty-wrapper { padding-top: 0.75rem; }
|
color: #8a5d00;
|
||||||
.below-sixty-title { position: relative; z-index: 1; margin-bottom: 1.25rem; }
|
font-weight: 600;
|
||||||
.below-sixty-table { margin-top: 0.75rem; }
|
}
|
||||||
|
|
||||||
|
.grade-red td {
|
||||||
|
background: #f8d7da !important;
|
||||||
|
color: #842029;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.below-sixty-wrapper {
|
||||||
|
padding-top: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.below-sixty-title {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
margin-bottom: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.below-sixty-table {
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.below-sixty-dt td {
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
(function() {
|
(function () {
|
||||||
if (!window.$ || !$.fn || !$.fn.DataTable) return;
|
if (window.$ && $.fn && $.fn.DataTable) {
|
||||||
$(function() {
|
$(function () {
|
||||||
const table = $('.below-sixty-dt');
|
const table = $('.below-sixty-dt');
|
||||||
|
|
||||||
if (!table.length) return;
|
if (!table.length) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const semesterOffset = <?= !empty($isYearMode) ? '1' : '0' ?>;
|
|
||||||
table.DataTable({
|
table.DataTable({
|
||||||
order: [[8 + semesterOffset, 'asc']],
|
order: [[2, 'asc']],
|
||||||
pageLength: 100,
|
pageLength: 100,
|
||||||
lengthMenu: [10, 25, 50, 100, 200]
|
lengthMenu: [10, 25, 50, 100, 200],
|
||||||
|
columnDefs: [
|
||||||
|
{ orderable: false, targets: [3, 4, 5] }
|
||||||
|
]
|
||||||
});
|
});
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
});
|
});
|
||||||
})();
|
}
|
||||||
|
|
||||||
|
const detailsModal = document.getElementById('detailsModal');
|
||||||
|
const detailsModalBody = document.getElementById('detailsModalBody');
|
||||||
|
const detailsModalTitle = document.getElementById('detailsModalLabel');
|
||||||
|
|
||||||
|
const SCORE_LABELS = {
|
||||||
|
homework_avg: 'Homework Avg',
|
||||||
|
project_avg: 'Project Avg',
|
||||||
|
participation_score: 'Participation',
|
||||||
|
test_avg: 'Test Avg',
|
||||||
|
ptap_score: 'PTAP Score',
|
||||||
|
attendance_score: 'Attendance',
|
||||||
|
midterm_exam_score: 'Midterm Score',
|
||||||
|
final_exam_score: 'Final Exam',
|
||||||
|
semester_score: 'Semester Score'
|
||||||
|
};
|
||||||
|
|
||||||
|
const COMMENT_TYPE_LABELS = {
|
||||||
|
general: 'General',
|
||||||
|
attendance: 'Attendance',
|
||||||
|
attendance_comment: 'Attendance',
|
||||||
|
midterm: 'Midterm',
|
||||||
|
final: 'Final Exam',
|
||||||
|
ptap: 'PTAP'
|
||||||
|
};
|
||||||
|
|
||||||
|
function fmtScore(value) {
|
||||||
|
if (value === null || value === '' || value === undefined) return '—';
|
||||||
|
|
||||||
|
const parsed = parseFloat(value);
|
||||||
|
|
||||||
|
return isNaN(parsed) ? value : parsed.toFixed(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
function esc(str) {
|
||||||
|
return String(str)
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildDetailsHtml(semesters) {
|
||||||
|
if (!semesters || semesters.length === 0) {
|
||||||
|
return '<div class="alert alert-warning mb-0">No score data found.</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
let html = '';
|
||||||
|
|
||||||
|
semesters.forEach(function (sem) {
|
||||||
|
html += '<h6 class="fw-bold mt-3 mb-2">' + esc(sem.semester || '') + ' Semester';
|
||||||
|
|
||||||
|
if (sem.class_section_name) {
|
||||||
|
html += ' <span class="text-muted fw-normal fs-6">— ' + esc(sem.class_section_name) + '</span>';
|
||||||
|
}
|
||||||
|
|
||||||
|
html += '</h6>';
|
||||||
|
|
||||||
|
html += '<table class="table table-sm table-bordered mb-2">';
|
||||||
|
html += '<thead class="table-light"><tr><th>Item</th><th class="text-center">Score</th></tr></thead><tbody>';
|
||||||
|
|
||||||
|
let hasScoreRow = false;
|
||||||
|
|
||||||
|
Object.entries(SCORE_LABELS).forEach(function (entry) {
|
||||||
|
const key = entry[0];
|
||||||
|
const label = entry[1];
|
||||||
|
const value = sem[key];
|
||||||
|
|
||||||
|
if (value === null || value === '' || value === undefined) return;
|
||||||
|
|
||||||
|
const bold = key === 'semester_score' ? ' fw-bold' : '';
|
||||||
|
|
||||||
|
html += '<tr><td>' + esc(label) + '</td><td class="text-center' + bold + '">' + esc(fmtScore(value)) + '</td></tr>';
|
||||||
|
hasScoreRow = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!hasScoreRow) {
|
||||||
|
html += '<tr><td colspan="2" class="text-muted">No scores recorded.</td></tr>';
|
||||||
|
}
|
||||||
|
|
||||||
|
html += '</tbody></table>';
|
||||||
|
|
||||||
|
const comments = sem.comments || {};
|
||||||
|
|
||||||
|
const commentEntries = Object.entries(comments).filter(function (entry) {
|
||||||
|
return entry[1] && String(entry[1]).trim();
|
||||||
|
});
|
||||||
|
|
||||||
|
const seen = {};
|
||||||
|
const deduped = [];
|
||||||
|
|
||||||
|
commentEntries.forEach(function (entry) {
|
||||||
|
const type = entry[0];
|
||||||
|
const text = String(entry[1]);
|
||||||
|
const label = COMMENT_TYPE_LABELS[type] || type;
|
||||||
|
const key = label + '|' + text.trim();
|
||||||
|
|
||||||
|
if (!seen[key]) {
|
||||||
|
seen[key] = true;
|
||||||
|
deduped.push([label, text]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (deduped.length > 0) {
|
||||||
|
html += '<div class="mb-3">';
|
||||||
|
html += '<p class="fw-semibold mb-1" style="font-size:0.9rem;">Comments</p>';
|
||||||
|
|
||||||
|
deduped.forEach(function (entry) {
|
||||||
|
const label = entry[0];
|
||||||
|
const text = entry[1];
|
||||||
|
|
||||||
|
html += '<div class="mb-2 p-2 bg-light rounded border-start border-3 border-secondary">';
|
||||||
|
html += '<span class="badge bg-secondary me-1" style="font-size:0.7rem;">' + esc(label) + '</span>';
|
||||||
|
html += '<span class="text-dark" style="font-size:0.9rem;">' + esc(text).replace(/\n/g, '<br>') + '</span>';
|
||||||
|
html += '</div>';
|
||||||
|
});
|
||||||
|
|
||||||
|
html += '</div>';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (detailsModal) {
|
||||||
|
document.addEventListener('click', function (e) {
|
||||||
|
const btn = e.target.closest('.btn-show-details');
|
||||||
|
|
||||||
|
if (!btn) return;
|
||||||
|
|
||||||
|
const studentId = btn.dataset.studentId;
|
||||||
|
const studentName = btn.dataset.studentName;
|
||||||
|
const schoolYear = btn.dataset.schoolYear;
|
||||||
|
|
||||||
|
detailsModalTitle.textContent = studentName + ' — Score Details';
|
||||||
|
detailsModalBody.innerHTML = '<div class="text-center py-4"><div class="spinner-border text-primary" role="status"></div></div>';
|
||||||
|
|
||||||
|
bootstrap.Modal.getOrCreateInstance(detailsModal).show();
|
||||||
|
|
||||||
|
const url = '<?= site_url('grading/below-60/decisions/student-details') ?>'
|
||||||
|
+ '?student_id=' + encodeURIComponent(studentId)
|
||||||
|
+ '&school_year=' + encodeURIComponent(schoolYear);
|
||||||
|
|
||||||
|
fetch(url, {
|
||||||
|
headers: {
|
||||||
|
'X-Requested-With': 'XMLHttpRequest'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(function (response) {
|
||||||
|
return response.json();
|
||||||
|
})
|
||||||
|
.then(function (data) {
|
||||||
|
if (data.error) {
|
||||||
|
detailsModalBody.innerHTML = '<div class="alert alert-danger">' + esc(data.error) + '</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
detailsModalBody.innerHTML = buildDetailsHtml(data.semesters);
|
||||||
|
})
|
||||||
|
.catch(function () {
|
||||||
|
detailsModalBody.innerHTML = '<div class="alert alert-danger">Failed to load details.</div>';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})();
|
||||||
</script>
|
</script>
|
||||||
<?= $this->endSection() ?>
|
<?= $this->endSection() ?>
|
||||||
@@ -1,25 +1,85 @@
|
|||||||
<?= $this->extend('layout/management_layout') ?>
|
<?= $this->extend('layout/management_layout') ?>
|
||||||
<?= $this->section('content') ?>
|
<?= $this->section('content') ?>
|
||||||
|
|
||||||
|
<?php
|
||||||
|
// This page is Whole Year only.
|
||||||
|
// Do not expose semester filter here.
|
||||||
|
$semester = 'year';
|
||||||
|
|
||||||
|
$schoolYear = $schoolYear ?? '';
|
||||||
|
$schoolYears = $schoolYears ?? [];
|
||||||
|
|
||||||
|
if (empty($schoolYears) && $schoolYear !== '') {
|
||||||
|
$schoolYears = [$schoolYear];
|
||||||
|
}
|
||||||
|
?>
|
||||||
|
|
||||||
<div class="container-fluid">
|
<div class="container-fluid">
|
||||||
<div class="wrapper below-sixty-decisions-wrapper">
|
<div class="wrapper below-sixty-decisions-wrapper">
|
||||||
<h2 class="text-center mt-4 mb-4">Below 60 — Decisions</h2>
|
<h2 class="text-center mt-4 mb-4">School Year Decisions</h2>
|
||||||
|
|
||||||
<?= $this->include('partials/academic_filter') ?>
|
<!-- School year filter -->
|
||||||
|
<div class="card shadow-sm mb-3">
|
||||||
|
<div class="card-body py-3">
|
||||||
|
<form method="get"
|
||||||
|
action="<?= site_url('grading/below-60/decisions') ?>"
|
||||||
|
class="row g-2 align-items-end justify-content-center">
|
||||||
|
|
||||||
|
<input type="hidden" name="semester" value="year">
|
||||||
|
|
||||||
|
<div class="col-12 col-sm-auto">
|
||||||
|
<label class="form-label mb-1 small fw-semibold">School Year</label>
|
||||||
|
|
||||||
|
<?php if (!empty($schoolYears)): ?>
|
||||||
|
<select name="school_year"
|
||||||
|
class="form-select form-select-sm"
|
||||||
|
style="min-width: 160px;">
|
||||||
|
<?php foreach ($schoolYears as $yr): ?>
|
||||||
|
<option value="<?= esc($yr) ?>" <?= (string)$yr === (string)$schoolYear ? 'selected' : '' ?>>
|
||||||
|
<?= esc($yr) ?>
|
||||||
|
</option>
|
||||||
|
<?php endforeach; ?>
|
||||||
|
</select>
|
||||||
|
<?php else: ?>
|
||||||
|
<input type="text"
|
||||||
|
name="school_year"
|
||||||
|
class="form-control form-control-sm"
|
||||||
|
style="min-width: 160px;"
|
||||||
|
value="<?= esc($schoolYear) ?>"
|
||||||
|
placeholder="2025-2026">
|
||||||
|
<?php endif; ?>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="col-12 col-sm-auto">
|
||||||
|
<button type="submit" class="btn btn-sm btn-primary">
|
||||||
|
<i class="bi bi-funnel me-1"></i>Apply
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
|
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
|
||||||
<div class="text-muted">
|
<div class="text-muted">
|
||||||
<?= esc(ucfirst($semester ?? '')) ?> • <?= esc($schoolYear ?? '') ?>
|
Whole Year • <?= esc($schoolYear) ?>
|
||||||
</div>
|
</div>
|
||||||
<div class="d-flex gap-2">
|
|
||||||
|
<div class="d-flex gap-2 flex-wrap">
|
||||||
<a class="btn btn-outline-secondary btn-sm"
|
<a class="btn btn-outline-secondary btn-sm"
|
||||||
href="<?= site_url('grading/below-60?' . http_build_query(['semester' => $semester, 'school_year' => $schoolYear])) ?>">
|
href="<?= site_url('grading/below-60?' . http_build_query([
|
||||||
|
'semester' => 'year',
|
||||||
|
'school_year' => $schoolYear,
|
||||||
|
])) ?>">
|
||||||
← Back to Below 60
|
← Back to Below 60
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
<a class="btn btn-outline-primary btn-sm"
|
<a class="btn btn-outline-primary btn-sm"
|
||||||
href="<?= site_url('grading/decisions?' . http_build_query(['semester' => $semester, 'school_year' => $schoolYear])) ?>">
|
href="<?= site_url('grading/decisions?' . http_build_query([
|
||||||
|
'school_year' => $schoolYear,
|
||||||
|
])) ?>">
|
||||||
All Decisions
|
All Decisions
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
<?php if (!empty($canViewGrading)): ?>
|
<?php if (!empty($canViewGrading)): ?>
|
||||||
<a class="btn btn-outline-secondary btn-sm" href="<?= base_url('grading') ?>">
|
<a class="btn btn-outline-secondary btn-sm" href="<?= base_url('grading') ?>">
|
||||||
Grading
|
Grading
|
||||||
@@ -34,6 +94,7 @@
|
|||||||
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
||||||
</div>
|
</div>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
|
|
||||||
<?php if (!empty(session()->getFlashdata('error'))): ?>
|
<?php if (!empty(session()->getFlashdata('error'))): ?>
|
||||||
<div class="alert alert-danger alert-dismissible fade show" role="alert">
|
<div class="alert alert-danger alert-dismissible fade show" role="alert">
|
||||||
<?= esc(session()->getFlashdata('error')) ?>
|
<?= esc(session()->getFlashdata('error')) ?>
|
||||||
@@ -47,7 +108,7 @@
|
|||||||
'Pass' => 'Pass',
|
'Pass' => 'Pass',
|
||||||
'Repeat Class' => 'Repeat Class',
|
'Repeat Class' => 'Repeat Class',
|
||||||
'Make-up exam in fall' => 'Make-up exam in fall',
|
'Make-up exam in fall' => 'Make-up exam in fall',
|
||||||
'Deferred decision' => 'Deferred decision',
|
'Deferred decision' => 'Deferred decision',
|
||||||
'Expel' => 'Expel',
|
'Expel' => 'Expel',
|
||||||
'Withdrawn' => 'Withdrawn',
|
'Withdrawn' => 'Withdrawn',
|
||||||
];
|
];
|
||||||
@@ -56,128 +117,139 @@
|
|||||||
'Pass' => 'success',
|
'Pass' => 'success',
|
||||||
'Repeat Class' => 'danger',
|
'Repeat Class' => 'danger',
|
||||||
'Make-up exam in fall' => 'info',
|
'Make-up exam in fall' => 'info',
|
||||||
'Deferred decision' => 'info',
|
'Deferred decision' => 'info',
|
||||||
'Expel' => 'danger',
|
'Expel' => 'danger',
|
||||||
'Withdrawn' => 'secondary',
|
'Withdrawn' => 'secondary',
|
||||||
];
|
];
|
||||||
|
|
||||||
$displayScore = function ($value) {
|
$displayScore = function ($value) {
|
||||||
if ($value === null || $value === '') return '—';
|
if ($value === null || $value === '') {
|
||||||
if (is_numeric($value)) return esc(number_format((float)$value, 2, '.', ''));
|
return '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_numeric($value)) {
|
||||||
|
return esc(number_format((float)$value, 2, '.', ''));
|
||||||
|
}
|
||||||
|
|
||||||
return esc($value);
|
return esc($value);
|
||||||
};
|
};
|
||||||
?>
|
?>
|
||||||
|
|
||||||
<?php if (empty($rows)): ?>
|
<?php if (empty($rows)): ?>
|
||||||
<div class="alert alert-success text-center d-inline-block">
|
<div class="alert alert-success text-center d-inline-block">
|
||||||
No students below 60 for this selection.
|
No students below 60 for the whole year in <?= esc($schoolYear) ?>.
|
||||||
</div>
|
</div>
|
||||||
<?php else: ?>
|
<?php else: ?>
|
||||||
<div class="table-responsive">
|
<div class="table-responsive">
|
||||||
<table class="table table-bordered table-striped align-middle w-100 decisions-dt" data-no-mgmt-sticky data-no-dt-fixedheader>
|
<table class="table table-bordered table-striped align-middle w-100 decisions-dt"
|
||||||
|
data-no-mgmt-sticky
|
||||||
|
data-no-dt-fixedheader>
|
||||||
<thead class="table-light">
|
<thead class="table-light">
|
||||||
<tr>
|
<tr>
|
||||||
<th style="min-width:160px">Student Name</th>
|
<th style="min-width:160px">Student Name</th>
|
||||||
<th>Section</th>
|
<th class="text-center">Age</th>
|
||||||
<th class="text-center">Score</th>
|
<th>Class-Section</th>
|
||||||
|
<th class="text-center">Year Score</th>
|
||||||
<th style="min-width:300px">Comments / Rationale & Decision</th>
|
<th style="min-width:300px">Comments / Rationale & Decision</th>
|
||||||
<th style="min-width:150px" class="text-center">Below-60 Decision</th>
|
<th style="min-width:150px" class="text-center">Below-60 Decision</th>
|
||||||
<th style="min-width:130px" class="text-center">Final Decision</th>
|
|
||||||
<th style="min-width:130px" class="text-center">Certificate</th>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
|
|
||||||
<tbody>
|
<tbody>
|
||||||
<?php foreach ($rows as $row): ?>
|
<?php foreach ($rows as $row): ?>
|
||||||
<?php
|
<?php
|
||||||
$scoreRaw = $row['semester_score'] ?? null;
|
// Whole-year page: use year_score only.
|
||||||
$scoreVal = is_numeric($scoreRaw) ? (float)$scoreRaw : null;
|
// Do not fall back to semester_score, because this page should not display semester results.
|
||||||
$rowClass = '';
|
$scoreRaw = $row['year_score'] ?? null;
|
||||||
|
$scoreVal = is_numeric($scoreRaw) ? (float)$scoreRaw : null;
|
||||||
|
|
||||||
|
$rowClass = '';
|
||||||
if ($scoreVal !== null) {
|
if ($scoreVal !== null) {
|
||||||
$rowClass = $scoreVal < 50 ? 'grade-red' : 'grade-orange';
|
$rowClass = $scoreVal < 50 ? 'grade-red' : 'grade-orange';
|
||||||
}
|
}
|
||||||
|
|
||||||
$studentName = trim((string)($row['firstname'] ?? '') . ' ' . (string)($row['lastname'] ?? ''));
|
$studentName = trim((string)($row['firstname'] ?? '') . ' ' . (string)($row['lastname'] ?? ''));
|
||||||
|
$studentLabel = $studentName !== '' ? $studentName : 'N/A';
|
||||||
$currentDecision = (string)($row['decision'] ?? '');
|
$currentDecision = (string)($row['decision'] ?? '');
|
||||||
$currentNotes = (string)($row['decision_notes'] ?? '');
|
$currentNotes = (string)($row['decision_notes'] ?? '');
|
||||||
$badge = $decisionBadge[$currentDecision] ?? null;
|
$badge = $decisionBadge[$currentDecision] ?? null;
|
||||||
?>
|
?>
|
||||||
|
|
||||||
<tr class="<?= esc($rowClass) ?>">
|
<tr class="<?= esc($rowClass) ?>">
|
||||||
<td><?= esc($studentName !== '' ? $studentName : 'N/A') ?></td>
|
<td><?= esc($studentLabel) ?></td>
|
||||||
|
|
||||||
|
<td class="text-center"><?= esc((string)($row['age'] ?? '—')) ?></td>
|
||||||
|
|
||||||
<td><?= esc($row['class_section_name'] ?? '—') ?></td>
|
<td><?= esc($row['class_section_name'] ?? '—') ?></td>
|
||||||
<td class="text-center">
|
|
||||||
|
<td class="text-center" data-order="<?= esc($scoreVal !== null ? (string)$scoreVal : '-1') ?>">
|
||||||
<div class="fw-semibold"><?= $displayScore($scoreRaw) ?></div>
|
<div class="fw-semibold"><?= $displayScore($scoreRaw) ?></div>
|
||||||
|
|
||||||
<button type="button"
|
<button type="button"
|
||||||
class="btn btn-outline-secondary btn-xs mt-1 btn-show-details"
|
class="btn btn-outline-secondary btn-xs mt-1 btn-show-details"
|
||||||
style="font-size:0.72rem;padding:1px 7px;"
|
style="font-size:0.72rem;padding:1px 7px;"
|
||||||
data-student-id="<?= (int)($row['student_id'] ?? 0) ?>"
|
data-student-id="<?= (int)($row['student_id'] ?? 0) ?>"
|
||||||
data-student-name="<?= esc($studentName !== '' ? $studentName : 'N/A') ?>"
|
data-student-name="<?= esc($studentLabel) ?>"
|
||||||
data-school-year="<?= esc((string)($schoolYear ?? '')) ?>">
|
data-school-year="<?= esc((string)$schoolYear) ?>">
|
||||||
Details
|
Details
|
||||||
</button>
|
</button>
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
<td>
|
<td>
|
||||||
<form method="post" action="<?= site_url('grading/below-60/decisions/save') ?>">
|
<form method="post" action="<?= site_url('grading/below-60/decisions/save') ?>">
|
||||||
<?= csrf_field() ?>
|
<?= csrf_field() ?>
|
||||||
<input type="hidden" name="student_id" value="<?= esc((string)($row['student_id'] ?? '')) ?>">
|
|
||||||
<input type="hidden" name="semester" value="<?= esc((string)($semester ?? '')) ?>">
|
<input type="hidden"
|
||||||
<input type="hidden" name="school_year" value="<?= esc((string)($schoolYear ?? '')) ?>">
|
name="student_id"
|
||||||
|
value="<?= esc((string)($row['student_id'] ?? '')) ?>">
|
||||||
|
|
||||||
|
<input type="hidden"
|
||||||
|
name="semester"
|
||||||
|
value="year">
|
||||||
|
|
||||||
|
<input type="hidden"
|
||||||
|
name="school_year"
|
||||||
|
value="<?= esc((string)$schoolYear) ?>">
|
||||||
|
|
||||||
<textarea name="notes"
|
<textarea name="notes"
|
||||||
class="form-control form-control-sm decision-notes"
|
class="form-control form-control-sm decision-notes"
|
||||||
rows="3"
|
rows="3"
|
||||||
placeholder="Add comments or rationale…"><?= esc($currentNotes) ?></textarea>
|
placeholder="Add comments or rationale…"><?= esc($currentNotes) ?></textarea>
|
||||||
|
|
||||||
<div class="d-flex gap-2 mt-2 align-items-center">
|
<div class="d-flex gap-2 mt-2 align-items-center">
|
||||||
<select name="decision" class="form-select form-select-sm decision-select flex-grow-1">
|
<select name="decision"
|
||||||
|
class="form-select form-select-sm decision-select flex-grow-1">
|
||||||
<?php foreach ($decisionOptions as $val => $label): ?>
|
<?php foreach ($decisionOptions as $val => $label): ?>
|
||||||
<option value="<?= esc($val) ?>" <?= $currentDecision === $val ? 'selected' : '' ?>>
|
<option value="<?= esc($val) ?>" <?= $currentDecision === $val ? 'selected' : '' ?>>
|
||||||
<?= esc($label) ?>
|
<?= esc($label) ?>
|
||||||
</option>
|
</option>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</select>
|
</select>
|
||||||
<button type="submit" class="btn btn-sm btn-primary">Save</button>
|
|
||||||
|
<button type="submit" class="btn btn-sm btn-primary">
|
||||||
|
Save
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
<td class="text-center align-middle">
|
<td class="text-center align-middle">
|
||||||
<?php if ($currentDecision !== '' && $badge): ?>
|
<?php if ($currentDecision !== '' && $badge): ?>
|
||||||
<span class="badge bg-<?= esc($badge) ?> fs-6 px-3 py-2 d-block mb-2"><?= esc($currentDecision) ?></span>
|
<span class="badge bg-<?= esc($badge) ?> fs-6 px-3 py-2 d-block mb-2">
|
||||||
|
<?= esc($currentDecision) ?>
|
||||||
|
</span>
|
||||||
|
|
||||||
<button type="button"
|
<button type="button"
|
||||||
class="btn btn-sm btn-outline-primary btn-send-email"
|
class="btn btn-sm btn-outline-primary btn-send-email"
|
||||||
data-student-id="<?= (int)($row['student_id'] ?? 0) ?>"
|
data-student-id="<?= (int)($row['student_id'] ?? 0) ?>"
|
||||||
data-semester="<?= esc((string)($semester ?? '')) ?>"
|
data-semester="year"
|
||||||
data-school-year="<?= esc((string)($schoolYear ?? '')) ?>">
|
data-school-year="<?= esc((string)$schoolYear) ?>">
|
||||||
Send Email
|
Send Email
|
||||||
</button>
|
</button>
|
||||||
<?php else: ?>
|
<?php else: ?>
|
||||||
<span class="text-muted small">Pending</span>
|
<span class="text-muted small">Pending</span>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</td>
|
</td>
|
||||||
|
|
||||||
<?php
|
|
||||||
// Final (consolidated) decision from student_decisions table
|
|
||||||
$finalDecision = $row['consolidated_decision'] ?? null;
|
|
||||||
$finalBadge = $finalDecision !== null ? ($decisionBadge[$finalDecision] ?? 'secondary') : null;
|
|
||||||
?>
|
|
||||||
<td class="text-center align-middle">
|
|
||||||
<?php if ($finalDecision !== null && $finalDecision !== ''): ?>
|
|
||||||
<span class="badge bg-<?= esc($finalBadge) ?> px-2 py-1"><?= esc($finalDecision) ?></span>
|
|
||||||
<?php else: ?>
|
|
||||||
<a href="<?= site_url('grading/decisions?' . http_build_query(['semester' => $semester ?? '', 'school_year' => $schoolYear ?? ''])) ?>"
|
|
||||||
class="text-muted small">Generate</a>
|
|
||||||
<?php endif; ?>
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<?php $certNumber = (string)($row['certificate_number'] ?? ''); ?>
|
|
||||||
<td class="text-center align-middle">
|
|
||||||
<?php if ($certNumber !== ''): ?>
|
|
||||||
<a href="<?= site_url('administrator/certificates/reprint/' . rawurlencode($certNumber)) ?>"
|
|
||||||
target="_blank"
|
|
||||||
class="font-monospace text-decoration-none fw-semibold"
|
|
||||||
title="Click to reprint certificate">
|
|
||||||
<?= esc($certNumber) ?>
|
|
||||||
</a>
|
|
||||||
<?php else: ?>
|
|
||||||
<span class="text-muted small">—</span>
|
|
||||||
<?php endif; ?>
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
</tbody>
|
</tbody>
|
||||||
@@ -186,9 +258,14 @@
|
|||||||
|
|
||||||
<div class="mt-3 mb-4 d-flex gap-2 flex-wrap">
|
<div class="mt-3 mb-4 d-flex gap-2 flex-wrap">
|
||||||
<?php foreach ($decisionBadge as $label => $color): ?>
|
<?php foreach ($decisionBadge as $label => $color): ?>
|
||||||
<span class="badge bg-<?= esc($color) ?> px-3 py-2"><?= esc($label) ?></span>
|
<span class="badge bg-<?= esc($color) ?> px-3 py-2">
|
||||||
|
<?= esc($label) ?>
|
||||||
|
</span>
|
||||||
<?php endforeach; ?>
|
<?php endforeach; ?>
|
||||||
<span class="text-muted small align-self-center ms-1">— decision colour key</span>
|
|
||||||
|
<span class="text-muted small align-self-center ms-1">
|
||||||
|
— decision colour key
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
</div>
|
</div>
|
||||||
@@ -202,13 +279,19 @@
|
|||||||
<h5 class="modal-title" id="detailsModalLabel">Score Details</h5>
|
<h5 class="modal-title" id="detailsModalLabel">Score Details</h5>
|
||||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="modal-body" id="detailsModalBody">
|
<div class="modal-body" id="detailsModalBody">
|
||||||
<div class="text-center py-4">
|
<div class="text-center py-4">
|
||||||
<div class="spinner-border text-primary" role="status"></div>
|
<div class="spinner-border text-primary" role="status"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
|
<button type="button"
|
||||||
|
class="btn btn-outline-secondary"
|
||||||
|
data-bs-dismiss="modal">
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -232,29 +315,46 @@
|
|||||||
<div class="alert alert-danger mb-0" id="emailModalErrorMsg"></div>
|
<div class="alert alert-danger mb-0" id="emailModalErrorMsg"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form id="decisionEmailForm" method="post"
|
<form id="decisionEmailForm"
|
||||||
|
method="post"
|
||||||
action="<?= site_url('grading/below-60/decisions/email') ?>"
|
action="<?= site_url('grading/below-60/decisions/email') ?>"
|
||||||
style="display:none;">
|
style="display:none;">
|
||||||
<?= csrf_field() ?>
|
<?= csrf_field() ?>
|
||||||
<input type="hidden" name="student_id" id="emailStudentId">
|
|
||||||
<input type="hidden" name="semester" id="emailSemester">
|
<input type="hidden" name="student_id" id="emailStudentId">
|
||||||
|
<input type="hidden" name="semester" id="emailSemester" value="year">
|
||||||
<input type="hidden" name="school_year" id="emailSchoolYear">
|
<input type="hidden" name="school_year" id="emailSchoolYear">
|
||||||
<input type="hidden" name="html" id="emailHtmlHidden">
|
<input type="hidden" name="html" id="emailHtmlHidden">
|
||||||
|
|
||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label class="form-label fw-semibold" for="emailSubjectInput">Subject</label>
|
<label class="form-label fw-semibold" for="emailSubjectInput">Subject</label>
|
||||||
<input type="text" class="form-control" id="emailSubjectInput" name="subject" required>
|
<input type="text"
|
||||||
|
class="form-control"
|
||||||
|
id="emailSubjectInput"
|
||||||
|
name="subject"
|
||||||
|
required>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-1">
|
<div class="mb-1">
|
||||||
<label class="form-label fw-semibold">Body</label>
|
<label class="form-label fw-semibold">Body</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<textarea id="decisionEmailEditor" rows="18"></textarea>
|
<textarea id="decisionEmailEditor" rows="18"></textarea>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
|
<button type="button"
|
||||||
<button type="submit" class="btn btn-primary" id="emailSendBtn">Send Email</button>
|
class="btn btn-outline-secondary"
|
||||||
|
data-bs-dismiss="modal">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button type="submit"
|
||||||
|
class="btn btn-primary"
|
||||||
|
id="emailSendBtn">
|
||||||
|
Send Email
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
@@ -265,34 +365,55 @@
|
|||||||
|
|
||||||
<?= $this->section('scripts') ?>
|
<?= $this->section('scripts') ?>
|
||||||
<style>
|
<style>
|
||||||
.grade-orange td { background: #fff3cd !important; color: #8a5d00; }
|
.grade-orange td {
|
||||||
.grade-red td { background: #f8d7da !important; color: #842029; }
|
background: #fff3cd !important;
|
||||||
.decision-notes { font-size: 0.85rem; resize: vertical; min-height: 60px; }
|
color: #8a5d00;
|
||||||
.decisions-dt td { vertical-align: top; }
|
}
|
||||||
|
|
||||||
|
.grade-red td {
|
||||||
|
background: #f8d7da !important;
|
||||||
|
color: #842029;
|
||||||
|
}
|
||||||
|
|
||||||
|
.decision-notes {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
resize: vertical;
|
||||||
|
min-height: 60px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.decisions-dt td {
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
<script src="<?= base_url('assets/tinymce/tinymce.min.js') ?>"></script>
|
<script src="<?= base_url('assets/tinymce/tinymce.min.js') ?>"></script>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
// DataTable
|
// DataTable
|
||||||
if (window.$ && $.fn && $.fn.DataTable) {
|
if (window.$ && $.fn && $.fn.DataTable) {
|
||||||
$(function () {
|
$(function () {
|
||||||
const tbl = $('.decisions-dt');
|
const tbl = $('.decisions-dt');
|
||||||
|
|
||||||
if (!tbl.length) return;
|
if (!tbl.length) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
tbl.DataTable({
|
tbl.DataTable({
|
||||||
order: [[2, 'asc']],
|
order: [[2, 'asc']],
|
||||||
pageLength: 100,
|
pageLength: 100,
|
||||||
lengthMenu: [10, 25, 50, 100, 200],
|
lengthMenu: [10, 25, 50, 100, 200],
|
||||||
columnDefs: [{ orderable: false, targets: [3] }]
|
columnDefs: [
|
||||||
|
{ orderable: false, targets: [4] }
|
||||||
|
]
|
||||||
});
|
});
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Details modal ────────────────────────────────────────────
|
// ── Details modal ────────────────────────────────────────────
|
||||||
const detailsModal = document.getElementById('detailsModal');
|
const detailsModal = document.getElementById('detailsModal');
|
||||||
const detailsModalBody = document.getElementById('detailsModalBody');
|
const detailsModalBody = document.getElementById('detailsModalBody');
|
||||||
const detailsModalTitle= document.getElementById('detailsModalLabel');
|
const detailsModalTitle = document.getElementById('detailsModalLabel');
|
||||||
|
|
||||||
const SCORE_LABELS = {
|
const SCORE_LABELS = {
|
||||||
homework_avg: 'Homework Avg',
|
homework_avg: 'Homework Avg',
|
||||||
@@ -303,7 +424,7 @@
|
|||||||
attendance_score: 'Attendance',
|
attendance_score: 'Attendance',
|
||||||
midterm_exam_score: 'Midterm Score',
|
midterm_exam_score: 'Midterm Score',
|
||||||
final_exam_score: 'Final Exam',
|
final_exam_score: 'Final Exam',
|
||||||
semester_score: 'Semester Score',
|
semester_score: 'Semester Score'
|
||||||
};
|
};
|
||||||
|
|
||||||
const COMMENT_TYPE_LABELS = {
|
const COMMENT_TYPE_LABELS = {
|
||||||
@@ -312,12 +433,14 @@
|
|||||||
attendance_comment: 'Attendance',
|
attendance_comment: 'Attendance',
|
||||||
midterm: 'Midterm',
|
midterm: 'Midterm',
|
||||||
final: 'Final Exam',
|
final: 'Final Exam',
|
||||||
ptap: 'PTAP',
|
ptap: 'PTAP'
|
||||||
};
|
};
|
||||||
|
|
||||||
function fmtScore(v) {
|
function fmtScore(v) {
|
||||||
if (v === null || v === '' || v === undefined) return '—';
|
if (v === null || v === '' || v === undefined) return '—';
|
||||||
|
|
||||||
const n = parseFloat(v);
|
const n = parseFloat(v);
|
||||||
|
|
||||||
return isNaN(n) ? v : n.toFixed(2);
|
return isNaN(n) ? v : n.toFixed(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,78 +456,110 @@
|
|||||||
if (!semesters || semesters.length === 0) {
|
if (!semesters || semesters.length === 0) {
|
||||||
return '<div class="alert alert-warning mb-0">No score data found.</div>';
|
return '<div class="alert alert-warning mb-0">No score data found.</div>';
|
||||||
}
|
}
|
||||||
|
|
||||||
let html = '';
|
let html = '';
|
||||||
|
|
||||||
semesters.forEach(function (sem) {
|
semesters.forEach(function (sem) {
|
||||||
html += '<h6 class="fw-bold mt-3 mb-2">' + esc(sem.semester || '') + ' Semester';
|
html += '<h6 class="fw-bold mt-3 mb-2">' + esc(sem.semester || '') + ' Semester';
|
||||||
if (sem.class_section_name) html += ' <span class="text-muted fw-normal fs-6">— ' + esc(sem.class_section_name) + '</span>';
|
|
||||||
|
if (sem.class_section_name) {
|
||||||
|
html += ' <span class="text-muted fw-normal fs-6">— ' + esc(sem.class_section_name) + '</span>';
|
||||||
|
}
|
||||||
|
|
||||||
html += '</h6>';
|
html += '</h6>';
|
||||||
|
|
||||||
// Scores table
|
|
||||||
html += '<table class="table table-sm table-bordered mb-2">';
|
html += '<table class="table table-sm table-bordered mb-2">';
|
||||||
html += '<thead class="table-light"><tr><th>Item</th><th class="text-center">Score</th></tr></thead><tbody>';
|
html += '<thead class="table-light"><tr><th>Item</th><th class="text-center">Score</th></tr></thead><tbody>';
|
||||||
|
|
||||||
let hasRow = false;
|
let hasRow = false;
|
||||||
|
|
||||||
Object.entries(SCORE_LABELS).forEach(function ([key, label]) {
|
Object.entries(SCORE_LABELS).forEach(function ([key, label]) {
|
||||||
const v = sem[key];
|
const v = sem[key];
|
||||||
|
|
||||||
if (v === null || v === '' || v === undefined) return;
|
if (v === null || v === '' || v === undefined) return;
|
||||||
|
|
||||||
const bold = key === 'semester_score' ? ' fw-bold' : '';
|
const bold = key === 'semester_score' ? ' fw-bold' : '';
|
||||||
html += '<tr><td>' + label + '</td><td class="text-center' + bold + '">' + fmtScore(v) + '</td></tr>';
|
|
||||||
|
html += '<tr><td>' + esc(label) + '</td><td class="text-center' + bold + '">' + esc(fmtScore(v)) + '</td></tr>';
|
||||||
hasRow = true;
|
hasRow = true;
|
||||||
});
|
});
|
||||||
if (!hasRow) html += '<tr><td colspan="2" class="text-muted">No scores recorded.</td></tr>';
|
|
||||||
|
if (!hasRow) {
|
||||||
|
html += '<tr><td colspan="2" class="text-muted">No scores recorded.</td></tr>';
|
||||||
|
}
|
||||||
|
|
||||||
html += '</tbody></table>';
|
html += '</tbody></table>';
|
||||||
|
|
||||||
// Comments section
|
|
||||||
const comments = sem.comments || {};
|
const comments = sem.comments || {};
|
||||||
const commentEntries = Object.entries(comments).filter(function ([, v]) { return v && v.trim(); });
|
|
||||||
|
|
||||||
// Deduplicate attendance + attendance_comment (show once)
|
const commentEntries = Object.entries(comments).filter(function ([, v]) {
|
||||||
|
return v && String(v).trim();
|
||||||
|
});
|
||||||
|
|
||||||
const seen = {};
|
const seen = {};
|
||||||
const deduped = [];
|
const deduped = [];
|
||||||
|
|
||||||
commentEntries.forEach(function ([type, text]) {
|
commentEntries.forEach(function ([type, text]) {
|
||||||
const label = COMMENT_TYPE_LABELS[type] || type;
|
const label = COMMENT_TYPE_LABELS[type] || type;
|
||||||
const key = label + '|' + text.trim();
|
const key = label + '|' + String(text).trim();
|
||||||
if (!seen[key]) { seen[key] = true; deduped.push([label, text]); }
|
|
||||||
|
if (!seen[key]) {
|
||||||
|
seen[key] = true;
|
||||||
|
deduped.push([label, String(text)]);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (deduped.length > 0) {
|
if (deduped.length > 0) {
|
||||||
html += '<div class="mb-3">';
|
html += '<div class="mb-3">';
|
||||||
html += '<p class="fw-semibold mb-1" style="font-size:0.9rem;">Comments</p>';
|
html += '<p class="fw-semibold mb-1" style="font-size:0.9rem;">Comments</p>';
|
||||||
|
|
||||||
deduped.forEach(function ([label, text]) {
|
deduped.forEach(function ([label, text]) {
|
||||||
html += '<div class="mb-2 p-2 bg-light rounded border-start border-3 border-secondary">';
|
html += '<div class="mb-2 p-2 bg-light rounded border-start border-3 border-secondary">';
|
||||||
html += '<span class="badge bg-secondary me-1" style="font-size:0.7rem;">' + esc(label) + '</span>';
|
html += '<span class="badge bg-secondary me-1" style="font-size:0.7rem;">' + esc(label) + '</span>';
|
||||||
html += '<span class="text-dark" style="font-size:0.9rem;">' + esc(text).replace(/\n/g, '<br>') + '</span>';
|
html += '<span class="text-dark" style="font-size:0.9rem;">' + esc(text).replace(/\n/g, '<br>') + '</span>';
|
||||||
html += '</div>';
|
html += '</div>';
|
||||||
});
|
});
|
||||||
|
|
||||||
html += '</div>';
|
html += '</div>';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return html;
|
return html;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (detailsModal) {
|
if (detailsModal) {
|
||||||
document.addEventListener('click', function (e) {
|
document.addEventListener('click', function (e) {
|
||||||
const btn = e.target.closest('.btn-show-details');
|
const btn = e.target.closest('.btn-show-details');
|
||||||
|
|
||||||
if (!btn) return;
|
if (!btn) return;
|
||||||
|
|
||||||
const studentId = btn.dataset.studentId;
|
const studentId = btn.dataset.studentId;
|
||||||
const studentName= btn.dataset.studentName;
|
const studentName = btn.dataset.studentName;
|
||||||
const schoolYear = btn.dataset.schoolYear;
|
const schoolYear = btn.dataset.schoolYear;
|
||||||
|
|
||||||
detailsModalTitle.textContent = studentName + ' — Score Details';
|
detailsModalTitle.textContent = studentName + ' — Score Details';
|
||||||
detailsModalBody.innerHTML = '<div class="text-center py-4"><div class="spinner-border text-primary" role="status"></div></div>';
|
detailsModalBody.innerHTML = '<div class="text-center py-4"><div class="spinner-border text-primary" role="status"></div></div>';
|
||||||
|
|
||||||
bootstrap.Modal.getOrCreateInstance(detailsModal).show();
|
bootstrap.Modal.getOrCreateInstance(detailsModal).show();
|
||||||
|
|
||||||
const url = '<?= site_url('grading/below-60/decisions/student-details') ?>'
|
const url = '<?= site_url('grading/below-60/decisions/student-details') ?>'
|
||||||
+ '?student_id=' + encodeURIComponent(studentId)
|
+ '?student_id=' + encodeURIComponent(studentId)
|
||||||
+ '&school_year=' + encodeURIComponent(schoolYear);
|
+ '&school_year=' + encodeURIComponent(schoolYear);
|
||||||
|
|
||||||
fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
|
fetch(url, {
|
||||||
.then(function (r) { return r.json(); })
|
headers: {
|
||||||
|
'X-Requested-With': 'XMLHttpRequest'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(function (r) {
|
||||||
|
return r.json();
|
||||||
|
})
|
||||||
.then(function (data) {
|
.then(function (data) {
|
||||||
if (data.error) {
|
if (data.error) {
|
||||||
detailsModalBody.innerHTML = '<div class="alert alert-danger">' + data.error + '</div>';
|
detailsModalBody.innerHTML = '<div class="alert alert-danger">' + esc(data.error) + '</div>';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
detailsModalBody.innerHTML = buildDetailsHtml(data.semesters);
|
detailsModalBody.innerHTML = buildDetailsHtml(data.semesters);
|
||||||
})
|
})
|
||||||
.catch(function () {
|
.catch(function () {
|
||||||
@@ -429,8 +584,8 @@
|
|||||||
|
|
||||||
function showPane(which) {
|
function showPane(which) {
|
||||||
loadingPane.style.display = which === 'loading' ? '' : 'none';
|
loadingPane.style.display = which === 'loading' ? '' : 'none';
|
||||||
errorPane.style.display = which === 'error' ? '' : 'none';
|
errorPane.style.display = which === 'error' ? '' : 'none';
|
||||||
form.style.display = which === 'form' ? '' : 'none';
|
form.style.display = which === 'form' ? '' : 'none';
|
||||||
}
|
}
|
||||||
|
|
||||||
function destroyEditor() {
|
function destroyEditor() {
|
||||||
@@ -441,6 +596,7 @@
|
|||||||
|
|
||||||
function initEditor(html) {
|
function initEditor(html) {
|
||||||
if (!window.tinymce) return;
|
if (!window.tinymce) return;
|
||||||
|
|
||||||
tinymce.init({
|
tinymce.init({
|
||||||
selector: '#decisionEmailEditor',
|
selector: '#decisionEmailEditor',
|
||||||
base_url: '<?= base_url('assets/tinymce') ?>',
|
base_url: '<?= base_url('assets/tinymce') ?>',
|
||||||
@@ -462,65 +618,76 @@
|
|||||||
setup(editor) {
|
setup(editor) {
|
||||||
editor.on('init', function () {
|
editor.on('init', function () {
|
||||||
editor.setContent(html);
|
editor.setContent(html);
|
||||||
if (htmlHidden) htmlHidden.value = html;
|
|
||||||
|
if (htmlHidden) {
|
||||||
|
htmlHidden.value = html;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
editor.on('keyup change undo redo SetContent', function () {
|
editor.on('keyup change undo redo SetContent', function () {
|
||||||
if (htmlHidden) htmlHidden.value = editor.getContent({ format: 'html' });
|
if (htmlHidden) {
|
||||||
|
htmlHidden.value = editor.getContent({ format: 'html' });
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sync hidden field before form submit
|
|
||||||
form.addEventListener('submit', function () {
|
form.addEventListener('submit', function () {
|
||||||
if (window.tinymce) {
|
if (window.tinymce) {
|
||||||
const ed = tinymce.get('decisionEmailEditor');
|
const ed = tinymce.get('decisionEmailEditor');
|
||||||
if (ed && htmlHidden) htmlHidden.value = ed.getContent({ format: 'html' });
|
|
||||||
|
if (ed && htmlHidden) {
|
||||||
|
htmlHidden.value = ed.getContent({ format: 'html' });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Destroy editor when modal closes
|
|
||||||
modal.addEventListener('hidden.bs.modal', function () {
|
modal.addEventListener('hidden.bs.modal', function () {
|
||||||
destroyEditor();
|
destroyEditor();
|
||||||
showPane('loading');
|
showPane('loading');
|
||||||
});
|
});
|
||||||
|
|
||||||
// Open modal when "Send Email" is clicked
|
|
||||||
document.addEventListener('click', function (e) {
|
document.addEventListener('click', function (e) {
|
||||||
const btn = e.target.closest('.btn-send-email');
|
const btn = e.target.closest('.btn-send-email');
|
||||||
|
|
||||||
if (!btn) return;
|
if (!btn) return;
|
||||||
|
|
||||||
const studentId = btn.dataset.studentId;
|
const studentId = btn.dataset.studentId;
|
||||||
const semester = btn.dataset.semester;
|
|
||||||
const schoolYear = btn.dataset.schoolYear;
|
const schoolYear = btn.dataset.schoolYear;
|
||||||
|
|
||||||
studentIdIn.value = studentId;
|
studentIdIn.value = studentId;
|
||||||
semesterIn.value = semester;
|
semesterIn.value = 'year';
|
||||||
schoolYearIn.value = schoolYear;
|
schoolYearIn.value = schoolYear;
|
||||||
|
|
||||||
showPane('loading');
|
showPane('loading');
|
||||||
|
|
||||||
// Open the modal immediately (shows spinner)
|
|
||||||
const bsModal = bootstrap.Modal.getOrCreateInstance(modal);
|
const bsModal = bootstrap.Modal.getOrCreateInstance(modal);
|
||||||
bsModal.show();
|
bsModal.show();
|
||||||
|
|
||||||
// Fetch the pre-rendered email
|
|
||||||
const url = '<?= site_url('grading/below-60/decisions/email/preview') ?>'
|
const url = '<?= site_url('grading/below-60/decisions/email/preview') ?>'
|
||||||
+ '?student_id=' + encodeURIComponent(studentId)
|
+ '?student_id=' + encodeURIComponent(studentId)
|
||||||
+ '&semester=' + encodeURIComponent(semester)
|
+ '&semester=year'
|
||||||
+ '&school_year='+ encodeURIComponent(schoolYear);
|
+ '&school_year=' + encodeURIComponent(schoolYear);
|
||||||
|
|
||||||
fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
|
fetch(url, {
|
||||||
.then(function (res) { return res.json(); })
|
headers: {
|
||||||
|
'X-Requested-With': 'XMLHttpRequest'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(function (res) {
|
||||||
|
return res.json();
|
||||||
|
})
|
||||||
.then(function (data) {
|
.then(function (data) {
|
||||||
if (data.error) {
|
if (data.error) {
|
||||||
errorMsg.textContent = data.error;
|
errorMsg.textContent = data.error;
|
||||||
showPane('error');
|
showPane('error');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
subjectInput.value = data.subject || '';
|
subjectInput.value = data.subject || '';
|
||||||
// Reset textarea content before init
|
|
||||||
document.getElementById('decisionEmailEditor').value = data.html || '';
|
document.getElementById('decisionEmailEditor').value = data.html || '';
|
||||||
|
|
||||||
showPane('form');
|
showPane('form');
|
||||||
initEditor(data.html || '');
|
initEditor(data.html || '');
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -40,12 +40,7 @@
|
|||||||
|
|
||||||
<div class="col-md-6">
|
<div class="col-md-6">
|
||||||
<h4>Payment Options</h4>
|
<h4>Payment Options</h4>
|
||||||
<form method="post" action="<?= base_url('payments/createPaypalPayment/' . $payment['id']) ?>">
|
<p class="text-muted mb-0">Online payment is currently unavailable. Please contact the school office to complete payment.</p>
|
||||||
<?= csrf_field(); ?>
|
|
||||||
<button type="submit" class="btn btn-primary btn-block">
|
|
||||||
Pay via PayPal
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -133,9 +133,9 @@ $role = strtolower(session()->get('role') ?? 'guest');
|
|||||||
<a class="dropdown-item" href="/discounts/list">Discount Management</a>
|
<a class="dropdown-item" href="/discounts/list">Discount Management</a>
|
||||||
<a class="dropdown-item" href="/expenses/index">Expenses Management</a>
|
<a class="dropdown-item" href="/expenses/index">Expenses Management</a>
|
||||||
<a class="dropdown-item" href="/payment/financial_report">Financial Report</a>
|
<a class="dropdown-item" href="/payment/financial_report">Financial Report</a>
|
||||||
|
<a class="dropdown-item" href="/administrator/tuition-forecast">Tuition Forecast</a>
|
||||||
<a class="dropdown-item" href="/invoice_payment/invoice_management">Invoices Management</a>
|
<a class="dropdown-item" href="/invoice_payment/invoice_management">Invoices Management</a>
|
||||||
<a class="dropdown-item" href="/payment/manual_pay">Manual Payment</a>
|
<a class="dropdown-item" href="/payment/manual_pay">Manual Payment</a>
|
||||||
<a class="dropdown-item" href="/administrator/paypal_transactions">PaypalTransactions</a>
|
|
||||||
<a class="dropdown-item" href="/refunds/list">Refund Management</a>
|
<a class="dropdown-item" href="/refunds/list">Refund Management</a>
|
||||||
<a class="dropdown-item" href="/reimbursements/index">Reimbursement Management</a>
|
<a class="dropdown-item" href="/reimbursements/index">Reimbursement Management</a>
|
||||||
<a class="dropdown-item" href="/payment/notification_management">Payment Notification Management</a>
|
<a class="dropdown-item" href="/payment/notification_management">Payment Notification Management</a>
|
||||||
@@ -233,9 +233,9 @@ $role = strtolower(session()->get('role') ?? 'guest');
|
|||||||
<a class="dropdown-item" href="/discounts/list">Discount Management</a>
|
<a class="dropdown-item" href="/discounts/list">Discount Management</a>
|
||||||
<a class="dropdown-item" href="/expenses/index">Expenses Management</a>
|
<a class="dropdown-item" href="/expenses/index">Expenses Management</a>
|
||||||
<a class="dropdown-item" href="/payment/financial_report">Financial Report</a>
|
<a class="dropdown-item" href="/payment/financial_report">Financial Report</a>
|
||||||
|
<a class="dropdown-item" href="/administrator/tuition-forecast">Tuition Forecast</a>
|
||||||
<a class="dropdown-item" href="/invoice_payment/invoice_management">Invoices Management</a>
|
<a class="dropdown-item" href="/invoice_payment/invoice_management">Invoices Management</a>
|
||||||
<a class="dropdown-item" href="/payment/manual_pay">Manual Payment</a>
|
<a class="dropdown-item" href="/payment/manual_pay">Manual Payment</a>
|
||||||
<a class="dropdown-item" href="/administrator/paypal_transactions">PaypalTransactions</a>
|
|
||||||
<a class="dropdown-item" href="/refunds/list">Refund Management</a>
|
<a class="dropdown-item" href="/refunds/list">Refund Management</a>
|
||||||
<a class="dropdown-item" href="/reimbursements/index">Reimbursement Management</a>
|
<a class="dropdown-item" href="/reimbursements/index">Reimbursement Management</a>
|
||||||
</div>
|
</div>
|
||||||
@@ -323,9 +323,9 @@ $role = strtolower(session()->get('role') ?? 'guest');
|
|||||||
<div class="dropdown-menu">
|
<div class="dropdown-menu">
|
||||||
<a class="dropdown-item" href="/expenses/index">Expenses Management</a>
|
<a class="dropdown-item" href="/expenses/index">Expenses Management</a>
|
||||||
<a class="dropdown-item" href="/payment/financial_report">Financial Report</a>
|
<a class="dropdown-item" href="/payment/financial_report">Financial Report</a>
|
||||||
|
<a class="dropdown-item" href="/administrator/tuition-forecast">Tuition Forecast</a>
|
||||||
<a class="dropdown-item" href="/invoice_payment/invoice_management">Invoices Management</a>
|
<a class="dropdown-item" href="/invoice_payment/invoice_management">Invoices Management</a>
|
||||||
<a class="dropdown-item" href="/payment/manual_pay">Manual Payment</a>
|
<a class="dropdown-item" href="/payment/manual_pay">Manual Payment</a>
|
||||||
<a class="dropdown-item" href="/administrator/paypal_transactions">PaypalTransactions</a>
|
|
||||||
<a class="dropdown-item" href="/refunds/list">Refund Management</a>
|
<a class="dropdown-item" href="/refunds/list">Refund Management</a>
|
||||||
<a class="dropdown-item" href="/reimbursements/index">Reimbursement Management</a>
|
<a class="dropdown-item" href="/reimbursements/index">Reimbursement Management</a>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -7,6 +7,8 @@
|
|||||||
<div class="d-flex align-items-center gap-2 my-3 flex-nowrap w-100 overflow-auto" style="white-space: nowrap;">
|
<div class="d-flex align-items-center gap-2 my-3 flex-nowrap w-100 overflow-auto" style="white-space: nowrap;">
|
||||||
<!-- School year filter -->
|
<!-- School year filter -->
|
||||||
<form id="summaryYearFilter" class="d-flex align-items-center gap-2 flex-nowrap me-auto" method="get" action="<?= site_url('financial-report/financialReportSummary') ?>" style="white-space: nowrap;">
|
<form id="summaryYearFilter" class="d-flex align-items-center gap-2 flex-nowrap me-auto" method="get" action="<?= site_url('financial-report/financialReportSummary') ?>" style="white-space: nowrap;">
|
||||||
|
<input type="hidden" name="date_from" value="<?= esc((string)($dateFrom ?? '')) ?>">
|
||||||
|
<input type="hidden" name="date_to" value="<?= esc((string)($dateTo ?? '')) ?>">
|
||||||
<label class="form-label mb-0 me-2">School year</label>
|
<label class="form-label mb-0 me-2">School year</label>
|
||||||
<select name="school_year" class="form-select form-select-sm rounded-pill px-3" style="min-width: 180px;">
|
<select name="school_year" class="form-select form-select-sm rounded-pill px-3" style="min-width: 180px;">
|
||||||
<?php foreach (($schoolYears ?? []) as $sy): ?>
|
<?php foreach (($schoolYears ?? []) as $sy): ?>
|
||||||
@@ -16,7 +18,8 @@
|
|||||||
</form>
|
</form>
|
||||||
<!-- Action buttons -->
|
<!-- Action buttons -->
|
||||||
<div class="d-flex align-items-center gap-2 flex-nowrap flex-shrink-0" style="white-space: nowrap;">
|
<div class="d-flex align-items-center gap-2 flex-nowrap flex-shrink-0" style="white-space: nowrap;">
|
||||||
<a href="<?= base_url('reports/downloadFinancialReport') ?>" class="btn btn-primary">Download PDF</a>
|
<a id="downloadSummaryCsvLink" href="<?= base_url('financial-report/downloadSummaryCsv') ?>" class="btn btn-success">Download CSV</a>
|
||||||
|
<a id="downloadSummaryAllDetailsCsvLink" href="<?= base_url('financial-report/downloadSummaryAllDetailsCsv') ?>" class="btn btn-primary">Download All Details CSV</a>
|
||||||
<a href="<?= base_url('/payment/financial_report') ?>" class="btn btn-secondary">Back To Detailed Report</a>
|
<a href="<?= base_url('/payment/financial_report') ?>" class="btn btn-secondary">Back To Detailed Report</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -31,21 +34,31 @@
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody id="summaryBody">
|
<tbody id="summaryBody">
|
||||||
<tr><td>Total Charges</td><td class="text-right" id="sumCharges">$0.00</td></tr>
|
<tr><td>Tuition Charges</td><td class="text-right" id="sumTuitionCharges">$0.00</td></tr>
|
||||||
<tr><td>Event Fees</td><td class="text-right" id="sumEventFees">$0.00</td></tr>
|
<tr><td>Event Fee Charges</td><td class="text-right" id="sumEventFees">$0.00</td></tr>
|
||||||
<tr><td>Total Extra Charges</td><td class="text-right" id="sumExtraCharges">$0.00</td></tr>
|
<tr><td>Prior-Year Tuition Carryover</td><td class="text-right" id="sumExtraCharges">$0.00</td></tr>
|
||||||
|
<tr><td>Gross Charges</td><td class="text-right" id="sumGrossCharges">$0.00</td></tr>
|
||||||
<tr><td>Total Discounts</td><td class="text-right" id="sumDiscounts">$0.00</td></tr>
|
<tr><td>Total Discounts</td><td class="text-right" id="sumDiscounts">$0.00</td></tr>
|
||||||
<tr><td>Total Refunds</td><td class="text-right" id="sumRefunds">$0.00</td></tr>
|
<tr><td>Total Refunds</td><td class="text-right" id="sumRefunds">$0.00</td></tr>
|
||||||
<tr><td>Total Expenses</td><td class="text-right" id="sumExpenses">$0.00</td></tr>
|
<tr><td>Total Expenses</td><td class="text-right" id="sumExpenses">$0.00</td></tr>
|
||||||
<tr><td>Total Reimbursements</td><td class="text-right" id="sumReimb">$0.00</td></tr>
|
<tr><td>Total Reimbursements</td><td class="text-right" id="sumReimb">$0.00</td></tr>
|
||||||
<tr><td>Donation to School (Masjid & Donation)</td><td class="text-right" id="sumDonationToSchool">$0.00</td></tr>
|
<tr><td>Donation to School (included in expenses)</td><td class="text-right" id="sumDonationToSchool">$0.00</td></tr>
|
||||||
<tr class="table-success"><td>Net Amount (Earned Income)</td><td class="text-right font-weight-bold" id="sumNet">$0.00</td></tr>
|
<tr class="table-success"><td>Net Charges After Discounts/Refunds</td><td class="text-right font-weight-bold" id="sumNet">$0.00</td></tr>
|
||||||
<tr class="table-info"><td>Amount Collected (Paid)</td><td class="text-right font-weight-bold" id="sumCollected">$0.00</td></tr>
|
<tr class="table-info"><td>Amount Collected (Paid)</td><td class="text-right font-weight-bold" id="sumCollected">$0.00</td></tr>
|
||||||
<tr class="table-warning"><td>Amount Unpaid (Outstanding)</td><td class="text-right font-weight-bold" id="sumUnpaid">$0.00</td></tr>
|
<tr><td>Overpayment Credits</td><td class="text-right" id="sumOverpaid">$0.00</td></tr>
|
||||||
|
<tr><td>Gross Outstanding Before Credits</td><td class="text-right" id="sumUnpaid">$0.00</td></tr>
|
||||||
|
<tr class="table-warning"><td>Amount Unpaid (Net of Credits)</td><td class="text-right font-weight-bold" id="sumNetReceivable">$0.00</td></tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<p class="small text-muted mb-3" id="summaryNetFormula"></p>
|
||||||
|
|
||||||
|
<div class="alert alert-light border my-3" id="summaryReconciliationBox">
|
||||||
|
<div class="fw-semibold">Reconciliation</div>
|
||||||
|
<div id="summaryReconciliationText" class="small text-muted"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="my-4">
|
<div class="my-4">
|
||||||
<h3>Summary Graph</h3>
|
<h3>Summary Graph</h3>
|
||||||
<canvas id="summaryChart" style="max-height:300px;"></canvas>
|
<canvas id="summaryChart" style="max-height:300px;"></canvas>
|
||||||
@@ -55,14 +68,14 @@
|
|||||||
<div class="row g-3">
|
<div class="row g-3">
|
||||||
<div class="col-12 col-lg-6">
|
<div class="col-12 col-lg-6">
|
||||||
<div class="h-100 p-3 border rounded">
|
<div class="h-100 p-3 border rounded">
|
||||||
<h3 class="h5">Collected vs Outstanding</h3>
|
<h3 class="h5">Collected vs Net Outstanding</h3>
|
||||||
<canvas id="collectedChart" style="max-height:320px; width:100%;"></canvas>
|
<canvas id="collectedChart" style="max-height:320px; width:100%;"></canvas>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-12 col-lg-6">
|
<div class="col-12 col-lg-6">
|
||||||
<div class="h-100 p-3 border rounded">
|
<div class="h-100 p-3 border rounded">
|
||||||
<h3 class="h5">Expense Breakdown</h3>
|
<h3 class="h5">Expenses out of Net Charges</h3>
|
||||||
<canvas id="expenseChart" style="max-height:320px; width:100%;"></canvas>
|
<canvas id="netExpenseChart" style="max-height:320px; width:100%;"></canvas>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -77,19 +90,118 @@
|
|||||||
|
|
||||||
<script>
|
<script>
|
||||||
function fmt(n){ return '$' + Number(n||0).toFixed(2); }
|
function fmt(n){ return '$' + Number(n||0).toFixed(2); }
|
||||||
|
const initialSummaryData = {
|
||||||
|
schoolYear: <?= json_encode((string)($schoolYear ?? '')) ?>,
|
||||||
|
dateFrom: <?= json_encode((string)($dateFrom ?? '')) ?>,
|
||||||
|
dateTo: <?= json_encode((string)($dateTo ?? '')) ?>,
|
||||||
|
grossCharges: <?= json_encode((float)($grossCharges ?? $totalCharges ?? 0)) ?>,
|
||||||
|
tuitionCharges: <?= json_encode((float)($tuitionCharges ?? 0)) ?>,
|
||||||
|
totalCharges: <?= json_encode((float)($totalCharges ?? 0)) ?>,
|
||||||
|
totalEventFees: <?= json_encode((float)($totalEventFees ?? 0)) ?>,
|
||||||
|
totalExtraCharges: <?= json_encode((float)($totalExtraCharges ?? 0)) ?>,
|
||||||
|
totalDiscounts: <?= json_encode((float)($totalDiscounts ?? 0)) ?>,
|
||||||
|
totalRefunds: <?= json_encode((float)($totalRefunds ?? 0)) ?>,
|
||||||
|
totalExpenses: <?= json_encode((float)($totalExpenses ?? 0)) ?>,
|
||||||
|
totalReimbursements: <?= json_encode((float)($totalReimbursements ?? 0)) ?>,
|
||||||
|
donationToSchool: <?= json_encode((float)($donationToSchool ?? 0)) ?>,
|
||||||
|
totalPaid: <?= json_encode((float)($totalPaid ?? 0)) ?>,
|
||||||
|
amountCollected: <?= json_encode((float)($amountCollected ?? 0)) ?>,
|
||||||
|
totalUnpaid: <?= json_encode((float)($totalUnpaid ?? 0)) ?>,
|
||||||
|
totalOverpaid: <?= json_encode((float)($totalOverpaid ?? 0)) ?>,
|
||||||
|
overpaymentDetails: <?= json_encode($overpaymentDetails ?? []) ?>,
|
||||||
|
netReceivable: <?= json_encode((float)($netReceivable ?? 0)) ?>,
|
||||||
|
netAmount: <?= json_encode((float)($netAmount ?? 0)) ?>
|
||||||
|
};
|
||||||
|
|
||||||
|
function buildSummaryPeriod(d) {
|
||||||
|
const parts = ['Report for School Year: ' + (d.schoolYear || '')];
|
||||||
|
if (d.dateFrom) parts.push('Date From: ' + d.dateFrom);
|
||||||
|
if (d.dateTo) parts.push('Date To: ' + d.dateTo);
|
||||||
|
return parts.join(' | ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildReconciliationText(d) {
|
||||||
|
const collected = Number(d.amountCollected || d.totalPaid || 0);
|
||||||
|
const unpaid = Number(d.totalUnpaid || 0);
|
||||||
|
const overpaid = Number(d.totalOverpaid || 0);
|
||||||
|
const net = Number(d.netAmount || 0);
|
||||||
|
return fmt(collected) + ' + ' + fmt(unpaid) + ' - ' + fmt(overpaid) + ' = ' + fmt(net)
|
||||||
|
+ ' (Collected + Gross Outstanding - Overpayment Credits = Net Charges After Discounts/Refunds)';
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildNetFormulaText(d) {
|
||||||
|
const gross = Number(d.grossCharges || d.totalCharges || 0);
|
||||||
|
const discounts = Number(d.totalDiscounts || 0);
|
||||||
|
const refunds = Number(d.totalRefunds || 0);
|
||||||
|
const net = Number(d.netAmount || 0);
|
||||||
|
return 'Net Charges After Discounts/Refunds = Gross Charges - Total Discounts - Total Refunds = '
|
||||||
|
+ fmt(gross) + ' - ' + fmt(discounts) + ' - ' + fmt(refunds) + ' = ' + fmt(net);
|
||||||
|
}
|
||||||
|
|
||||||
|
function applySummaryData(d) {
|
||||||
|
document.getElementById('summaryPeriod').textContent = buildSummaryPeriod(d);
|
||||||
|
document.getElementById('sumTuitionCharges').textContent = fmt(d.tuitionCharges || 0);
|
||||||
|
if (document.getElementById('sumEventFees')) {
|
||||||
|
document.getElementById('sumEventFees').textContent = fmt(d.totalEventFees || 0);
|
||||||
|
}
|
||||||
|
if (document.getElementById('sumExtraCharges')) {
|
||||||
|
document.getElementById('sumExtraCharges').textContent = fmt(d.totalExtraCharges || 0);
|
||||||
|
}
|
||||||
|
document.getElementById('sumGrossCharges').textContent = fmt(d.grossCharges || d.totalCharges || 0);
|
||||||
|
document.getElementById('sumDiscounts').textContent = fmt(d.totalDiscounts);
|
||||||
|
document.getElementById('sumRefunds').textContent = fmt(d.totalRefunds);
|
||||||
|
document.getElementById('sumExpenses').textContent = fmt(d.totalExpenses);
|
||||||
|
document.getElementById('sumReimb').textContent = fmt(d.totalReimbursements);
|
||||||
|
if (document.getElementById('sumDonationToSchool')) {
|
||||||
|
document.getElementById('sumDonationToSchool').textContent = fmt(d.donationToSchool);
|
||||||
|
}
|
||||||
|
document.getElementById('sumNet').textContent = fmt(d.netAmount);
|
||||||
|
document.getElementById('sumCollected').textContent = fmt(d.amountCollected || d.totalPaid || 0);
|
||||||
|
document.getElementById('sumOverpaid').textContent = fmt(d.totalOverpaid || 0);
|
||||||
|
document.getElementById('sumUnpaid').textContent = fmt(d.totalUnpaid);
|
||||||
|
document.getElementById('sumNetReceivable').textContent = fmt(d.netReceivable || 0);
|
||||||
|
document.getElementById('summaryNetFormula').textContent = buildNetFormulaText(d);
|
||||||
|
document.getElementById('summaryReconciliationText').textContent = buildReconciliationText(d);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildSummaryParams() {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
const form = document.getElementById('summaryYearFilter');
|
||||||
|
if (form) {
|
||||||
|
new FormData(form).forEach((value, key) => {
|
||||||
|
params.set(key, value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateSummaryActionLinks() {
|
||||||
|
const params = buildSummaryParams().toString();
|
||||||
|
const summaryHref = '<?= base_url('financial-report/downloadSummaryCsv') ?>' + (params ? ('?' + params) : '');
|
||||||
|
const allDetailsHref = '<?= base_url('financial-report/downloadSummaryAllDetailsCsv') ?>' + (params ? ('?' + params) : '');
|
||||||
|
const summaryLink = document.getElementById('downloadSummaryCsvLink');
|
||||||
|
const allDetailsLink = document.getElementById('downloadSummaryAllDetailsCsvLink');
|
||||||
|
if (summaryLink) summaryLink.href = summaryHref;
|
||||||
|
if (allDetailsLink) allDetailsLink.href = allDetailsHref;
|
||||||
|
}
|
||||||
|
|
||||||
// Auto-submit school year on change and hydrate via API
|
// Auto-submit school year on change and hydrate via API
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
const sel = document.querySelector('#summaryYearFilter select[name="school_year"]');
|
const sel = document.querySelector('#summaryYearFilter select[name="school_year"]');
|
||||||
if (sel) sel.addEventListener('change', function(){ loadSummary(); });
|
if (sel) sel.addEventListener('change', function(){
|
||||||
|
updateSummaryActionLinks();
|
||||||
|
loadSummary();
|
||||||
|
});
|
||||||
|
applySummaryData(initialSummaryData);
|
||||||
|
updateSummaryActionLinks();
|
||||||
|
renderCharts(initialSummaryData);
|
||||||
loadSummary();
|
loadSummary();
|
||||||
});
|
});
|
||||||
|
|
||||||
let __sumSeq = 0;
|
let __sumSeq = 0;
|
||||||
function loadSummary(){
|
function loadSummary(){
|
||||||
const mySeq = ++__sumSeq;
|
const mySeq = ++__sumSeq;
|
||||||
const sel = document.querySelector('#summaryYearFilter select[name="school_year"]');
|
const params = buildSummaryParams();
|
||||||
const params = new URLSearchParams();
|
|
||||||
if (sel && sel.value) params.append('school_year', sel.value);
|
|
||||||
const baseUrl = '<?= site_url('financial-report/financialReportSummary') ?>';
|
const baseUrl = '<?= site_url('financial-report/financialReportSummary') ?>';
|
||||||
const url = baseUrl + (params.toString() ? ('?' + params.toString() + '&format=json') : '?format=json');
|
const url = baseUrl + (params.toString() ? ('?' + params.toString() + '&format=json') : '?format=json');
|
||||||
fetch(url, { headers: { 'Accept': 'application/json' }})
|
fetch(url, { headers: { 'Accept': 'application/json' }})
|
||||||
@@ -97,26 +209,7 @@ function loadSummary(){
|
|||||||
.then(d => {
|
.then(d => {
|
||||||
if (mySeq !== __sumSeq) return; // stale response
|
if (mySeq !== __sumSeq) return; // stale response
|
||||||
if (!d || d.ok !== true) return;
|
if (!d || d.ok !== true) return;
|
||||||
document.getElementById('summaryPeriod').textContent = 'Report for School Year: ' + (d.schoolYear||'');
|
applySummaryData(d);
|
||||||
document.getElementById('sumCharges').textContent = fmt(d.totalCharges);
|
|
||||||
if (document.getElementById('sumEventFees')) {
|
|
||||||
document.getElementById('sumEventFees').textContent = fmt(d.totalEventFees || 0);
|
|
||||||
}
|
|
||||||
if (document.getElementById('sumExtraCharges')) {
|
|
||||||
document.getElementById('sumExtraCharges').textContent = fmt(d.totalExtraCharges || 0);
|
|
||||||
}
|
|
||||||
document.getElementById('sumDiscounts').textContent = fmt(d.totalDiscounts);
|
|
||||||
document.getElementById('sumRefunds').textContent = fmt(d.totalRefunds);
|
|
||||||
document.getElementById('sumExpenses').textContent = fmt(d.totalExpenses);
|
|
||||||
document.getElementById('sumReimb').textContent = fmt(d.totalReimbursements);
|
|
||||||
if (document.getElementById('sumDonationToSchool')) {
|
|
||||||
document.getElementById('sumDonationToSchool').textContent = fmt(d.donationToSchool);
|
|
||||||
}
|
|
||||||
document.getElementById('sumNet').textContent = fmt(d.netAmount);
|
|
||||||
document.getElementById('sumCollected').textContent = fmt(d.amountCollected);
|
|
||||||
document.getElementById('sumUnpaid').textContent = fmt(d.totalUnpaid);
|
|
||||||
|
|
||||||
// Refresh charts with new data
|
|
||||||
renderCharts(d);
|
renderCharts(d);
|
||||||
})
|
})
|
||||||
.catch(()=>{});
|
.catch(()=>{});
|
||||||
@@ -127,14 +220,40 @@ function renderCharts(d){
|
|||||||
// Destroy existing if present
|
// Destroy existing if present
|
||||||
if (window._summaryChart) { window._summaryChart.destroy(); }
|
if (window._summaryChart) { window._summaryChart.destroy(); }
|
||||||
if (window._collectedChart) { window._collectedChart.destroy(); }
|
if (window._collectedChart) { window._collectedChart.destroy(); }
|
||||||
if (window._expenseChart) { window._expenseChart.destroy(); }
|
if (window._netExpenseChart) { window._netExpenseChart.destroy(); }
|
||||||
|
const chartColors = {
|
||||||
|
tuition: '#1f77b4',
|
||||||
|
eventFees: '#ff7f0e',
|
||||||
|
carryover: '#2ca02c',
|
||||||
|
grossCharges: '#d62728',
|
||||||
|
discounts: '#9467bd',
|
||||||
|
expenses: '#20c997',
|
||||||
|
netCharges: '#e377c2',
|
||||||
|
collected: '#28a745',
|
||||||
|
overpaymentCredits: '#dc3545',
|
||||||
|
outstanding: '#ffc107',
|
||||||
|
netReceivable: '#f4a261'
|
||||||
|
};
|
||||||
const summaryCtx = document.getElementById('summaryChart').getContext('2d');
|
const summaryCtx = document.getElementById('summaryChart').getContext('2d');
|
||||||
|
const summaryBarColors = [
|
||||||
|
chartColors.tuition,
|
||||||
|
chartColors.eventFees,
|
||||||
|
chartColors.carryover,
|
||||||
|
chartColors.grossCharges,
|
||||||
|
chartColors.discounts,
|
||||||
|
chartColors.expenses,
|
||||||
|
chartColors.netCharges,
|
||||||
|
chartColors.collected,
|
||||||
|
chartColors.overpaymentCredits,
|
||||||
|
chartColors.outstanding,
|
||||||
|
chartColors.netReceivable
|
||||||
|
];
|
||||||
window._summaryChart = new Chart(summaryCtx, {
|
window._summaryChart = new Chart(summaryCtx, {
|
||||||
type: 'bar',
|
type: 'bar',
|
||||||
data: { labels: ['Charges','Event Fees','Paid','Unpaid','Discounts','Refunds','Expenses','Reimbursements','Net'],
|
data: { labels: ['Tuition','Event Fees','Prior-Year Carryover','Gross Charges','Discounts','Expenses','Net Charges','Collected','Overpayment Credits','Outstanding','Net Receivable'],
|
||||||
datasets: [{ label:'Amount (USD)', data:[
|
datasets: [{ label:'Amount (USD)', data:[
|
||||||
d.totalCharges||0, d.totalEventFees||0, d.totalPaid||0, d.totalUnpaid||0, d.totalDiscounts||0, d.totalRefunds||0, d.totalExpenses||0, d.totalReimbursements||0, d.netAmount||0
|
d.tuitionCharges||0, d.totalEventFees||0, d.totalExtraCharges||0, d.grossCharges||d.totalCharges||0, d.totalDiscounts||0, d.totalExpenses||0, d.netAmount||0, d.amountCollected||d.totalPaid||0, d.totalOverpaid||0, d.totalUnpaid||0, d.netReceivable||0
|
||||||
], backgroundColor: ['#007bff','#6610f2','#28a745','#ffc107','#17a2b8','#ffc107','#dc3545','#6f42c1','#20c997']}] },
|
], backgroundColor: summaryBarColors}] },
|
||||||
options: { responsive:true, scales:{ y:{ beginAtZero:true }}}
|
options: { responsive:true, scales:{ y:{ beginAtZero:true }}}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -142,21 +261,54 @@ function renderCharts(d){
|
|||||||
window._collectedChart = new Chart(collectedCtx, {
|
window._collectedChart = new Chart(collectedCtx, {
|
||||||
type: 'pie',
|
type: 'pie',
|
||||||
data: {
|
data: {
|
||||||
labels: ['Amount Collected (Paid)', 'Amount Outstanding (Unpaid)'],
|
labels: ['Amount Collected (Paid)', 'Amount Unpaid (Net of Credits)', 'Overpayment Credits'],
|
||||||
datasets: [{
|
datasets: [{
|
||||||
data: [ d.amountCollected || d.totalPaid || 0, d.totalUnpaid || 0 ],
|
data: [ d.amountCollected || d.totalPaid || 0, d.netReceivable || 0, d.totalOverpaid || 0 ],
|
||||||
backgroundColor: ['#28a745', '#ffc107'],
|
backgroundColor: [chartColors.collected, chartColors.outstanding, chartColors.overpaymentCredits],
|
||||||
borderWidth: 1
|
borderWidth: 1
|
||||||
}]
|
}]
|
||||||
},
|
},
|
||||||
options: { responsive:true, plugins:{ legend:{ position:'bottom' } } }
|
options: { responsive:true, plugins:{ legend:{ position:'bottom' } } }
|
||||||
});
|
});
|
||||||
|
|
||||||
const expenseCtx = document.getElementById('expenseChart').getContext('2d');
|
const netExpenseCtx = document.getElementById('netExpenseChart').getContext('2d');
|
||||||
window._expenseChart = new Chart(expenseCtx, {
|
const netAmount = Number(d.netAmount || 0);
|
||||||
|
const totalExpenses = Number(d.totalExpenses || 0);
|
||||||
|
const expensePortion = Math.max(0, Math.min(totalExpenses, netAmount));
|
||||||
|
const remainingNet = Math.max(0, netAmount - expensePortion);
|
||||||
|
const expensePercent = netAmount > 0 ? ((totalExpenses / netAmount) * 100).toFixed(1) : '0.0';
|
||||||
|
const remainingPercent = netAmount > 0 ? ((remainingNet / netAmount) * 100).toFixed(1) : '0.0';
|
||||||
|
const netExpenseValues = [expensePortion, remainingNet];
|
||||||
|
const netExpenseLabels = [
|
||||||
|
'Expenses (' + expensePercent + '%)',
|
||||||
|
'Remaining Net (' + remainingPercent + '%)'
|
||||||
|
];
|
||||||
|
window._netExpenseChart = new Chart(netExpenseCtx, {
|
||||||
type: 'pie',
|
type: 'pie',
|
||||||
data: { labels: ['Expenses','Reimbursements'], datasets: [{ data:[ d.totalExpenses||0, d.totalReimbursements||0 ], backgroundColor: ['#dc3545','#6f42c1']}]},
|
data: {
|
||||||
options: { responsive:true }
|
labels: netExpenseLabels,
|
||||||
|
datasets: [{
|
||||||
|
data: netExpenseValues,
|
||||||
|
backgroundColor: [chartColors.expenses, chartColors.netCharges],
|
||||||
|
borderWidth: 1
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
responsive: true,
|
||||||
|
plugins: {
|
||||||
|
legend: { position: 'bottom' },
|
||||||
|
tooltip: {
|
||||||
|
callbacks: {
|
||||||
|
label: function(context) {
|
||||||
|
if (context.dataIndex === 0) {
|
||||||
|
return 'Expenses: ' + fmt(totalExpenses) + ' (' + expensePercent + '% of net charges)';
|
||||||
|
}
|
||||||
|
return 'Remaining Net: ' + fmt(remainingNet) + ' (' + remainingPercent + '%)';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
@@ -174,82 +326,4 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
<script>
|
|
||||||
document.addEventListener("DOMContentLoaded", function() {
|
|
||||||
// Bar chart summary
|
|
||||||
const summaryCtx = document.getElementById('summaryChart').getContext('2d');
|
|
||||||
window._summaryChart = new Chart(summaryCtx, {
|
|
||||||
type: 'bar',
|
|
||||||
data: {
|
|
||||||
labels: ['Charges', 'Event Fees', 'Paid', 'Unpaid', 'Discounts', 'Refunds', 'Expenses', 'Reimbursements', 'Net'],
|
|
||||||
datasets: [{
|
|
||||||
label: 'Amount (USD)',
|
|
||||||
data: [
|
|
||||||
<?= (float)$totalCharges ?>,
|
|
||||||
<?= (float)($totalEventFees ?? 0) ?>,
|
|
||||||
<?= (float)$totalPaid ?>,
|
|
||||||
<?= (float)$totalUnpaid ?>,
|
|
||||||
<?= (float)$totalDiscounts ?>,
|
|
||||||
<?= (float)$totalRefunds ?>,
|
|
||||||
<?= (float)$totalExpenses ?>,
|
|
||||||
<?= (float)$totalReimbursements ?>,
|
|
||||||
<?= (float)$netAmount ?>
|
|
||||||
],
|
|
||||||
backgroundColor: [
|
|
||||||
'#007bff', '#6610f2', '#28a745', '#ffc107', '#17a2b8', '#ffc107', '#dc3545', '#6f42c1', '#20c997'
|
|
||||||
]
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
scales: {
|
|
||||||
y: {
|
|
||||||
beginAtZero: true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Collected vs Outstanding pie
|
|
||||||
const collectedCtx = document.getElementById('collectedChart').getContext('2d');
|
|
||||||
window._collectedChart = new Chart(collectedCtx, {
|
|
||||||
type: 'pie',
|
|
||||||
data: {
|
|
||||||
labels: ['Amount Collected (Paid)', 'Amount Outstanding (Unpaid)'],
|
|
||||||
datasets: [{
|
|
||||||
data: [
|
|
||||||
<?= (float)$amountCollected ?>,
|
|
||||||
<?= (float)$totalUnpaid ?>
|
|
||||||
],
|
|
||||||
backgroundColor: ['#28a745', '#ffc107']
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true,
|
|
||||||
plugins: { legend: { position: 'bottom' } }
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Pie chart expenses
|
|
||||||
const expenseCtx = document.getElementById('expenseChart').getContext('2d');
|
|
||||||
window._expenseChart = new Chart(expenseCtx, {
|
|
||||||
type: 'pie',
|
|
||||||
data: {
|
|
||||||
labels: ['Expenses', 'Reimbursements'],
|
|
||||||
datasets: [{
|
|
||||||
data: [
|
|
||||||
<?= (float)$totalExpenses ?>,
|
|
||||||
<?= (float)$totalReimbursements ?>
|
|
||||||
],
|
|
||||||
backgroundColor: ['#dc3545', '#6f42c1']
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
options: {
|
|
||||||
responsive: true
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
|
|
||||||
<?= $this->endSection() ?>
|
<?= $this->endSection() ?>
|
||||||
|
|||||||
@@ -260,7 +260,7 @@
|
|||||||
<td>
|
<td>
|
||||||
<?php if (!empty($payment['check_file'])): ?>
|
<?php if (!empty($payment['check_file'])): ?>
|
||||||
<a href="#" data-bs-toggle="modal" data-bs-target="#checkModal<?= (int)$payment['id'] ?>">View</a> /
|
<a href="#" data-bs-toggle="modal" data-bs-target="#checkModal<?= (int)$payment['id'] ?>">View</a> /
|
||||||
<a href="<?= base_url('payment/serveCheckFile/' . esc($payment['check_file']) . '/download') ?>">Download</a>
|
<a href="<?= base_url('payment/file/' . (int) $payment['id'] . '/download') ?>">Download</a>
|
||||||
|
|
||||||
<!-- File Preview Modal -->
|
<!-- File Preview Modal -->
|
||||||
<div class="modal fade" id="checkModal<?= (int)$payment['id'] ?>" tabindex="-1" aria-hidden="true">
|
<div class="modal fade" id="checkModal<?= (int)$payment['id'] ?>" tabindex="-1" aria-hidden="true">
|
||||||
@@ -271,7 +271,7 @@
|
|||||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-body text-center">
|
<div class="modal-body text-center">
|
||||||
<iframe src="<?= base_url('payment/serveCheckFile/' . esc($payment['check_file']) . '/inline') ?>" width="100%" height="600" style="border:none;"></iframe>
|
<iframe src="<?= base_url('payment/file/' . (int) $payment['id'] . '/inline') ?>" width="100%" height="600" style="border:none;"></iframe>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -91,10 +91,9 @@
|
|||||||
<td><?= esc($payment['status']) ?></td>
|
<td><?= esc($payment['status']) ?></td>
|
||||||
<td>
|
<td>
|
||||||
<?php if (!empty($payment['check_file'])): ?>
|
<?php if (!empty($payment['check_file'])): ?>
|
||||||
<?php $file = rawurlencode((string)$payment['check_file']); ?>
|
|
||||||
<!-- Trigger Modal -->
|
<!-- Trigger Modal -->
|
||||||
<a href="#" data-bs-toggle="modal" data-bs-target="#checkModal<?= (int)$payment['id'] ?>">View</a> /
|
<a href="#" data-bs-toggle="modal" data-bs-target="#checkModal<?= (int)$payment['id'] ?>">View</a> /
|
||||||
<a href="<?= base_url('payment/serveCheckFile/' . $file . '/download') ?>">Download</a>
|
<a href="<?= base_url('payment/file/' . (int) $payment['id'] . '/download') ?>">Download</a>
|
||||||
|
|
||||||
<!-- Modal -->
|
<!-- Modal -->
|
||||||
<div class="modal fade" id="checkModal<?= (int)$payment['id'] ?>" tabindex="-1" aria-hidden="true">
|
<div class="modal fade" id="checkModal<?= (int)$payment['id'] ?>" tabindex="-1" aria-hidden="true">
|
||||||
@@ -105,7 +104,7 @@
|
|||||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-body text-center">
|
<div class="modal-body text-center">
|
||||||
<iframe src="<?= base_url('payment/serveCheckFile/' . $file . '/inline') ?>"
|
<iframe src="<?= base_url('payment/file/' . (int) $payment['id'] . '/inline') ?>"
|
||||||
width="100%" height="600px" style="border:none;"></iframe>
|
width="100%" height="600px" style="border:none;"></iframe>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,81 +0,0 @@
|
|||||||
<!-- This snippet supports rendering separate standalone buttons
|
|
||||||
in different parts of your page with unique payment methods.
|
|
||||||
Test EMAIL: sb-cbmre43313068@business.example.com
|
|
||||||
Test PASSWORD: 9JC?].qM
|
|
||||||
-->
|
|
||||||
|
|
||||||
<?= $this->extend('layout/register_layout') ?>
|
|
||||||
<?= $this->section('content') ?>
|
|
||||||
|
|
||||||
<div class="container d-flex justify-content-center align-items-start" style="min-height: 100vh; padding-top: 80px;">
|
|
||||||
<div class="registration-form text-center p-4 rounded-4 shadow"
|
|
||||||
style="background-color: white; max-width: 600px; width: 300%;">
|
|
||||||
|
|
||||||
<!-- Logo -->
|
|
||||||
<div class="mb-4">
|
|
||||||
<a href="<?= base_url('/parent_dashboard') ?>">
|
|
||||||
<img src="<?= base_url('assets/images/alrahma_logo.png') ?>" alt="Alrahma Logo"
|
|
||||||
style="width: 120px; height: 120px; border-radius: 50%; object-fit: cover;">
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Page Title -->
|
|
||||||
<h3 class="text-success" style="font-family: Arial, sans-serif;">Payment</h3>
|
|
||||||
<br>
|
|
||||||
|
|
||||||
<!-- PayPal Button -->
|
|
||||||
<div class="d-flex justify-content-center">
|
|
||||||
<div id="paypal-button-container"></div>
|
|
||||||
</div>
|
|
||||||
<p class="text-success">
|
|
||||||
<br><strong>Your payment information, including credit card and bank account details, is securely stored only by PayPal and Venmo. </strong>
|
|
||||||
</p>
|
|
||||||
<p class="text-danger">
|
|
||||||
We do not collect or save any financial data on our website.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<?= $this->endSection() ?>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<?= $this->section('scripts') ?>
|
|
||||||
<script src="https://www.paypal.com/sdk/js?client-id=AYsiOekZUvrjgx9C5c554ZeSQ4W6yd0ZX-OHE93_D0fWoa4YXrMmroEeLiAjjdCKkELH8EVZR_yGMLPS¤cy=USD&components=buttons,funding-eligibility&enable-funding=venmo&disable-funding=card,paylater">
|
|
||||||
</script>
|
|
||||||
<script>
|
|
||||||
const parentName = <?= json_encode($parentName) ?>;
|
|
||||||
const totalAmount = <?= json_encode(number_format($totalAmount, 2, '.', '')) ?>;
|
|
||||||
const schoolId = <?= json_encode($schoolId) ?>;
|
|
||||||
|
|
||||||
paypal.Buttons({
|
|
||||||
style: {
|
|
||||||
layout: 'vertical',
|
|
||||||
color: 'blue',
|
|
||||||
shape: 'rect',
|
|
||||||
label: 'paypal'
|
|
||||||
},
|
|
||||||
createOrder: function(data, actions) {
|
|
||||||
return actions.order.create({
|
|
||||||
purchase_units: [{
|
|
||||||
amount: {
|
|
||||||
value: totalAmount
|
|
||||||
},
|
|
||||||
custom_id: `${schoolId}`,
|
|
||||||
description: `Payment by ${parentName}`
|
|
||||||
}]
|
|
||||||
});
|
|
||||||
},
|
|
||||||
|
|
||||||
onApprove: function(data, actions) {
|
|
||||||
return actions.order.capture().then(function(details) {
|
|
||||||
alert('Transaction completed by ' + details.payer.name.given_name + ' for <?= esc($parentName) ?>');
|
|
||||||
});
|
|
||||||
},
|
|
||||||
onError: function(err) {
|
|
||||||
console.error('An error occurred during the transaction', err);
|
|
||||||
}
|
|
||||||
}).render('#paypal-button-container');
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<?= $this->endSection() ?>
|
|
||||||
@@ -113,7 +113,7 @@
|
|||||||
<td><?= esc($r['check_nbr'] ?? '-') ?></td>
|
<td><?= esc($r['check_nbr'] ?? '-') ?></td>
|
||||||
<td>
|
<td>
|
||||||
<?php if (!empty($r['check_file'])): ?>
|
<?php if (!empty($r['check_file'])): ?>
|
||||||
<a href="<?= base_url('uploads/checks/' . $r['check_file']) ?>" target="_blank">View</a>
|
<a href="<?= base_url('refunds/file/' . (int) $r['id'] . '/inline') ?>" target="_blank">View</a>
|
||||||
<?php else: ?>
|
<?php else: ?>
|
||||||
-
|
-
|
||||||
<?php endif; ?>
|
<?php endif; ?>
|
||||||
@@ -200,7 +200,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="checkFile" class="form-label">Upload Check Image</label>
|
<label for="checkFile" class="form-label">Upload Check Image</label>
|
||||||
<input type="file" class="form-control" name="check_file" id="checkFile" accept="image/*">
|
<input type="file" class="form-control" name="check_file" id="checkFile" accept=".jpg,.jpeg,.png,.pdf">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -373,8 +373,94 @@
|
|||||||
let tempBatchCounter = -1;
|
let tempBatchCounter = -1;
|
||||||
|
|
||||||
let csrfValue = cfg.csrfHash || '';
|
let csrfValue = cfg.csrfHash || '';
|
||||||
|
const csrfCookieName = <?= json_encode(config('Security')->csrfCookieName ?? (config('Security')->cookieName ?? 'csrf_cookie_name')) ?>;
|
||||||
|
let csrfRequestQueue = Promise.resolve();
|
||||||
let dragPayload = null;
|
let dragPayload = null;
|
||||||
|
|
||||||
|
function getCookie(name) {
|
||||||
|
const parts = document.cookie.split(';');
|
||||||
|
for (let i = 0; i < parts.length; i += 1) {
|
||||||
|
const part = parts[i].trim();
|
||||||
|
if (part.startsWith(`${name}=`)) {
|
||||||
|
return decodeURIComponent(part.slice(name.length + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncCsrfFromCookie() {
|
||||||
|
if (!csrfCookieName) {
|
||||||
|
return csrfValue;
|
||||||
|
}
|
||||||
|
const cookieValue = getCookie(csrfCookieName);
|
||||||
|
if (cookieValue) {
|
||||||
|
csrfValue = cookieValue;
|
||||||
|
}
|
||||||
|
return csrfValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateCsrfToken(response, data = null) {
|
||||||
|
const headerValue = response?.headers?.get?.('X-CSRF-HASH') || '';
|
||||||
|
if (headerValue) {
|
||||||
|
csrfValue = headerValue;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const bodyValue = data && typeof data === 'object' ? (data.csrf_hash || data.csrfHash || '') : '';
|
||||||
|
if (bodyValue) {
|
||||||
|
csrfValue = bodyValue;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
syncCsrfFromCookie();
|
||||||
|
}
|
||||||
|
|
||||||
|
function withSerializedCsrfRequest(task) {
|
||||||
|
const run = csrfRequestQueue
|
||||||
|
.catch(() => undefined)
|
||||||
|
.then(() => task());
|
||||||
|
csrfRequestQueue = run.then(() => undefined, () => undefined);
|
||||||
|
return run;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postJson(url, form, fallbackError) {
|
||||||
|
return withSerializedCsrfRequest(async () => {
|
||||||
|
syncCsrfFromCookie();
|
||||||
|
if (cfg.csrfToken) {
|
||||||
|
form.set(cfg.csrfToken, csrfValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = { 'X-Requested-With': 'XMLHttpRequest' };
|
||||||
|
if (csrfValue) {
|
||||||
|
headers['X-CSRF-TOKEN'] = csrfValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
credentials: 'same-origin',
|
||||||
|
body: form,
|
||||||
|
});
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
let data = null;
|
||||||
|
try {
|
||||||
|
data = text ? JSON.parse(text) : {};
|
||||||
|
} catch (_) {
|
||||||
|
data = {
|
||||||
|
success: false,
|
||||||
|
error: text || fallbackError || 'Unexpected response',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
updateCsrfToken(response, data);
|
||||||
|
|
||||||
|
if (!response.ok || !data.success) {
|
||||||
|
throw new Error(data.error || fallbackError || 'Request failed.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function openReceiptModal(url) {
|
function openReceiptModal(url) {
|
||||||
if (!url) {
|
if (!url) {
|
||||||
return;
|
return;
|
||||||
@@ -470,23 +556,8 @@
|
|||||||
}
|
}
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
form.append('expense_id', itemId);
|
form.append('expense_id', itemId);
|
||||||
if (cfg.csrfToken) {
|
|
||||||
form.append(cfg.csrfToken, csrfValue);
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(cfg.markDonationUrl, {
|
await postJson(cfg.markDonationUrl, form, 'Unable to mark donation right now.');
|
||||||
method: 'POST',
|
|
||||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
|
||||||
body: form,
|
|
||||||
});
|
|
||||||
const data = await response.json().catch(() => ({ success: false, error: 'Unexpected response' }));
|
|
||||||
const newHash = response.headers.get('X-CSRF-HASH') || data.csrf_hash;
|
|
||||||
if (newHash) {
|
|
||||||
csrfValue = newHash;
|
|
||||||
}
|
|
||||||
if (!response.ok || !data.success) {
|
|
||||||
throw new Error(data.error || 'Unable to mark donation right now.');
|
|
||||||
}
|
|
||||||
removeItemFromUI(itemId);
|
removeItemFromUI(itemId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
@@ -737,23 +808,7 @@
|
|||||||
} else {
|
} else {
|
||||||
form.append('admin_id', '');
|
form.append('admin_id', '');
|
||||||
}
|
}
|
||||||
if (cfg.csrfToken) {
|
postJson(cfg.updateUrl, form, 'Unable to update batch assignment.').then((data) => {
|
||||||
form.append(cfg.csrfToken, csrfValue);
|
|
||||||
}
|
|
||||||
|
|
||||||
fetch(cfg.updateUrl, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
|
||||||
body: form,
|
|
||||||
}).then(async (response) => {
|
|
||||||
const data = await response.json().catch(() => ({ success: false, error: 'Unexpected response' }));
|
|
||||||
const newHash = response.headers.get('X-CSRF-HASH') || data.csrf_hash;
|
|
||||||
if (newHash) {
|
|
||||||
csrfValue = newHash;
|
|
||||||
}
|
|
||||||
if (!response.ok || !data.success) {
|
|
||||||
throw new Error(data.error || 'Unable to update batch assignment.');
|
|
||||||
}
|
|
||||||
entry.batch_number = batchId;
|
entry.batch_number = batchId;
|
||||||
entry.batchId = batchId;
|
entry.batchId = batchId;
|
||||||
entry.admin_id = (adminId || adminId === 0) ? adminId : null;
|
entry.admin_id = (adminId || adminId === 0) ? adminId : null;
|
||||||
@@ -791,25 +846,7 @@
|
|||||||
throw new Error('Batch creation endpoint is not configured.');
|
throw new Error('Batch creation endpoint is not configured.');
|
||||||
}
|
}
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
if (cfg.csrfToken) {
|
return postJson(cfg.createBatchUrl, form, 'Unable to create a new batch right now.');
|
||||||
form.append(cfg.csrfToken, csrfValue);
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch(cfg.createBatchUrl, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
|
||||||
body: form,
|
|
||||||
});
|
|
||||||
const data = await response.json().catch(() => ({ success: false, error: 'Unexpected response when creating batch.' }));
|
|
||||||
const newHash = response.headers.get('X-CSRF-HASH') || data.csrf_hash;
|
|
||||||
if (newHash) {
|
|
||||||
csrfValue = newHash;
|
|
||||||
}
|
|
||||||
if (!response.ok || !data.success) {
|
|
||||||
throw new Error(data.error || 'Unable to create a new batch right now.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function uploadAdminCheckFile(batchId, adminId, input, statusEl, linkEl) {
|
async function uploadAdminCheckFile(batchId, adminId, input, statusEl, linkEl) {
|
||||||
@@ -827,28 +864,13 @@
|
|||||||
form.append('batch_id', batchId);
|
form.append('batch_id', batchId);
|
||||||
form.append('admin_id', adminId ?? 0);
|
form.append('admin_id', adminId ?? 0);
|
||||||
form.append('check_file', file);
|
form.append('check_file', file);
|
||||||
if (cfg.csrfToken) {
|
|
||||||
form.append(cfg.csrfToken, csrfValue);
|
|
||||||
}
|
|
||||||
|
|
||||||
input.disabled = true;
|
input.disabled = true;
|
||||||
const previous = statusEl.textContent;
|
const previous = statusEl.textContent;
|
||||||
statusEl.textContent = 'Uploading...';
|
statusEl.textContent = 'Uploading...';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(cfg.checkUploadUrl, {
|
const data = await postJson(cfg.checkUploadUrl, form, 'Unable to upload check file right now.');
|
||||||
method: 'POST',
|
|
||||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
|
||||||
body: form,
|
|
||||||
});
|
|
||||||
const data = await response.json().catch(() => ({ success: false, error: 'Unexpected response' }));
|
|
||||||
const newHash = response.headers.get('X-CSRF-HASH') || data.csrf_hash;
|
|
||||||
if (newHash) {
|
|
||||||
csrfValue = newHash;
|
|
||||||
}
|
|
||||||
if (!response.ok || !data.success) {
|
|
||||||
throw new Error(data.error || 'Unable to upload check file right now.');
|
|
||||||
}
|
|
||||||
const label = data.original_filename || 'View check';
|
const label = data.original_filename || 'View check';
|
||||||
statusEl.textContent = `Uploaded: ${data.original_filename || 'file'}`;
|
statusEl.textContent = `Uploaded: ${data.original_filename || 'file'}`;
|
||||||
if (linkEl && data.url) {
|
if (linkEl && data.url) {
|
||||||
@@ -979,34 +1001,19 @@
|
|||||||
}
|
}
|
||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
form.append('batch_id', batchId);
|
form.append('batch_id', batchId);
|
||||||
if (cfg.csrfToken) {
|
|
||||||
form.append(cfg.csrfToken, csrfValue);
|
|
||||||
}
|
|
||||||
if (button) {
|
if (button) {
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
button.textContent = 'Locking...';
|
button.textContent = 'Locking...';
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const response = await fetch(cfg.lockBatchUrl, {
|
await postJson(cfg.lockBatchUrl, form, 'Unable to lock batch at the moment.');
|
||||||
method: 'POST',
|
|
||||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
|
||||||
body: form,
|
|
||||||
});
|
|
||||||
const data = await response.json().catch(() => ({ success: false, error: 'Unexpected response' }));
|
|
||||||
const newHash = response.headers.get('X-CSRF-HASH') || data.csrf_hash;
|
|
||||||
if (newHash) {
|
|
||||||
csrfValue = newHash;
|
|
||||||
}
|
|
||||||
if (!response.ok || !data.success) {
|
|
||||||
throw new Error(data.error || 'Unable to lock batch at the moment.');
|
|
||||||
}
|
|
||||||
markBatchCardLocked(card);
|
markBatchCardLocked(card);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
alert(err.message || 'Unable to lock the batch. Please try again.');
|
alert(err.message || 'Unable to lock the batch. Please try again.');
|
||||||
if (button) {
|
if (button) {
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
button.textContent = 'Lock Batch';
|
button.textContent = 'Submit Batch';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,6 @@
|
|||||||
"fpdf/fpdf": "^1.86",
|
"fpdf/fpdf": "^1.86",
|
||||||
"kint-php/kint": "^6.0",
|
"kint-php/kint": "^6.0",
|
||||||
"mike42/escpos-php": "^4.0",
|
"mike42/escpos-php": "^4.0",
|
||||||
"paypal/rest-api-sdk-php": "^1.6",
|
|
||||||
"phpmailer/phpmailer": "^6.9",
|
"phpmailer/phpmailer": "^6.9",
|
||||||
"phpoffice/phpword": "^1.3",
|
"phpoffice/phpword": "^1.3",
|
||||||
"tecnickcom/tcpdf": "^6.7"
|
"tecnickcom/tcpdf": "^6.7"
|
||||||
|
|||||||
Generated
+2
-55
@@ -4,7 +4,7 @@
|
|||||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||||
"This file is @generated automatically"
|
"This file is @generated automatically"
|
||||||
],
|
],
|
||||||
"content-hash": "1d9a05bb735e750eee1a58bae71f7cda",
|
"content-hash": "4ed9702ae876705936ba1463bc717a32",
|
||||||
"packages": [
|
"packages": [
|
||||||
{
|
{
|
||||||
"name": "bacon/bacon-qr-code",
|
"name": "bacon/bacon-qr-code",
|
||||||
@@ -1109,59 +1109,6 @@
|
|||||||
},
|
},
|
||||||
"time": "2019-10-05T02:44:33+00:00"
|
"time": "2019-10-05T02:44:33+00:00"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"name": "paypal/rest-api-sdk-php",
|
|
||||||
"version": "v1.6.4",
|
|
||||||
"source": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "https://github.com/paypal/PayPal-PHP-SDK.git",
|
|
||||||
"reference": "06837d290c4906578cfd92786412dff330a1429c"
|
|
||||||
},
|
|
||||||
"dist": {
|
|
||||||
"type": "zip",
|
|
||||||
"url": "https://api.github.com/repos/paypal/PayPal-PHP-SDK/zipball/06837d290c4906578cfd92786412dff330a1429c",
|
|
||||||
"reference": "06837d290c4906578cfd92786412dff330a1429c",
|
|
||||||
"shasum": ""
|
|
||||||
},
|
|
||||||
"require": {
|
|
||||||
"ext-curl": "*",
|
|
||||||
"ext-json": "*",
|
|
||||||
"php": ">=5.3.0"
|
|
||||||
},
|
|
||||||
"require-dev": {
|
|
||||||
"phpunit/phpunit": "3.7.*"
|
|
||||||
},
|
|
||||||
"type": "library",
|
|
||||||
"autoload": {
|
|
||||||
"psr-0": {
|
|
||||||
"PayPal": "lib/"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"notification-url": "https://packagist.org/downloads/",
|
|
||||||
"license": [
|
|
||||||
"Apache2"
|
|
||||||
],
|
|
||||||
"authors": [
|
|
||||||
{
|
|
||||||
"name": "PayPal",
|
|
||||||
"homepage": "https://github.com/paypal/rest-api-sdk-php/contributors"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"description": "PayPal's PHP SDK for REST APIs",
|
|
||||||
"homepage": "http://paypal.github.io/PayPal-PHP-SDK/",
|
|
||||||
"keywords": [
|
|
||||||
"payments",
|
|
||||||
"paypal",
|
|
||||||
"rest",
|
|
||||||
"sdk"
|
|
||||||
],
|
|
||||||
"support": {
|
|
||||||
"issues": "https://github.com/paypal/PayPal-PHP-SDK/issues",
|
|
||||||
"source": "https://github.com/paypal/PayPal-PHP-SDK/tree/stable"
|
|
||||||
},
|
|
||||||
"abandoned": "paypal/paypal-server-sdk",
|
|
||||||
"time": "2016-01-20T17:45:52+00:00"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"name": "phpmailer/phpmailer",
|
"name": "phpmailer/phpmailer",
|
||||||
"version": "v6.10.0",
|
"version": "v6.10.0",
|
||||||
@@ -4305,5 +4252,5 @@
|
|||||||
"php": "^8.1"
|
"php": "^8.1"
|
||||||
},
|
},
|
||||||
"platform-dev": {},
|
"platform-dev": {},
|
||||||
"plugin-api-version": "2.6.0"
|
"plugin-api-version": "2.9.0"
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"advisories": {
|
||||||
|
"phpoffice/math": [
|
||||||
|
{
|
||||||
|
"advisoryId": "PKSA-jw72-bn8m-h7rc",
|
||||||
|
"packageName": "phpoffice/math",
|
||||||
|
"affectedVersions": "<=0.2.0",
|
||||||
|
"title": "PHPOffice Math allows XXE when processing an XML file in the MathML format ",
|
||||||
|
"cve": "CVE-2025-48882",
|
||||||
|
"link": "https://github.com/advisories/GHSA-42hm-pq2f-3r7m",
|
||||||
|
"reportedAt": "2025-05-29T17:27:39+00:00",
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"name": "GitHub",
|
||||||
|
"remoteId": "GHSA-42hm-pq2f-3r7m"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"severity": "high"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"phpunit/phpunit": [
|
||||||
|
{
|
||||||
|
"advisoryId": "PKSA-z3gr-8qht-p93v",
|
||||||
|
"packageName": "phpunit/phpunit",
|
||||||
|
"affectedVersions": ">=0,<8.5.52|>=9.0.0,<9.6.33|>=10.0.0,<10.5.62|>=11.0.0,<11.5.50|>=12.0.0,<12.5.8",
|
||||||
|
"title": "Unsafe Deserialization in PHPT Code Coverage Handling",
|
||||||
|
"cve": "CVE-2026-24765",
|
||||||
|
"link": "https://github.com/sebastianbergmann/phpunit/security/advisories/GHSA-vvj3-c3rp-c85p",
|
||||||
|
"reportedAt": "2026-01-27T05:21:14+00:00",
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"name": "GitHub",
|
||||||
|
"remoteId": "GHSA-vvj3-c3rp-c85p"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "FriendsOfPHP/security-advisories",
|
||||||
|
"remoteId": "phpunit/phpunit/CVE-2026-24765.yaml"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"severity": "high"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"abandoned": {
|
||||||
|
"paypal/rest-api-sdk-php": "paypal/paypal-server-sdk"
|
||||||
|
},
|
||||||
|
"filter": []
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Controllers\View {
|
||||||
|
if (!function_exists(__NAMESPACE__ . '\view')) {
|
||||||
|
function view($name, array $data = [], $options = [])
|
||||||
|
{
|
||||||
|
return ['view' => $name, 'data' => $data, 'options' => $options];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace Tests\App\Controllers\View {
|
||||||
|
|
||||||
|
use App\Controllers\View\PaymentController;
|
||||||
|
use CodeIgniter\HTTP\RedirectResponse;
|
||||||
|
use CodeIgniter\Test\CIUnitTestCase;
|
||||||
|
|
||||||
|
class PaymentRequestStub
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private string $method = 'get',
|
||||||
|
private array $post = [],
|
||||||
|
private $file = null
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getMethod(): string
|
||||||
|
{
|
||||||
|
return $this->method;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPost(?string $key = null)
|
||||||
|
{
|
||||||
|
if ($key === null) {
|
||||||
|
return $this->post;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->post[$key] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getFile(string $name)
|
||||||
|
{
|
||||||
|
return $name === 'proof' ? $this->file : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ManualPaymentModelSpy
|
||||||
|
{
|
||||||
|
public array $inserted = [];
|
||||||
|
|
||||||
|
public function insert(array $data)
|
||||||
|
{
|
||||||
|
$this->inserted[] = $data;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class AttachmentServiceStub
|
||||||
|
{
|
||||||
|
public function __construct(private ?string $path = null)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function saveUploadedFile($file, string $subdir): ?string
|
||||||
|
{
|
||||||
|
return $this->path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class TestablePaymentController extends PaymentController
|
||||||
|
{
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setRequestObject($request): self
|
||||||
|
{
|
||||||
|
$this->request = $request;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setManualPaymentModel($model): self
|
||||||
|
{
|
||||||
|
$this->manualPaymentModel = $model;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setAttachmentService($service): self
|
||||||
|
{
|
||||||
|
$this->financialAttachmentService = $service;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class PaymentControllerRegressionTest extends CIUnitTestCase
|
||||||
|
{
|
||||||
|
public function testRedirectPageSendsUsersBackToInvoicePaymentWithInfoMessage(): void
|
||||||
|
{
|
||||||
|
$controller = new TestablePaymentController();
|
||||||
|
|
||||||
|
$response = $controller->redirectPage();
|
||||||
|
|
||||||
|
$this->assertInstanceOf(RedirectResponse::class, $response);
|
||||||
|
$this->assertStringContainsString('parent/invoice_payment', $response->getHeaderLine('Location'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testManualGetReturnsManualPaymentView(): void
|
||||||
|
{
|
||||||
|
$controller = (new TestablePaymentController())
|
||||||
|
->setRequestObject(new PaymentRequestStub('get'));
|
||||||
|
|
||||||
|
$result = $controller->manual();
|
||||||
|
|
||||||
|
$this->assertSame('payment/manual_payment', $result['view']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testManualPostStoresProofPathFromAttachmentService(): void
|
||||||
|
{
|
||||||
|
$model = new ManualPaymentModelSpy();
|
||||||
|
$controller = (new TestablePaymentController())
|
||||||
|
->setManualPaymentModel($model)
|
||||||
|
->setAttachmentService(new AttachmentServiceStub('proofs/check-123.pdf'))
|
||||||
|
->setRequestObject(new PaymentRequestStub('post', [
|
||||||
|
'invoice_number' => 'INV-001',
|
||||||
|
'amount' => '125.00',
|
||||||
|
'payment_method' => 'check',
|
||||||
|
'reference' => 'CHK123',
|
||||||
|
], new \stdClass()));
|
||||||
|
|
||||||
|
$response = $controller->manual();
|
||||||
|
|
||||||
|
$this->assertInstanceOf(RedirectResponse::class, $response);
|
||||||
|
$this->assertCount(1, $model->inserted);
|
||||||
|
$this->assertSame('proofs/check-123.pdf', $model->inserted[0]['proof_path']);
|
||||||
|
$this->assertSame('INV-001', $model->inserted[0]['invoice_number']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Controllers\View {
|
||||||
|
if (!function_exists(__NAMESPACE__ . '\view')) {
|
||||||
|
function view($name, array $data = [], $options = [])
|
||||||
|
{
|
||||||
|
return ['view' => $name, 'data' => $data, 'options' => $options];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace Tests\App\Controllers\View {
|
||||||
|
|
||||||
|
use App\Controllers\View\TuitionForecastController;
|
||||||
|
use App\Libraries\Tuition\TuitionForecastService;
|
||||||
|
use CodeIgniter\HTTP\ResponseInterface;
|
||||||
|
use CodeIgniter\Test\CIUnitTestCase;
|
||||||
|
|
||||||
|
class ForecastRequestStub
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private array $get = [],
|
||||||
|
private array $post = []
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getGet(?string $key = null)
|
||||||
|
{
|
||||||
|
if ($key === null) {
|
||||||
|
return $this->get;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->get[$key] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPost(?string $key = null)
|
||||||
|
{
|
||||||
|
if ($key === null) {
|
||||||
|
return $this->post;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->post[$key] ?? null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class FakeForecastService extends TuitionForecastService
|
||||||
|
{
|
||||||
|
public array $calls = [];
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function calculate(string $schoolYear = '', string $semester = '', string $mode = 'compare', array $options = []): array
|
||||||
|
{
|
||||||
|
$this->calls[] = compact('schoolYear', 'semester', 'mode', 'options');
|
||||||
|
|
||||||
|
return [
|
||||||
|
'school_year' => $schoolYear !== '' ? $schoolYear : '2025-2026',
|
||||||
|
'semester' => $semester,
|
||||||
|
'calculator_mode' => $mode,
|
||||||
|
'options' => [
|
||||||
|
'include_withdrawn_mode' => $options['include_withdrawn_mode'] ?? 'refund_deadline',
|
||||||
|
'include_payment_pending' => $options['include_payment_pending'] ?? '0',
|
||||||
|
'include_event_only' => $options['include_event_only'] ?? '0',
|
||||||
|
'include_paid_invoices' => $options['include_paid_invoices'] ?? '0',
|
||||||
|
'unit_price' => $options['unit_price'] ?? '370.00',
|
||||||
|
'youth_unit_price' => $options['youth_unit_price'] ?? '200.00',
|
||||||
|
],
|
||||||
|
'summary' => [
|
||||||
|
'family_count' => 1,
|
||||||
|
'student_count' => 2,
|
||||||
|
'billable_student_count' => 2,
|
||||||
|
'old_projected_tuition' => '550.00',
|
||||||
|
'new_projected_tuition' => '650.00',
|
||||||
|
'old_projected_income' => '550.00',
|
||||||
|
'new_projected_income' => '650.00',
|
||||||
|
'unit_price' => '370.00',
|
||||||
|
'youth_unit_price' => '200.00',
|
||||||
|
'difference' => '100.00',
|
||||||
|
],
|
||||||
|
'families' => [[
|
||||||
|
'parent_name' => 'Layla Yusuf',
|
||||||
|
'student_count' => 2,
|
||||||
|
'billable_student_count' => 2,
|
||||||
|
'old_total' => '550.00',
|
||||||
|
'new_total' => '650.00',
|
||||||
|
'difference' => '100.00',
|
||||||
|
'warnings' => ['warning'],
|
||||||
|
'student_details' => [[
|
||||||
|
'student_name' => 'Student One',
|
||||||
|
'grade_level' => '1',
|
||||||
|
'billable' => true,
|
||||||
|
'excluded_reason' => '',
|
||||||
|
'old_rule' => 'full',
|
||||||
|
'old_amount' => '350.00',
|
||||||
|
'new_rule' => 'full',
|
||||||
|
'new_amount' => '370.00',
|
||||||
|
]],
|
||||||
|
]],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getAvailableSchoolYears(): array
|
||||||
|
{
|
||||||
|
return ['2025-2026'];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getAvailableSemesters(): array
|
||||||
|
{
|
||||||
|
return ['Fall', 'Spring'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class TestableTuitionForecastController extends TuitionForecastController
|
||||||
|
{
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setForecastService(TuitionForecastService $service): self
|
||||||
|
{
|
||||||
|
$this->forecastService = $service;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setRequestObject($request): self
|
||||||
|
{
|
||||||
|
$this->request = $request;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setResponseObject(ResponseInterface $response): self
|
||||||
|
{
|
||||||
|
$this->response = $response;
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class TuitionForecastControllerTest extends CIUnitTestCase
|
||||||
|
{
|
||||||
|
private TestableTuitionForecastController $controller;
|
||||||
|
private FakeForecastService $service;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->service = new FakeForecastService();
|
||||||
|
$this->controller = (new TestableTuitionForecastController())
|
||||||
|
->setForecastService($this->service)
|
||||||
|
->setResponseObject(service('response'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testIndexBuildsForecastViewDataFromQueryParameters(): void
|
||||||
|
{
|
||||||
|
$request = new ForecastRequestStub([
|
||||||
|
'school_year' => '2026-2027',
|
||||||
|
'semester' => 'Spring',
|
||||||
|
'calculator_mode' => 'new',
|
||||||
|
'include_withdrawn_mode' => 'always',
|
||||||
|
'include_payment_pending' => '1',
|
||||||
|
'include_event_only' => '1',
|
||||||
|
'include_paid_invoices' => '1',
|
||||||
|
'unit_price' => '395.00',
|
||||||
|
'youth_unit_price' => '200.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$result = $this->controller->setRequestObject($request)->index();
|
||||||
|
|
||||||
|
$this->assertSame('administrator/tuition_forecast', $result['view']);
|
||||||
|
$this->assertSame('2026-2027', $result['data']['filters']['school_year']);
|
||||||
|
$this->assertSame('Spring', $result['data']['filters']['semester']);
|
||||||
|
$this->assertSame('new', $result['data']['filters']['calculator_mode']);
|
||||||
|
$this->assertSame('1', $result['data']['filters']['include_payment_pending']);
|
||||||
|
$this->assertSame('395.00', $result['data']['filters']['unit_price']);
|
||||||
|
$this->assertSame('200.00', $result['data']['filters']['youth_unit_price']);
|
||||||
|
$this->assertSame('always', $this->service->calls[0]['options']['include_withdrawn_mode']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCalculateReturnsJsonPayload(): void
|
||||||
|
{
|
||||||
|
$request = new ForecastRequestStub([], [
|
||||||
|
'school_year' => '2025-2026',
|
||||||
|
'semester' => 'Fall',
|
||||||
|
'calculator_mode' => 'compare',
|
||||||
|
'include_withdrawn_mode' => 'refund_deadline',
|
||||||
|
'include_payment_pending' => '1',
|
||||||
|
'include_event_only' => '0',
|
||||||
|
'include_paid_invoices' => '1',
|
||||||
|
'unit_price' => '390.00',
|
||||||
|
'youth_unit_price' => '210.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response = $this->controller->setRequestObject($request)->calculate();
|
||||||
|
$payload = json_decode((string) $response->getBody(), true);
|
||||||
|
|
||||||
|
$this->assertSame('2025-2026', $payload['school_year']);
|
||||||
|
$this->assertSame('Fall', $payload['semester']);
|
||||||
|
$this->assertSame('compare', $payload['calculator_mode']);
|
||||||
|
$this->assertSame('390.00', $payload['options']['unit_price']);
|
||||||
|
$this->assertSame('210.00', $payload['options']['youth_unit_price']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testExportCsvBuildsDownloadWithSummaryAndFamilyRows(): void
|
||||||
|
{
|
||||||
|
$request = new ForecastRequestStub([
|
||||||
|
'school_year' => '2025-2026',
|
||||||
|
'calculator_mode' => 'compare',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response = $this->controller->setRequestObject($request)->exportCsv();
|
||||||
|
$body = (string) $response->getBody();
|
||||||
|
|
||||||
|
$this->assertStringContainsString('text/csv', $response->getHeaderLine('Content-Type'));
|
||||||
|
$this->assertStringContainsString('tuition_forecast_2025-2026_all-year_compare.csv', $response->getHeaderLine('Content-Disposition'));
|
||||||
|
$this->assertStringContainsString('Summary', $body);
|
||||||
|
$this->assertStringContainsString('All Year', $body);
|
||||||
|
$this->assertStringContainsString('Old Projected Income', $body);
|
||||||
|
$this->assertStringContainsString('Youth Unit Price', $body);
|
||||||
|
$this->assertStringContainsString('Layla Yusuf', $body);
|
||||||
|
$this->assertStringContainsString('Student One', $body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\App\Database\Migrations;
|
||||||
|
|
||||||
|
require_once APPPATH . 'Database/Migrations/2026-05-30-000001_FinancialSystemLedgerCleanup.php';
|
||||||
|
|
||||||
|
use App\Database\Migrations\FinancialSystemLedgerCleanup;
|
||||||
|
use CodeIgniter\Test\CIUnitTestCase;
|
||||||
|
|
||||||
|
class TestableFinancialSystemLedgerCleanup extends FinancialSystemLedgerCleanup
|
||||||
|
{
|
||||||
|
public array $calls = [];
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function addInstallmentSequenceColumn(): void
|
||||||
|
{
|
||||||
|
$this->calls[] = 'addInstallmentSequenceColumn';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function ensureIndexes(): void
|
||||||
|
{
|
||||||
|
$this->calls[] = 'ensureIndexes';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function ensureConfigurationDefaults(): void
|
||||||
|
{
|
||||||
|
$this->calls[] = 'ensureConfigurationDefaults';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function archivePaypalTables(): void
|
||||||
|
{
|
||||||
|
$this->calls[] = 'archivePaypalTables';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function refreshFinancialNavItems(): void
|
||||||
|
{
|
||||||
|
$this->calls[] = 'refreshFinancialNavItems';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function restorePaypalTables(): void
|
||||||
|
{
|
||||||
|
$this->calls[] = 'restorePaypalTables';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function dropIndexIfExists(string $table, string $indexName): void
|
||||||
|
{
|
||||||
|
$this->calls[] = "dropIndexIfExists:$table:$indexName";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class FinancialSystemLedgerCleanupTest extends CIUnitTestCase
|
||||||
|
{
|
||||||
|
public function testUpRunsCleanupStepsInExpectedOrder(): void
|
||||||
|
{
|
||||||
|
$migration = new TestableFinancialSystemLedgerCleanup();
|
||||||
|
|
||||||
|
$migration->up();
|
||||||
|
|
||||||
|
$this->assertSame([
|
||||||
|
'addInstallmentSequenceColumn',
|
||||||
|
'ensureIndexes',
|
||||||
|
'ensureConfigurationDefaults',
|
||||||
|
'archivePaypalTables',
|
||||||
|
'refreshFinancialNavItems',
|
||||||
|
], $migration->calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testDownRestoresPaypalAndDropsFinancialIndexes(): void
|
||||||
|
{
|
||||||
|
$migration = new TestableFinancialSystemLedgerCleanup();
|
||||||
|
$fakeDb = new class () {
|
||||||
|
public function tableExists(string $name): bool
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fieldExists(string $field, string $table): bool
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
$fakeForge = new class () {
|
||||||
|
public array $dropped = [];
|
||||||
|
|
||||||
|
public function dropColumn(string $table, string $column): void
|
||||||
|
{
|
||||||
|
$this->dropped[] = [$table, $column];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
self::setPrivateProperty($migration, 'db', $fakeDb);
|
||||||
|
self::setPrivateProperty($migration, 'forge', $fakeForge);
|
||||||
|
|
||||||
|
$migration->down();
|
||||||
|
|
||||||
|
$this->assertSame('restorePaypalTables', $migration->calls[0]);
|
||||||
|
$this->assertContains('dropIndexIfExists:payments:uniq_payments_transaction_id', $migration->calls);
|
||||||
|
$this->assertContains('dropIndexIfExists:invoice_event:idx_invoice_event_invoice_id', $migration->calls);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\App\Helpers;
|
||||||
|
|
||||||
|
use CodeIgniter\Test\CIUnitTestCase;
|
||||||
|
|
||||||
|
class AttendanceCommentHelperTest extends CIUnitTestCase
|
||||||
|
{
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
helper('attendance_comment');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testTemplateMatchReturnsDirectRangeHit(): void
|
||||||
|
{
|
||||||
|
$templates = [
|
||||||
|
['min_score' => 60, 'max_score' => 69, 'template_text' => 'below average'],
|
||||||
|
['min_score' => 70, 'max_score' => 79, 'template_text' => 'fair'],
|
||||||
|
];
|
||||||
|
|
||||||
|
$match = attendance_comment_template_match($templates, 70.0);
|
||||||
|
|
||||||
|
$this->assertNotNull($match);
|
||||||
|
$this->assertSame('fair', $match['template_text']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testTemplateMatchFallsBackToNearestLowerBandForDecimalGap(): void
|
||||||
|
{
|
||||||
|
$templates = [
|
||||||
|
['min_score' => 60, 'max_score' => 69, 'template_text' => 'below average'],
|
||||||
|
['min_score' => 70, 'max_score' => 79, 'template_text' => 'fair'],
|
||||||
|
];
|
||||||
|
|
||||||
|
$match = attendance_comment_template_match($templates, 69.23);
|
||||||
|
|
||||||
|
$this->assertNotNull($match);
|
||||||
|
$this->assertSame('below average', $match['template_text']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCommentUsesResolvedTemplateForDecimalGap(): void
|
||||||
|
{
|
||||||
|
$templates = [
|
||||||
|
['min_score' => 60, 'max_score' => 69, 'template_text' => 'attendance has been below average.'],
|
||||||
|
['min_score' => 70, 'max_score' => 79, 'template_text' => 'attendance has been fair.'],
|
||||||
|
];
|
||||||
|
|
||||||
|
$match = attendance_comment_template_match($templates, 69.23);
|
||||||
|
|
||||||
|
$this->assertNotNull($match);
|
||||||
|
$this->assertSame('attendance has been below average.', $match['template_text']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\App\Libraries;
|
||||||
|
|
||||||
|
use App\Libraries\FinancialAttachmentService;
|
||||||
|
use CodeIgniter\HTTP\Files\UploadedFile;
|
||||||
|
use CodeIgniter\Test\CIUnitTestCase;
|
||||||
|
|
||||||
|
class FinancialAttachmentServiceTest extends CIUnitTestCase
|
||||||
|
{
|
||||||
|
private FinancialAttachmentService $service;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
$this->service = new FinancialAttachmentService();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSaveUploadedFileReturnsNullForInvalidInput(): void
|
||||||
|
{
|
||||||
|
$this->assertNull($this->service->saveUploadedFile(null, 'payments'));
|
||||||
|
|
||||||
|
$file = $this->createMock(UploadedFile::class);
|
||||||
|
$file->method('isValid')->willReturn(false);
|
||||||
|
|
||||||
|
$this->assertNull($this->service->saveUploadedFile($file, 'payments'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSaveUploadedFileRejectsUnsupportedMimeType(): void
|
||||||
|
{
|
||||||
|
$file = $this->createMock(UploadedFile::class);
|
||||||
|
$file->method('isValid')->willReturn(true);
|
||||||
|
$file->method('hasMoved')->willReturn(false);
|
||||||
|
$file->method('getSize')->willReturn(1000);
|
||||||
|
$file->method('getMimeType')->willReturn('text/plain');
|
||||||
|
$file->method('getClientExtension')->willReturn('txt');
|
||||||
|
|
||||||
|
$this->expectException(\RuntimeException::class);
|
||||||
|
$this->expectExceptionMessage('Unsupported file type.');
|
||||||
|
|
||||||
|
$this->service->saveUploadedFile($file, 'payments');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSaveUploadedFileRejectsOversizedFiles(): void
|
||||||
|
{
|
||||||
|
$file = $this->createMock(UploadedFile::class);
|
||||||
|
$file->method('isValid')->willReturn(true);
|
||||||
|
$file->method('hasMoved')->willReturn(false);
|
||||||
|
$file->method('getSize')->willReturn(5242881);
|
||||||
|
$file->method('getMimeType')->willReturn('application/pdf');
|
||||||
|
$file->method('getClientExtension')->willReturn('pdf');
|
||||||
|
|
||||||
|
$this->expectException(\RuntimeException::class);
|
||||||
|
$this->expectExceptionMessage('File too large.');
|
||||||
|
|
||||||
|
$this->service->saveUploadedFile($file, 'payments');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSaveUploadedFileMovesValidFilesAndReturnsRandomName(): void
|
||||||
|
{
|
||||||
|
$file = $this->createMock(UploadedFile::class);
|
||||||
|
$file->method('isValid')->willReturn(true);
|
||||||
|
$file->method('hasMoved')->willReturn(false);
|
||||||
|
$file->method('getSize')->willReturn(1024);
|
||||||
|
$file->method('getMimeType')->willReturn('application/pdf');
|
||||||
|
$file->method('getClientExtension')->willReturn('pdf');
|
||||||
|
$file->method('getRandomName')->willReturn('proof.pdf');
|
||||||
|
|
||||||
|
$file->expects($this->once())
|
||||||
|
->method('move')
|
||||||
|
->with($this->stringContains('writable/uploads/payments'), 'proof.pdf');
|
||||||
|
|
||||||
|
$this->assertSame('proof.pdf', $this->service->saveUploadedFile($file, 'payments'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testResolvePathUsesBasenameAndReturnsNullForMissingFiles(): void
|
||||||
|
{
|
||||||
|
$dir = $this->service->ensureSubdir('receipts');
|
||||||
|
$path = $dir . DIRECTORY_SEPARATOR . 'receipt.pdf';
|
||||||
|
file_put_contents($path, 'pdf');
|
||||||
|
|
||||||
|
$this->assertSame($path, $this->service->resolvePath('receipts', '../receipt.pdf'));
|
||||||
|
$this->assertNull($this->service->resolvePath('receipts', 'missing.pdf'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testDetectMimeReturnsKnownMimeForExistingFile(): void
|
||||||
|
{
|
||||||
|
$dir = $this->service->ensureSubdir('mime-tests');
|
||||||
|
$path = $dir . DIRECTORY_SEPARATOR . 'image.png';
|
||||||
|
file_put_contents(
|
||||||
|
$path,
|
||||||
|
base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aap8AAAAASUVORK5CYII=')
|
||||||
|
);
|
||||||
|
|
||||||
|
$mime = $this->service->detectMime($path);
|
||||||
|
|
||||||
|
$this->assertStringContainsString('image/', $mime);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\App\Libraries;
|
||||||
|
|
||||||
|
use App\Libraries\Tuition\NewTuitionCalculatorService;
|
||||||
|
use CodeIgniter\Test\CIUnitTestCase;
|
||||||
|
|
||||||
|
class NewTuitionCalculatorServiceTest extends CIUnitTestCase
|
||||||
|
{
|
||||||
|
public function testFamilyDiscountsApplyByStudentPosition(): void
|
||||||
|
{
|
||||||
|
$service = new NewTuitionCalculatorService();
|
||||||
|
$result = $service->calculateFamilyTuition([
|
||||||
|
['student_id' => 4, 'student_name' => 'Fourth', 'grade_level' => '4'],
|
||||||
|
['student_id' => 1, 'student_name' => 'First', 'grade_level' => '1'],
|
||||||
|
['student_id' => 3, 'student_name' => 'Third', 'grade_level' => '3'],
|
||||||
|
['student_id' => 2, 'student_name' => 'Second', 'grade_level' => '2'],
|
||||||
|
], [
|
||||||
|
'grade_fee' => 9,
|
||||||
|
'new_tuition_full_amount' => '350.00',
|
||||||
|
'new_tuition_second_student_discount' => '50.00',
|
||||||
|
'new_tuition_third_student_discount' => '50.00',
|
||||||
|
'new_tuition_fourth_plus_discount' => '100.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->assertSame('1200.00', $result['total']);
|
||||||
|
$this->assertSame('350.00', $result['details'][0]['amount']);
|
||||||
|
$this->assertSame('300.00', $result['details'][1]['amount']);
|
||||||
|
$this->assertSame('300.00', $result['details'][2]['amount']);
|
||||||
|
$this->assertSame('250.00', $result['details'][3]['amount']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testDiscountCannotDriveAmountBelowZero(): void
|
||||||
|
{
|
||||||
|
$service = new NewTuitionCalculatorService();
|
||||||
|
$result = $service->calculateFamilyTuition([
|
||||||
|
['student_id' => 1, 'student_name' => 'One', 'grade_level' => '1'],
|
||||||
|
['student_id' => 2, 'student_name' => 'Two', 'grade_level' => '2'],
|
||||||
|
['student_id' => 3, 'student_name' => 'Three', 'grade_level' => '3'],
|
||||||
|
['student_id' => 4, 'student_name' => 'Four', 'grade_level' => '4'],
|
||||||
|
['student_id' => 5, 'student_name' => 'Five', 'grade_level' => '5'],
|
||||||
|
], [
|
||||||
|
'grade_fee' => 9,
|
||||||
|
'new_tuition_full_amount' => '75.00',
|
||||||
|
'new_tuition_second_student_discount' => '50.00',
|
||||||
|
'new_tuition_third_student_discount' => '50.00',
|
||||||
|
'new_tuition_fourth_plus_discount' => '100.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->assertSame('125.00', $result['total']);
|
||||||
|
$this->assertSame('0.00', $result['details'][3]['amount']);
|
||||||
|
$this->assertSame('0.00', $result['details'][4]['amount']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testYouthStudentsUseSeparateUnitPriceWithoutAffectingRegularDiscountOrder(): void
|
||||||
|
{
|
||||||
|
$service = new NewTuitionCalculatorService();
|
||||||
|
$result = $service->calculateFamilyTuition([
|
||||||
|
['student_id' => 3, 'student_name' => 'Youth', 'grade_level' => 'Youth 1'],
|
||||||
|
['student_id' => 1, 'student_name' => 'Regular One', 'grade_level' => '2'],
|
||||||
|
['student_id' => 2, 'student_name' => 'Regular Two', 'grade_level' => '5'],
|
||||||
|
], [
|
||||||
|
'grade_fee' => 9,
|
||||||
|
'new_tuition_full_amount' => '370.00',
|
||||||
|
'new_tuition_youth_amount' => '200.00',
|
||||||
|
'new_tuition_second_student_discount' => '150.00',
|
||||||
|
'new_tuition_third_student_discount' => '150.00',
|
||||||
|
'new_tuition_fourth_plus_discount' => '150.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->assertSame('790.00', $result['total']);
|
||||||
|
$this->assertSame('new_first_student_full_amount', $result['details'][0]['rule']);
|
||||||
|
$this->assertSame('370.00', $result['details'][0]['amount']);
|
||||||
|
$this->assertSame('new_second_student_discount', $result['details'][1]['rule']);
|
||||||
|
$this->assertSame('220.00', $result['details'][1]['amount']);
|
||||||
|
$this->assertSame('new_youth_unit_price', $result['details'][2]['rule']);
|
||||||
|
$this->assertSame('200.00', $result['details'][2]['amount']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\App\Libraries;
|
||||||
|
|
||||||
|
use App\Libraries\Tuition\OldTuitionCalculatorService;
|
||||||
|
use CodeIgniter\Test\CIUnitTestCase;
|
||||||
|
|
||||||
|
class OldTuitionCalculatorServiceTest extends CIUnitTestCase
|
||||||
|
{
|
||||||
|
public function testRegularAndYouthStudentsUseLegacyRules(): void
|
||||||
|
{
|
||||||
|
$service = new OldTuitionCalculatorService();
|
||||||
|
$result = $service->calculateFamilyTuition([
|
||||||
|
['student_id' => 3, 'student_name' => 'Older Youth', 'grade_level' => 'Youth 1'],
|
||||||
|
['student_id' => 1, 'student_name' => 'First Regular', 'grade_level' => '3'],
|
||||||
|
['student_id' => 2, 'student_name' => 'Second Regular', 'grade_level' => '5'],
|
||||||
|
], [
|
||||||
|
'grade_fee' => 9,
|
||||||
|
'first_student_fee' => '350.00',
|
||||||
|
'second_student_fee' => '200.00',
|
||||||
|
'youth_fee' => '180.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->assertSame('730.00', $result['total']);
|
||||||
|
$this->assertSame('old_first_student_fee', $result['details'][0]['rule']);
|
||||||
|
$this->assertSame('old_second_student_fee', $result['details'][1]['rule']);
|
||||||
|
$this->assertSame('old_youth_fee', $result['details'][2]['rule']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\App\Libraries;
|
||||||
|
|
||||||
|
use App\Libraries\Tuition\TuitionForecastService;
|
||||||
|
use CodeIgniter\Test\CIUnitTestCase;
|
||||||
|
|
||||||
|
class TuitionForecastServiceTest extends CIUnitTestCase
|
||||||
|
{
|
||||||
|
public function testForecastSubtractsAlreadyCollectedAndKeepsEventOnlyStudentsNonBillable(): void
|
||||||
|
{
|
||||||
|
$service = new class () extends TuitionForecastService {
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
parent::__construct();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getDefaultSchoolYear(): string
|
||||||
|
{
|
||||||
|
return '2025-2026';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getDefaultSemester(): string
|
||||||
|
{
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function loadFamilies(string $schoolYear, string $semester): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
['parent_id' => 10, 'parent_name' => 'Yusuf, Layla'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function loadFamilyStudents(int $parentId, string $schoolYear, string $semester, array $options): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'students' => [
|
||||||
|
['student_id' => 1, 'student_name' => 'Mariam', 'grade_level' => '1'],
|
||||||
|
['student_id' => 2, 'student_name' => 'Yahya', 'grade_level' => '2'],
|
||||||
|
['student_id' => 4, 'student_name' => 'Youth Student', 'grade_level' => 'Youth 1'],
|
||||||
|
],
|
||||||
|
'all_students' => [
|
||||||
|
['student_id' => 1, 'student_name' => 'Mariam', 'grade_level' => '1', 'billable' => true, 'excluded_reason' => null],
|
||||||
|
['student_id' => 2, 'student_name' => 'Yahya', 'grade_level' => '2', 'billable' => true, 'excluded_reason' => null],
|
||||||
|
['student_id' => 4, 'student_name' => 'Youth Student', 'grade_level' => 'Youth 1', 'billable' => true, 'excluded_reason' => null],
|
||||||
|
['student_id' => 3, 'student_name' => 'Event Only', 'grade_level' => '3', 'billable' => false, 'excluded_reason' => 'event_only'],
|
||||||
|
],
|
||||||
|
'warnings' => ['1 event-only student(s) excluded from tuition.'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getTuitionConfig(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'grade_fee' => 9,
|
||||||
|
'first_student_fee' => '350.00',
|
||||||
|
'second_student_fee' => '200.00',
|
||||||
|
'youth_fee' => '200.00',
|
||||||
|
'new_tuition_full_amount' => $this->unitPriceOverride ?? '350.00',
|
||||||
|
'new_tuition_youth_amount' => $this->youthUnitPriceOverride ?? '200.00',
|
||||||
|
'new_tuition_second_student_discount' => '50.00',
|
||||||
|
'new_tuition_third_student_discount' => '50.00',
|
||||||
|
'new_tuition_fourth_plus_discount' => '100.00',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
$result = $service->calculate('2025-2026', 'Fall', 'compare', [
|
||||||
|
'include_payment_pending' => true,
|
||||||
|
'include_withdrawn_mode' => 'refund_deadline',
|
||||||
|
'unit_price' => '400.00',
|
||||||
|
'youth_unit_price' => '200.00',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->assertSame(1, $result['summary']['family_count']);
|
||||||
|
$this->assertSame(4, $result['summary']['student_count']);
|
||||||
|
$this->assertSame(3, $result['summary']['billable_student_count']);
|
||||||
|
$this->assertSame('750.00', $result['summary']['old_projected_tuition']);
|
||||||
|
$this->assertSame('950.00', $result['summary']['new_projected_tuition']);
|
||||||
|
$this->assertSame('750.00', $result['summary']['old_projected_income']);
|
||||||
|
$this->assertSame('950.00', $result['summary']['new_projected_income']);
|
||||||
|
$this->assertSame('400.00', $result['summary']['unit_price']);
|
||||||
|
$this->assertSame('200.00', $result['summary']['youth_unit_price']);
|
||||||
|
$this->assertSame('event_only', $result['families'][0]['student_details'][3]['excluded_reason']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\App\Models;
|
||||||
|
|
||||||
|
use App\Models\PaymentModel;
|
||||||
|
use CodeIgniter\Test\CIUnitTestCase;
|
||||||
|
|
||||||
|
class PaymentModelMetadataTest extends CIUnitTestCase
|
||||||
|
{
|
||||||
|
public function testAllowedFieldsIncludeInstallmentSequence(): void
|
||||||
|
{
|
||||||
|
$model = new PaymentModel();
|
||||||
|
$fields = self::getPrivateProperty($model, 'allowedFields');
|
||||||
|
|
||||||
|
$this->assertContains('installment_seq', $fields);
|
||||||
|
$this->assertContains('transaction_id', $fields);
|
||||||
|
$this->assertContains('check_file', $fields);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Tests\App\Models;
|
|
||||||
|
|
||||||
use Tests\Support\DBReset;
|
|
||||||
use CodeIgniter\Test\CIUnitTestCase;
|
|
||||||
use App\Models\PaypalTransactionModel;
|
|
||||||
|
|
||||||
class PaypalTransactionModelTest extends CIUnitTestCase
|
|
||||||
{
|
|
||||||
protected function setUp(): void
|
|
||||||
{
|
|
||||||
parent::setUp();
|
|
||||||
DBReset::resetDatabase();
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testCanInsertAndRetrieve()
|
|
||||||
{
|
|
||||||
$record = fake(PaypalTransactionModel::class);
|
|
||||||
$this->assertNotNull($record->id);
|
|
||||||
$fetched = (new PaypalTransactionModel())->find($record->id);
|
|
||||||
$this->assertEquals($record->id, $fetched->id);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testCanUpdate()
|
|
||||||
{
|
|
||||||
$record = fake(PaypalTransactionModel::class);
|
|
||||||
$model = new PaypalTransactionModel();
|
|
||||||
$model->update($record->id, ['updated_at' => date('Y-m-d H:i:s')]);
|
|
||||||
$this->assertTrue(true); // simple test to verify no exception thrown
|
|
||||||
}
|
|
||||||
|
|
||||||
public function testCanDelete()
|
|
||||||
{
|
|
||||||
$record = fake(PaypalTransactionModel::class);
|
|
||||||
$model = new PaypalTransactionModel();
|
|
||||||
$model->delete($record->id);
|
|
||||||
$this->assertNull($model->find($record->id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user