fix financial issues
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user