Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: readability and useless code #91

Merged
merged 1 commit into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 60 additions & 22 deletions client/main.lua
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ local sharedConfig = require 'config.shared'
local VEHICLES = exports.qbx_core:GetVehiclesByName()
local VEHICLES_HASH = exports.qbx_core:GetVehiclesByHash()
local testDriveVeh = 0
local insideShop = nil
local insideShop

---@class VehicleFinanceClient
---@field vehiclePlate string
Expand Down Expand Up @@ -45,17 +45,18 @@ local function confirmationCheck()
confirm = 'Yes',
}
})

return alert
end

---@param data VehicleFinanceClient
local function showVehicleFinanceMenu(data)
local vehLabel = data.brand..' '..data.name
local vehLabel = ('%s %s'):format(data.brand, data.name)
local vehFinance = {
{
title = 'Finance Information',
icon = 'circle-info',
description = string.format('Name: %s\nPlate: %s\nRemaining Balance: $%s\nRecurring Payment Amount: $%s\nPayments Left: %s', vehLabel, data.vehiclePlate, lib.math.groupdigits(data.balance), lib.math.groupdigits(data.paymentAmount), data.paymentsLeft),
description = ('Name: %s\nPlate: %s\nRemaining Balance: $%s\nRecurring Payment Amount: $%s\nPayments Left: %s'):format(vehLabel, data.vehiclePlate, lib.math.groupdigits(data.balance), lib.math.groupdigits(data.paymentAmount), data.paymentsLeft),
readOnly = true,
},
{
Expand All @@ -68,8 +69,9 @@ local function showVehicleFinanceMenu(data)
title = locale('menus.veh_finance_payoff'),
onSelect = function()
local check = confirmationCheck()

if check == 'confirm' then
TriggerServerEvent('qbx_vehicleshop:server:financePaymentFull', {vehBalance = data.balance, vehId = data.vehId})
TriggerServerEvent('qbx_vehicleshop:server:financePaymentFull', { vehBalance = data.balance, vehId = data.vehId })
else
lib.showContext('vehicleFinance')
end
Expand All @@ -92,14 +94,17 @@ local function showFinancedVehiclesMenu()
local vehicles = lib.callback.await('qbx_vehicleshop:server:GetVehiclesByName')
local ownedVehicles = {}

if vehicles == nil or #vehicles == 0 then return exports.qbx_core:Notify(locale('error.nofinanced'), 'error') end
if not vehicles or #vehicles == 0 then
return exports.qbx_core:Notify(locale('error.nofinanced'), 'error')
end

for _, v in pairs(vehicles) do
if v.balance and v.balance > 0 then
local plate = v.props.plate
local vehicle = VEHICLES[v.modelName]

plate = plate and plate:upper()

local vehicle = VEHICLES[v.modelName]
ownedVehicles[#ownedVehicles + 1] = {
title = vehicle.name,
description = locale('menus.veh_platetxt')..plate,
Expand Down Expand Up @@ -129,6 +134,7 @@ local function showFinancedVehiclesMenu()
title = locale('menus.owned_vehicles_header'),
options = ownedVehicles
})

lib.showContext('ownedVehicles')
end

Expand All @@ -142,6 +148,7 @@ end)
---@return string
local function getVehName(closestVehicle)
local vehicle = sharedConfig.shops[insideShop].showroomVehicles[closestVehicle].vehicle

return VEHICLES[vehicle].name
end

Expand All @@ -150,6 +157,7 @@ end
---@return string
local function getVehPrice(closestVehicle)
local vehicle = sharedConfig.shops[insideShop].showroomVehicles[closestVehicle].vehicle

return lib.math.groupdigits(VEHICLES[vehicle].price)
end

Expand All @@ -158,13 +166,15 @@ end
---@return string
local function getVehBrand(closestVehicle)
local vehicle = sharedConfig.shops[insideShop].showroomVehicles[closestVehicle].vehicle

return VEHICLES[vehicle].brand
end

