0 || created_by > 0`, * and this row always carries a zero Balance. * * @param int $applicationId * @param int|float $installmentAmount * @param int $userId User credited with the create/update. * @param int|null $creditId Resolved from the credit report when null. * @return array{id: int, created: bool, changed: bool, old_installment_amount: int|float} */ public static function upsertCreditFairEMI($applicationId, $installmentAmount, $userId, $creditId = null) { $installmentAmount = $installmentAmount ?: 0; $existing = static::where('application_id', $applicationId) ->where('AccountType', self::CREDIT_FAIR_EMI) ->first(['id', 'InstallmentAmount']); if (isset($existing->id)) { $changed = $existing->InstallmentAmount != $installmentAmount; if ($changed) { static::where('id', $existing->id)->update([ 'InstallmentAmount' => $installmentAmount, 'updated_by' => $userId, 'updated_at' => Carbon::now()->toDateTimeString(), ]); } return [ 'id' => $existing->id, 'created' => false, 'changed' => $changed, 'old_installment_amount' => $existing->InstallmentAmount, ]; } if (is_null($creditId)) { // Lowest applicant_type first, so the applicant's report wins over the co-applicant's. $creditReport = CreditReport::where('application_id', $applicationId) ->orderBy('applicant_type', 'asc') ->first(['id']); $creditId = isset($creditReport->id) ? $creditReport->id : 0; } $id = static::insertGetId([ 'application_id' => $applicationId, 'credit_id' => $creditId, 'AccountType' => self::CREDIT_FAIR_EMI, 'ApprovedAmount' => 0, 'Balance' => 0, 'InterestRate' => 0, 'RepaymentTenure' => 0, 'InstallmentAmount' => $installmentAmount, 'cc_loan' => 1, 'DateOpened' => null, 'DateClosed' => null, 'OwnershipType' => '', 'applicant_type' => 1, 'Institution' => '', 'LastPayment' => null, 'PastDueAmount' => null, 'isOpened' => 1, 'dpd' => json_encode([]), 'reason_info' => null, 'created_by' => $userId, 'created_at' => Carbon::now()->toDateTimeString(), ]); return [ 'id' => $id, 'created' => true, 'changed' => true, 'old_installment_amount' => 0, ]; } }