local QBCore = exports['qb-core']:GetCoreObject()
-- Utility function to get player identifier
local function GetPlayerID(source)
local xPlayer = QBCore.Functions.GetPlayer(source)
if xPlayer then return xPlayer.identifier end
return nil
end
-- Get credit tier for a score
local function GetCreditTier(score)
for _, tier in pairs(Config.CreditTiers) do
if score >= tier.min and score <= tier.max then
return tier
end
end
-- If lower than min, return bottom tier
return Config.CreditTiers[1]
end
-- Load player credit data from DB or create default
local function LoadPlayerCreditData(identifier)
local result = MySQL.Sync.fetchAll('SELECT * FROM player_loans WHERE identifier = ?', {identifier})
if #result == 0 then
-- Insert new record
MySQL.Sync.execute('INSERT INTO player_loans (identifier, credit_score, defaulted, current_loan) VALUES (?, ?, ?, ?)', {
identifier,
Config.StartCreditScore,
0,
json.encode(nil)
})
return {
credit_score = Config.StartCreditScore,
defaulted = false,
current_loan = nil
}
else
local data = result[1]
local loanData = nil
if data.current_loan and data.current_loan ~= 'null' then
loanData = json.decode(data.current_loan)
end
return {
credit_score = tonumber(data.credit_score),
defaulted = (data.defaulted == 1),
current_loan = loanData
}
end
end
-- Save player credit data to DB
local function SavePlayerCreditData(identifier, credit_score, defaulted, current_loan)
local loanJson = current_loan and json.encode(current_loan) or nil
MySQL.Sync.execute('UPDATE player_loans SET credit_score = ?, defaulted = ?, current_loan = ? WHERE identifier = ?', {
credit_score,
(defaulted and 1 or 0),
loanJson,
identifier
})
end
-- Get player credit data async
local function GetPlayerCreditDataAsync(source, cb)
local identifier = GetPlayerID(source)
if not identifier then cb(nil) return end
MySQL.Async.fetchAll('SELECT * FROM player_loans WHERE identifier = ?', {identifier}, function(result)
if #result == 0 then
-- Insert new record
MySQL.Async.execute('INSERT INTO player_loans (identifier, credit_score, defaulted, current_loan) VALUES (?, ?, ?, ?)', {
identifier,
Config.StartCreditScore,
0,
json.encode(nil)
}, function()
cb({
credit_score = Config.StartCreditScore,
defaulted = false,
current_loan = nil
})
end)
else
local data = result[1]
local loanData = nil
if data.current_loan and data.current_loan ~= 'null' then
loanData = json.decode(data.current_loan)
end
cb({
credit_score = tonumber(data.credit_score),
defaulted = (data.defaulted == 1),
current_loan = loanData
})
end
end)
end
-- Update player loan after payment or default
local function UpdatePlayerLoanAfterPayment(identifier, loan)
-- If fully paid
if loan.paymentsMade >= loan.paymentCount then
-- Increase credit score
local newScore = math.min(Config.CreditScoreMax, loan.credit_score + Config.CreditScoreIncrease)
SavePlayerCreditData(identifier, newScore, false, nil)
return true -- loan fully repaid
else
-- Save updated loan with incremented paymentsMade and due date updated externally
SavePlayerCreditData(identifier, loan.credit_score, false, loan)
return false
end
end
-- Mark player defaulted
local function MarkPlayerDefaulted(identifier)
local data = LoadPlayerCreditData(identifier)
if data then
SavePlayerCreditData(identifier, data.credit_score, true, nil)
end
end
-- Check if payment is overdue
local function CheckLoanOverdue(loan)
if not loan then return false end
local now = os.time()
return now > loan.nextPaymentDue
end
-- Handle repayment payment logic (to be called hourly or on demand)
local function HandlePlayerRepayments()
-- This system assumes some external trigger or a cron job or periodic check
-- You may also handle repayments on player login / interaction
-- For demonstration, checking all loans in DB
MySQL.Async.fetchAll('SELECT * FROM player_loans WHERE current_loan IS NOT NULL AND current_loan <> ? AND defaulted = 0', {'null'}, function(results)
for _, row in pairs(results) do
local identifier = row.identifier
local loan = json.decode(row.current_loan)
local now = os.time()
if (loan.nextPaymentDue or 0) < now then
-- Payment overdue
MarkPlayerDefaulted(identifier)
-- Delete loan from DB (flag defaulted)
SavePlayerCreditData(identifier, loan.credit_score, true, nil)
print("[LoanOfficer] Player " .. identifier .. " has defaulted on the loan.")
end
end
end)
end
-- Event: Player repays a payment
RegisterNetEvent('loans:repayPayment', function()
local src = source
local xPlayer = QBCore.Functions.GetPlayer(src)
if not xPlayer then return end
local identifier = xPlayer.identifier
GetPlayerCreditDataAsync(src, function(data)
if not data.current_loan then
TriggerClientEvent('QBCore:Notify', src, "You do not have an active loan.", "error")
return
end
local loan = data.current_loan
if loan.paymentsMade >= loan.paymentCount then
TriggerClientEvent('QBCore:Notify', src, "You already repaid your loan.", "success")
return
end
local paymentAmount = loan.paymentAmount
-- Check if player has enough money
if xPlayer.Functions.RemoveMoney("bank", paymentAmount) then
loan.paymentsMade = loan.paymentsMade + 1
loan.nextPaymentDue = os.time() + Config.PaymentIntervalHours * 3600
if loan.paymentsMade >= loan.paymentCount then
-- Fully repaid
local newCredit = math.min(Config.CreditScoreMax, loan.credit_score + Config.CreditScoreIncrease)
SavePlayerCreditData(identifier, newCredit, false, nil)
TriggerClientEvent('QBCore:Notify', src, Config.Dialog.loanFullyPaid, "success")
else
-- Update loan with next payment due and payments made
SavePlayerCreditData(identifier, loan.credit_score, false, loan)
TriggerClientEvent('QBCore:Notify', src, "Payment successful! Payments left: " .. (loan.paymentCount - loan.paymentsMade), "success")
end
else
TriggerClientEvent('QBCore:Notify', src, "Insufficient funds for payment.", "error")
end
end)
end)
-- Loan creation event from client
QBCore.Functions.CreateCallback('loans:getPlayerCreditScore', function(source, cb)
local xPlayer = QBCore.Functions.GetPlayer(source)
if not xPlayer then cb(nil) return end
local identifier = xPlayer.identifier
GetPlayerCreditDataAsync(source, function(data)
if data then
cb(data)
else
cb(nil)
end
end)
end)
RegisterNetEvent('loans:createLoan', function(amount)
local src = source
local xPlayer = QBCore.Functions.GetPlayer(src)
if not xPlayer then return end
local identifier = xPlayer.identifier
-- Validate amount
if type(amount) ~= "number" or amount <= 0 then
TriggerClientEvent('QBCore:Notify', src, "Invalid loan amount.", "error")
return
end
GetPlayerCreditDataAsync(src, function(data)
if not data then
TriggerClientEvent('QBCore:Notify', src, "Error fetching credit data.", "error")
return
end
if data.defaulted then
TriggerClientEvent('QBCore:Notify', src, Config.Dialog.noLoansAllowed, "error")
return
end
if data.current_loan then
TriggerClientEvent('QBCore:Notify', src, Config.Dialog.alreadyHasLoan, "error")
return
end
local creditScore = data.credit_score
local tier = GetCreditTier(creditScore)
local maxLoanAmount = tier.maxLoan
if amount > maxLoanAmount then
TriggerClientEvent('QBCore:Notify', src, "You cannot borrow more than $" .. maxLoanAmount, "error")
return
end
-- Calculate interest and total payable
local interestRate = tier.interestRate
local payments = tier.payments
local totalInterest = math.floor(amount * interestRate * payments)
local totalPayable = amount + totalInterest
local paymentAmount = math.ceil(totalPayable / payments)
local now = os.time()
local loanData = {
principal = amount,
interestRate = interestRate,
paymentCount = payments,
paymentsMade = 0,
paymentAmount = paymentAmount,
nextPaymentDue = now + Config.PaymentIntervalHours * 3600,
credit_score = creditScore,
totalPayable = totalPayable
}
-- Give player money
xPlayer.Functions.AddMoney("bank", amount)
-- Save loan in DB
SavePlayerCreditData(identifier, creditScore, false, loanData)
TriggerClientEvent('QBCore:Notify', src, Config.Dialog.loanCreated:gsub("${amount}", tostring(amount)), "success")
end)
end)
-- Periodic check for overdue loans (every hour)
Citizen.CreateThread(function()
while true do
Citizen.Wait(3600 * 1000)
HandlePlayerRepayments()
end
end)
local QBCore = exports['qb-core']:GetCoreObject()
local LoanOfficerPed = nil
local isNearLoanOfficer = false
local function DrawText3D(x, y, z, text)
SetTextScale(0.35, 0.35)
SetTextFont(4)
SetTextProportional(1)
SetTextColour(255, 255, 255, 215)
SetTextEntry("STRING")
SetTextCentre(true)
AddTextComponentString(text)
SetDrawOrigin(x, y, z, 0)
DrawText(0.0, 0.0)
ClearDrawOrigin()
end
local function SpawnLoanOfficer()
local model = GetHashKey(Config.LoanOfficer.model)
RequestModel(model)
while not HasModelLoaded(model) do
Citizen.Wait(0)
end
LoanOfficerPed = CreatePed(4, model, Config.LoanOfficer.coords.x, Config.LoanOfficer.coords.y, Config.LoanOfficer.coords.z - 1, Config.LoanOfficer.coords.w, false, true)
SetEntityInvincible(LoanOfficerPed, true)
SetBlockingOfNonTemporaryEvents(LoanOfficerPed, true)
TaskStartScenarioInPlace(LoanOfficerPed, Config.LoanOfficer.pedScenario, 0, true)
FreezeEntityPosition(LoanOfficerPed, true)
end
local dialogStage = 0
local playerCreditData = nil
local loanAmountInput = nil
local function ShowLoanDialog()
QBCore.Functions.TriggerCallback('loans:getPlayerCreditScore', function(data)
if not data then
QBCore.Functions.Notify("Could not fetch credit data.", "error")
return
end
playerCreditData = data
if data.defaulted then
QBCore.Functions.Notify(Config.Dialog.noLoansAllowed, "error")
return
end
if data.current_loan then
QBCore.Functions.Notify(Config.Dialog.alreadyHasLoan, "error")
return
end
local creditScore = data.credit_score
local tier = nil
for _, t in pairs(Config.CreditTiers) do
if creditScore >= t.min and creditScore <= t.max then
tier = t
break
end
end
if not tier then
tier = Config.CreditTiers[1]
end
-- Dialog flow
local dialog = {}
-- Step 1: Greetings
table.insert(dialog, {
text = Config.Dialog.greetings:gsub("{score}", tostring(creditScore)),
options = {
{label = Config.Dialog.yes, value = "yes"},
{label = Config.Dialog.no, value = "no"}
}
})
local choice1 = exports['qb-input']:ShowInput({
header = Config.Dialog.greetings:gsub("{score}", tostring(creditScore)),
submitText = Config.Dialog.yes,
inputs = {
{
type = 'radio',
options = {
{label = Config.Dialog.yes, value = "yes", selected = true},
{label = Config.Dialog.no, value = "no"}
},
icon = "money-bill",
isRequired = true,
name = 'loan_choice'
}
}
})
if not choice1 or choice1.loan_choice == "no" then
QBCore.Functions.Notify("Maybe next time.", "primary")
return
end
-- Step 2: Ask loan amount
local maxLoan = tier.maxLoan
local input = exports['qb-input']:ShowInput({
header = Config.Dialog.loanOffer:gsub("{maxLoan}", tostring(maxLoan)),
submitText = "Submit",
inputs = {
{
type = 'number',
isRequired = true,
name = 'loan_amount',
text = 'Amount',
min = 1,
max = maxLoan
}
}
})
if not input or not tonumber(input.loan_amount) then
QBCore.Functions.Notify("Invalid amount entered.", "error")
return
end
local amount = tonumber(input.loan_amount)
if amount > maxLoan or amount < 1 then
QBCore.Functions.Notify("Amount must be between 1 and " .. maxLoan, "error")
return
end
-- Step 3: Show loan terms and ask for acceptance
local interestRate = tier.interestRate
local payments = tier.payments
local totalInterest = math.floor(amount * interestRate * payments)
local totalPayable = amount + totalInterest
local hours = payments * Config.PaymentIntervalHours
local acceptDialog = exports['qb-input']:ShowInput({
header = Config.Dialog.loanTerms
:gsub("${total}", tostring(totalPayable))
:gsub("{payments}", tostring(payments))
:gsub("{hours}", tostring(hours)),
submitText = "Accept",
inputs = {
{
type = 'radio',
options = {
{label = Config.Dialog.accept, value = "accept", selected = true},
{label = Config.Dialog.decline, value = "decline"}
},
name = 'accept_loan',
isRequired = true
}
}
})
if not acceptDialog or acceptDialog.accept_loan == "decline" then
QBCore.Functions.Notify(Config.Dialog.loanDeclined, "error")
return
end
-- Create loan request to server
TriggerServerEvent('loans:createLoan', amount)
end)
end
CreateThread(function()
SpawnLoanOfficer()
while true do
local pedCoords = GetEntityCoords(PlayerPedId())
local dist = #(pedCoords - Config.LoanOfficer.coords.xyz)
if dist <= Config.LoanOfficer.interactDistance then
DrawText3D(Config.LoanOfficer.coords.x, Config.LoanOfficer.coords.y, Config.LoanOfficer.coords.z + 1.0, "[E] Talk to Loan Officer")
if IsControlJustReleased(0, 38) then -- E key
ShowLoanDialog()
end
end
Citizen.Wait(5)
end
end)