---@param targetShowroomVehicle integer vehicleName
---@param buyVehicle string model
local function openFinance(targetShowroomVehicle, buyVehicle)
local dialog = lib.inputDialog(VEHICLES[buyVehicle].brand:upper()..' '..VEHICLES[buyVehicle].name:upper()..' - $'..getVehPrice(targetShowroomVehicle), {
local title = ('%s %s - $%s'):format(VEHICLES[buyVehicle].brand:upper(), VEHICLES[buyVehicle].name:upper(), getVehPrice(targetShowroomVehicle))
local dialog = lib.inputDialog(title, {
{
type = 'number',
label = locale('menus.financesubmit_downpayment')..sharedConfig.finance.minimumDown..'%',
Expand Down Expand Up @@ -194,15 +204,16 @@ end
---@param targetVehicle number
local function openVehCatsMenu(category, targetVehicle)
local vehMenu = {}

for k, v in pairs(VEHICLES) do
if VEHICLES[k].category == category then
if config.vehicles[k] == nil then
if not config.vehicles[k] then
lib.print.debug('Vehicle not found in config.vehicles. Skipping: '..k)
elseif type(config.vehicles[k].shop) == 'table' then
for _, shop in pairs(config.vehicles[k].shop) do
if shop == insideShop then
vehMenu[#vehMenu + 1] = {
title = v.brand..' '..v.name,
title = ('%s %s'):format(v.brand, v.name),
description = locale('menus.veh_price')..lib.math.groupdigits(v.price),
serverEvent = 'qbx_vehicleshop:server:swapVehicle',
args = {
Expand All @@ -215,7 +226,7 @@ local function openVehCatsMenu(category, targetVehicle)
end
elseif config.vehicles[k].shop == insideShop then
vehMenu[#vehMenu + 1] = {
title = v.brand..' '..v.name,
title = ('%s %s'):format(v.brand, v.name),
description = locale('menus.veh_price')..lib.math.groupdigits(v.price),
serverEvent = 'qbx_vehicleshop:server:swapVehicle',
args = {
Expand Down Expand Up @@ -285,7 +296,8 @@ end
---@param targetVehicle integer
local function openCustomFinance(targetVehicle)
local vehicle = sharedConfig.shops[insideShop].showroomVehicles[targetVehicle].vehicle
local dialog = lib.inputDialog(getVehBrand(targetVehicle):upper()..' '..vehicle:upper()..' - $'..getVehPrice(targetVehicle), {
local title = ('%s %s - $%s'):format(getVehBrand(targetVehicle):upper(), vehicle:upper(), getVehPrice(targetVehicle))
local dialog = lib.inputDialog(title, {
{
type = 'number',
label = locale('menus.financesubmit_downpayment')..sharedConfig.finance.minimumDown..'%',
Expand Down Expand Up @@ -332,12 +344,14 @@ end
---@param vehModel string
local function startTestDrive(vehModel)
local playerId = getPlayerIdInput(vehModel)

TriggerServerEvent('qbx_vehicleshop:server:customTestDrive', vehModel, playerId)
end

---@param vehModel string
local function sellVehicle(vehModel)
local playerId = getPlayerIdInput(vehModel)

TriggerServerEvent('qbx_vehicleshop:server:sellShowroomVehicle', vehModel, playerId)
end

Expand Down Expand Up @@ -424,9 +438,10 @@ local function openVehicleSellMenu(targetVehicle)

lib.registerContext({
id = 'vehicleMenu',
title = getVehBrand(targetVehicle):upper()..' '..getVehName(targetVehicle):upper()..' - $'..getVehPrice(targetVehicle),
title = ('%s %s - $%s'):format(getVehBrand(targetVehicle):upper(), getVehName(targetVehicle):upper(), getVehPrice(targetVehicle)),
options = options
})

lib.showContext('vehicleMenu')
end

Expand All @@ -448,10 +463,17 @@ local function startTestDriveTimer(time)
while playerState.isInTestDrive do
local currentGameTime = GetGameTimer()
local secondsLeft = currentGameTime - gameTimer

if currentGameTime < gameTimer + timeMs and secondsLeft >= timeMs - 50 then
endTestDrive()
end
qbx.drawText2d({ text = locale('general.testdrive_timer')..math.ceil(time - secondsLeft / 1000), coords = vec2(1.0, 1.38), scale = 0.5})

qbx.drawText2d({
text = locale('general.testdrive_timer')..math.ceil(time - secondsLeft / 1000),
coords = vec2(1.0, 1.38),
scale = 0.5
})

Wait(0)
end
end)
Expand All @@ -462,6 +484,7 @@ end
---@param targetVehicle number
local function createVehicleTarget(shopName, entity, targetVehicle)
local shop = sharedConfig.shops[shopName]

exports.ox_target:addLocalEntity(entity, {
{
name = 'vehicleshop:showVehicleOptions',
Expand All @@ -481,21 +504,26 @@ end
---@param targetVehicle number
local function createVehicleZone(shopName, coords, targetVehicle)
local shop = sharedConfig.shops[shopName]

lib.zones.box({
coords = coords.xyz,
size = shop.zone.size,
rotation = coords.w,
debug = config.debugPoly,
onEnter = function()
if not insideShop then return end

local job = sharedConfig.shops[insideShop].job
if job and QBX.PlayerData.job.name ~= job then return end

lib.showTextUI(locale('menus.keypress_vehicleViewMenu'))
end,
inside = function()
if not insideShop then return end

local job = sharedConfig.shops[insideShop].job
if not IsControlJustPressed(0, 38) or job and QBX.PlayerData.job.name ~= job then return end

openVehicleSellMenu(targetVehicle)
end,
onExit = function()
Expand Down Expand Up @@ -535,6 +563,7 @@ local function createShowroomVehicle(model, coords)
SetVehicleDoorsLocked(veh, 3)
FreezeEntityPosition(veh, true)
SetVehicleNumberPlateText(veh, 'BUY ME')

return veh
end

Expand Down Expand Up @@ -572,7 +601,9 @@ local function init()
for i = 1, #showroomVehicles do
local showroomVehicle = showroomVehicles[i]
local veh = createShowroomVehicle(showroomVehicle.vehicle, showroomVehicle.coords)

shopVehs[i] = veh

if config.useTarget then
createVehicleTarget(shopName, veh, i)
else
Expand All @@ -595,6 +626,7 @@ AddEventHandler('QBCore:Client:OnPlayerUnload', function()
for i = 1, #shopVehs do
DeleteEntity(shopVehs[i])
end

shopVehs = {}
end)

Expand All @@ -618,9 +650,7 @@ RegisterNetEvent('qbx_vehicleshop:client:testDrive', function(args)
})

lib.waitFor(function()
if NetworkDoesEntityExistWithNetworkId(netId) then
return true
end
return NetworkDoesEntityExistWithNetworkId(netId)
Comment on lines -621 to +653
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've had issues with waitFor and this. I believe it needs to return nil implicitly if the condition hasn't been met. Maybe explicitly would work as well, but the way it was done before will definitely work.

end, 'netId not exist')

testDriveVeh = netId
Expand Down Expand Up @@ -652,7 +682,9 @@ RegisterNetEvent('qbx_vehicleshop:client:swapVehicle', function(data)

dataTargetVehicle.vehicle = data.toVehicle

if config.useTarget then createVehicleTarget(shopName, veh, data.targetVehicle) end
if config.useTarget then
createVehicleTarget(shopName, veh, data.targetVehicle)
end
end)

lib.callback.register('qbx_vehicleshop:client:getPlayerCurrentShop', function()
Expand All @@ -661,6 +693,7 @@ end)

local function confirmTrade(confirmationText)
local accepted

exports.npwd:createSystemNotification({
uniqId = "vehicleShop:confirmTrade",
content = confirmationText,
Expand All @@ -675,12 +708,17 @@ local function confirmTrade(confirmationText)
accepted = false
end,
})
while accepted == nil do Wait(100) end

while not accepted do
Wait(100)
end

return accepted
end

lib.callback.register('qbx_vehicleshop:client:confirmTrade', function(vehicle, sellAmount)
local confirmationText = locale('general.transfervehicle_confirm', VEHICLES_HASH[vehicle].brand, VEHICLES_HASH[vehicle].name, lib.math.groupdigits(sellAmount) or 0)

if GetResourceState('npwd') ~= 'started' then
local input = lib.inputDialog(confirmationText, {
{
Expand Down Expand Up @@ -712,7 +750,7 @@ CreateThread(function()
end)

AddEventHandler('onResourceStart', function(resource)
if GetCurrentResourceName() == resource then
init()
end
end)
if resource ~= cache.resource then return end

init()
end)
5 changes: 3 additions & 2 deletions fxmanifest.lua
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
fx_version 'cerulean'
game 'gta5'

description 'qbx_vehicleshop'
name 'qbx_vehicleshop'
description 'Vehicle shop system for Qbox'
repository 'https://github.com/Qbox-project/qbx_vehicleshop'
version '1.0.0'

Expand Down Expand Up @@ -30,4 +31,4 @@ files {

provide 'qb-vehicleshop'
lua54 'yes'
use_experimental_fxv2_oal 'yes'
use_experimental_fxv2_oal 'yes'
25 changes: 15 additions & 10 deletions server/finance.lua
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,15 @@
---@field paymentsleft integer
---@field financetime number

local finance = {}

---@param request InsertVehicleEntityWithFinanceRequest
function finance.insertVehicleEntityWithFinance(request)
local function insertVehicleEntityWithFinance(request)
local insertVehicleEntityRequest = request.insertVehicleEntityRequest
local vehicleFinance = request.vehicleFinance
local vehicleId = exports.qbx_vehicles:CreatePlayerVehicle({
model = insertVehicleEntityRequest.model,
citizenid = insertVehicleEntityRequest.citizenId,
})

local vehicleFinance = request.vehicleFinance
MySQL.insert('INSERT INTO vehicle_financing (vehicleId, balance, paymentamount, paymentsleft, financetime) VALUES (?, ?, ?, ?, ?)', {
vehicleId,
vehicleFinance.balance,
Expand All @@ -43,13 +41,13 @@ end

---@param time number
---@param vehicleId integer
function finance.updateVehicleEntityFinanceTime(time, vehicleId)
local function updateVehicleEntityFinanceTime(time, vehicleId)
MySQL.update('UPDATE vehicle_financing SET financetime = ? WHERE vehicleId = ?', {time, vehicleId})
end

---@param vehicleFinance VehicleFinanceServer
---@param vehicleId number
function finance.updateVehicleFinance(vehicleFinance, vehicleId)
local function updateVehicleFinance(vehicleFinance, vehicleId)
if vehicleFinance.balance == 0 then
MySQL.query('DELETE FROM vehicle_financing WHERE vehicleId = ?', {
vehicleId
Expand All @@ -67,22 +65,29 @@ end

---@param id integer
---@return VehicleFinancingEntity
function finance.fetchFinancedVehicleEntityById(id)
local function fetchFinancedVehicleEntityById(id)
return MySQL.single.await('SELECT * FROM vehicle_financing WHERE vehicleId = ? AND balance > 0 AND financetime < 1', {id})
end

---@param vehicleId integer
---@return boolean
function finance.fetchIsFinanced(vehicleId)
local function fetchIsFinanced(vehicleId)
return MySQL.scalar.await('SELECT 1 FROM vehicle_financing WHERE vehicleId = ? AND balance > 0', {
vehicleId
}) ~= nil
end

---@param citizenId string
---@return VehicleFinancingEntity
function finance.fetchFinancedVehicleEntitiesByCitizenId(citizenId)
local function fetchFinancedVehicleEntitiesByCitizenId(citizenId)
return MySQL.query.await('SELECT vehicle_financing.* FROM vehicle_financing INNER JOIN player_vehicles ON player_vehicles.citizenid = ? WHERE vehicle_financing.vehicleId = player_vehicles.id AND vehicle_financing.balance > 0 AND vehicle_financing.financetime > 1', {citizenId})
end

return finance
return {
insertVehicleEntityWithFinance = insertVehicleEntityWithFinance,
updateVehicleEntityFinanceTime = updateVehicleEntityFinanceTime,
updateVehicleFinance = updateVehicleFinance,
fetchFinancedVehicleEntityById = fetchFinancedVehicleEntityById,
fetchIsFinanced = fetchIsFinanced,
fetchFinancedVehicleEntitiesByCitizenId = fetchFinancedVehicleEntitiesByCitizenId,
}
Loading