fix payments

This commit is contained in:
root
2026-07-08 23:30:16 -04:00
parent 6e8da3cc2c
commit ed11cccecc
15 changed files with 959 additions and 132 deletions
+283 -66
View File
@@ -2,7 +2,9 @@
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
use CodeIgniter\Validation\ValidationInterface;
class PaymentModel extends Model
{
@@ -10,12 +12,22 @@ class PaymentModel extends Model
protected $primaryKey = 'id';
protected $returnType = 'array';
/**
* Keep this list broad, then filter it in __construct() against the real DB schema.
* This prevents CI from trying to insert/update columns that do not exist, such as `balance`.
*/
protected $allowedFields = [
'parent_id',
'invoice_id',
// Legacy invoice snapshot fields. Do not use these as source of truth.
'total_amount',
// Actual payment fields.
'paid_amount',
'balance',
'balance_amount',
'balance_after_payment',
'number_of_installments',
'installment_seq',
'transaction_id',
@@ -24,26 +36,44 @@ class PaymentModel extends Model
'payment_method',
'payment_date',
'school_year',
'semester',
'status',
'updated_by'
'updated_by',
];
protected $useTimestamps = false;
// ❗ Your DB handles created_at / updated_at with default CURRENT_TIMESTAMP
// Remove CI4 auto timestamp management unless you modify your DB schema
/**
* Let DB defaults handle created_at / updated_at.
* Keep validation strict for actual payment data, but do not require legacy snapshot columns.
*/
protected $cleanValidationRules = true;
protected $validationRules = [
'parent_id' => 'required|integer',
'invoice_id' => 'required|integer',
'total_amount' => 'required|decimal',
'paid_amount' => 'required|decimal',
'balance' => 'required|decimal',
'number_of_installments' => 'required|integer',
'payment_method' => 'required|max_length[50]', // ✅ Removed 'string'
'payment_date' => 'required|valid_date[Y-m-d H:i:s]',
'status' => 'required|max_length[50]', // ✅ Removed 'string'
// Legacy snapshot. Optional because invoice total belongs to invoices table.
'total_amount' => 'permit_empty|decimal',
'paid_amount' => 'required|decimal|greater_than[0]',
// These are optional because not every live schema has a balance snapshot column.
'balance' => 'permit_empty|decimal|greater_than_equal_to[0]',
'balance_amount' => 'permit_empty|decimal|greater_than_equal_to[0]',
'balance_after_payment' => 'permit_empty|decimal|greater_than_equal_to[0]',
// Legacy/current sequence columns.
'number_of_installments' => 'permit_empty|integer|greater_than[0]',
'installment_seq' => 'permit_empty|integer|greater_than[0]',
'transaction_id' => 'permit_empty|max_length[100]',
'payment_method' => 'required|in_list[cash,check,card]',
'payment_date' => 'required|valid_date',
'school_year' => 'permit_empty|max_length[20]',
'status' => 'required|max_length[50]',
'check_file' => 'permit_empty|max_length[255]',
'check_number' => 'permit_empty|max_length[100]',
'updated_by' => 'permit_empty|integer',
];
protected $validationMessages = [
@@ -56,112 +86,225 @@ class PaymentModel extends Model
'integer' => 'Invoice ID must be an integer.',
],
'total_amount' => [
'required' => 'Total amount is required.',
'decimal' => 'Total amount must be a valid decimal.',
],
'paid_amount' => [
'required' => 'Paid amount is required.',
'decimal' => 'Paid amount must be a valid decimal.',
'greater_than' => 'Paid amount must be greater than zero.',
],
'balance' => [
'required' => 'Balance is required.',
'decimal' => 'Balance must be a valid decimal.',
'greater_than_equal_to' => 'Balance must not be negative.',
],
'balance_amount' => [
'decimal' => 'Balance amount must be a valid decimal.',
'greater_than_equal_to' => 'Balance amount must not be negative.',
],
'balance_after_payment' => [
'decimal' => 'Balance after payment must be a valid decimal.',
'greater_than_equal_to' => 'Balance after payment must not be negative.',
],
'payment_date' => [
'required' => 'Payment date is required.',
'valid_date' => 'Payment date must be a valid date (Y-m-d H:i:s).',
'valid_date' => 'Payment date must be a valid date.',
],
'payment_method' => [
'required' => 'Payment method is required.',
'max_length' => 'Payment method must not exceed 50 characters.',
'in_list' => 'Payment method must be cash, check, or card.',
],
'status' => [
'required' => 'Status is required.',
'max_length' => 'Status must not exceed 50 characters.',
],
'number_of_installments' => [
'required' => 'Number of installments is required.',
'integer' => 'Number of installments must be an integer.',
'greater_than' => 'Number of installments must be greater than zero.',
],
'installment_seq' => [
'integer' => 'Installment sequence must be an integer.',
'greater_than' => 'Installment sequence must be greater than zero.',
],
'check_number' => [
'max_length' => 'Check number must not exceed 100 characters.',
]
],
];
/**
* Get payments by parent ID.
*
* @param int $parentId
* @return array
*/
public function getPaymentsByParentId(int $parentId): array
private array $paymentColumns = [];
private array $excludedPaymentStatuses = [
'void',
'voided',
'refunded',
'failed',
'chargeback',
'declined',
'reversed',
'canceled',
'cancelled',
];
public function __construct(?ConnectionInterface $db = null, ?ValidationInterface $validation = null)
{
return $this->where('parent_id', $parentId)
->orderBy('payment_date', 'DESC')
->findAll();
parent::__construct($db, $validation);
$this->paymentColumns = $this->getTableColumns($this->table);
// Remove fields that do not exist in the live DB.
// This prevents errors like "Unknown column balance".
$this->allowedFields = array_values(array_filter(
$this->allowedFields,
fn (string $field): bool => in_array($field, $this->paymentColumns, true)
));
// Remove validation rules for columns that do not exist.
foreach (array_keys($this->validationRules) as $field) {
if (!in_array($field, $this->allowedFields, true)) {
unset($this->validationRules[$field]);
unset($this->validationMessages[$field]);
}
}
}
/**
* Calculate the total paid amount for a specific parent.
* Get payments by parent ID with invoice context.
*
* @param int $parentId
* @return float
* The source of truth for invoice total/status/balance is invoices, not payments.
*/
public function getPaymentsByParentId(int $parentId, ?string $schoolYear = null): array
{
return $this->parentPaymentHistoryQuery($parentId, $schoolYear)->findAll();
}
/**
* Build parent payment history query with invoice context.
*
* Kept public so controllers can paginate without duplicating select/join logic.
*/
public function parentPaymentHistoryQuery(int $parentId, ?string $schoolYear = null): self
{
$paymentBalanceSelect = $this->getPaymentBalanceSelectExpression('payments');
$invoiceBalanceSelect = $this->columnExists('invoices', 'balance')
? 'invoices.balance AS invoice_current_balance'
: '0.00 AS invoice_current_balance';
$select = [
'payments.id',
'payments.invoice_id',
'invoices.invoice_number',
'payments.transaction_id',
'payments.paid_amount',
'payments.payment_method',
'payments.check_number',
'payments.check_file',
'payments.payment_date',
'payments.installment_seq',
'payments.number_of_installments',
$paymentBalanceSelect,
'payments.status AS payment_status',
'invoices.total_amount AS invoice_total',
$invoiceBalanceSelect,
'invoices.status AS invoice_status',
'invoices.school_year',
];
$model = new self($this->db);
$builder = $model->select(implode(', ', $select), false)
->join('invoices', 'invoices.id = payments.invoice_id', 'inner')
->where('payments.parent_id', $parentId);
if ($schoolYear !== null && $schoolYear !== '') {
$builder->where('invoices.school_year', $schoolYear);
}
return $builder
->orderBy('payments.payment_date', 'DESC')
->orderBy('payments.id', 'DESC');
}
/**
* Calculate the total paid amount for a parent in a school year.
*
* Uses invoices.school_year so old poisoned payment term data does not corrupt totals.
*/
public function getTotalPaidByParentId(int $parentId, string $schoolYear): float
{
$db = \Config\Database::connect();
$result = $db->table('payments')
->selectSum('paid_amount', 'total_paid')
->where('parent_id', $parentId)
->where('school_year', $schoolYear)
->whereNotIn('status', ['void', 'voided', 'refunded', 'failed', 'chargeback', 'declined', 'reversed', 'canceled', 'cancelled'])
$result = $this->db->table('payments p')
->selectSum('p.paid_amount', 'total_paid')
->join('invoices i', 'i.id = p.invoice_id', 'inner')
->where('p.parent_id', $parentId)
->where('i.school_year', $schoolYear)
->where($this->successfulPaymentWhereSql('p.status'), null, false)
->get()
->getRowArray();
return $result && isset($result['total_paid']) ? (float) $result['total_paid'] : 0.00;
return $result && isset($result['total_paid'])
? (float) $result['total_paid']
: 0.00;
}
/**
* Update balance for a specific payment.
* Legacy method.
*
* @param int $paymentId
* @param float $amountPaid
* @return bool
* This should not be used for new payment recording.
* New payments should be inserted as immutable payment rows and invoices recalculated by InvoiceLedgerService.
*/
public function updateBalance(int $paymentId, float $amountPaid): bool
{
if ($amountPaid <= 0) {
return false;
}
$payment = $this->find($paymentId);
if (!$payment) {
return false;
}
$newBalance = $payment['balance'] - $amountPaid;
$updateData = [
'paid_amount' => round((float) ($payment['paid_amount'] ?? 0) + $amountPaid, 2),
];
return $this->update($paymentId, [
'paid_amount' => $payment['paid_amount'] + $amountPaid,
'balance' => $newBalance
]);
$balanceField = $this->getPaymentBalanceField();
if ($balanceField !== null && array_key_exists($balanceField, $payment)) {
$updateData[$balanceField] = max(
0.00,
round((float) ($payment[$balanceField] ?? 0) - $amountPaid, 2)
);
}
return $this->update($paymentId, $updateData);
}
/**
* Get payments by school year.
*
* @param string $schoolYear
* @return array
* Uses invoice school year when possible because payment.school_year may have old bad data.
*/
public function getPaymentsByYear(string $schoolYear): array
{
return $this->where('school_year', $schoolYear)
->orderBy('payment_date', 'DESC')
$paymentBalanceSelect = $this->getPaymentBalanceSelectExpression('payments');
$select = [
'payments.*',
'invoices.invoice_number',
'invoices.total_amount AS invoice_total',
'invoices.status AS invoice_status',
$paymentBalanceSelect,
];
return $this->select(implode(', ', $select), false)
->join('invoices', 'invoices.id = payments.invoice_id', 'inner')
->where('invoices.school_year', $schoolYear)
->orderBy('payments.payment_date', 'DESC')
->orderBy('payments.id', 'DESC')
->findAll();
}
/**
* Generate a new transaction ID.
* Generate a transaction ID.
*
* @return string
* This is okay for legacy/manual use, but a DB UNIQUE KEY on transaction_id is still required.
*/
public function generateNewTransactionId(): string
{
@@ -173,41 +316,115 @@ class PaymentModel extends Model
->first();
if ($latest && isset($latest['transaction_id'])) {
$lastNumber = (int) str_replace($prefix, '', $latest['transaction_id']);
$lastNumber = (int) str_replace($prefix, '', (string) $latest['transaction_id']);
$newNumber = $lastNumber + 1;
} else {
$newNumber = 1;
}
return $prefix . str_pad($newNumber, 6, '0', STR_PAD_LEFT);
return $prefix . str_pad((string) $newNumber, 6, '0', STR_PAD_LEFT);
}
/**
* Get latest successful payment per invoice.
*
* Uses latest payment ID instead of latest date only.
* Date-only matching can return duplicates when several payments happen on the same day.
*/
public function getPaymentsByInvoice($invoiceIds): array
{
// Normalize input
if (!is_array($invoiceIds)) {
$invoiceIds = [$invoiceIds];
}
$invoiceIds = array_values(array_filter(array_map('intval', $invoiceIds)));
if (empty($invoiceIds)) {
return [];
}
// Subquery: latest payment_date per invoice (Full/Partial only)
$latestSub = $this->db->table('payments')
->select('invoice_id, MAX(payment_date) AS max_date')
->whereIn('status', ['Full', 'Paid', 'Partially Paid'])
->select('invoice_id, MAX(id) AS max_id')
->whereIn('invoice_id', $invoiceIds)
->where('paid_amount >', 0)
->where($this->successfulPaymentWhereSql('status'), null, false)
->groupBy('invoice_id')
->getCompiledSelect();
// Main query: join payments to the latest per invoice
$rows = $this->db->table('payments p')
->select('p.invoice_id, p.paid_amount AS last_paid_amount, p.payment_date AS last_payment_date, p.status AS last_payment_status')
->join("($latestSub) latest", 'latest.invoice_id = p.invoice_id AND latest.max_date = p.payment_date', 'inner', false) // <-- escape=false
return $this->db->table('payments p')
->select([
'p.invoice_id',
'p.id AS payment_id',
'p.paid_amount AS last_paid_amount',
'p.payment_date AS last_payment_date',
'p.status AS last_payment_status',
'p.transaction_id',
'p.payment_method',
'p.check_number',
])
->join(
"($latestSub) latest",
'latest.invoice_id = p.invoice_id AND latest.max_id = p.id',
'inner',
false
)
->whereIn('p.invoice_id', $invoiceIds)
->whereIn('p.status', ['Full', 'Paid', 'Partially Paid'])
->get()
->getResultArray();
}
return $rows;
private function getPaymentBalanceField(): ?string
{
foreach (['balance_after_payment', 'balance', 'balance_amount'] as $field) {
if (in_array($field, $this->paymentColumns, true)) {
return $field;
}
}
return null;
}
private function getPaymentBalanceSelectExpression(string $alias = 'payments'): string
{
$field = $this->getPaymentBalanceField();
if ($field === null) {
return '0.00 AS balance_after_payment';
}
return "{$alias}.{$field} AS balance_after_payment";
}
private function successfulPaymentWhereSql(string $column): string
{
$escapedStatuses = array_map(
fn (string $status): string => $this->db->escape($status),
$this->excludedPaymentStatuses
);
return 'LOWER(COALESCE(' . $column . ', \'\')) NOT IN (' . implode(', ', $escapedStatuses) . ')';
}
private function getTableColumns(string $table): array
{
try {
return $this->db->getFieldNames($table);
} catch (\Throwable $e) {
log_message('error', '[PaymentModel] Could not read table columns for {table}: {error}', [
'table' => $table,
'error' => $e->getMessage(),
]);
return [];
}
}
private function columnExists(string $table, string $column): bool
{
try {
return $this->db->fieldExists($column, $table);
} catch (\Throwable $e) {
return false;
}
}
}