client/addons/bank/ui/_site/script.js
Jacob Schmidt 90476345db feat: Enhance admin and bank systems with event handling and UI improvements
This commit introduces significant updates to the admin and bank systems, focusing on improved event handling and user interface enhancements. Key changes include:

- Refactored event handling for player data requests, paygrade updates, and message broadcasting in the admin panel.
- Implemented new event types for handling player funds and transaction history in the bank system.
- Updated JavaScript functions for better interaction with the web-based UI, including dynamic data requests and improved user feedback.
- Removed deprecated functions and streamlined code for better maintainability.

These enhancements aim to provide a more efficient and user-friendly experience for administrators and players alike.
2025-05-10 17:50:11 -05:00

312 lines
8.7 KiB
JavaScript

/**
* Bank Management Script
* This script handles the bank interface functionality for the Arma 3 game interface.
* It provides wallet/account management, transfers, and transaction history.
*/
//=============================================================================
// #region DATA STRUCTURES AND VARIABLES
//=============================================================================
/**
* Bank state - will be populated from game events
*/
let bankState = {
wallet: 0,
account: 0,
players: [],
transactions: []
};
//=============================================================================
// #region INITIALIZATION AND DATA REQUESTS
//=============================================================================
/**
* Initialize the bank interface
* Sets up the UI and requests initial data from the game engine
*/
function initializeBank() {
// Request initial data from the game
requestPlayerFunds();
requestPlayerData();
requestTransactionHistory();
}
/**
* Request player funds data from the game engine
*/
function requestPlayerFunds() {
const message = {
event: "REQUEST::PLAYER::FUNDS",
data: {}
};
A3API.SendAlert(JSON.stringify(message));
}
/**
* Request player data from the game engine
*/
function requestPlayerData() {
const message = {
event: "REQUEST::PLAYER::DATA",
data: {}
};
A3API.SendAlert(JSON.stringify(message));
}
/**
* Request transaction history from the game engine
*/
function requestTransactionHistory() {
const message = {
event: "REQUEST::TRANSACTION::HISTORY",
data: {}
};
A3API.SendAlert(JSON.stringify(message));
}
//=============================================================================
// #region DATA HANDLERS
//=============================================================================
/**
* Handle player data received from the game engine
* @param {Array} data - List of player objects
*/
function handlePlayerDataRequest(data) {
bankState.players = data;
populatePlayerList();
}
/**
* Handle player funds data received from the game engine
* @param {Object} data - Object containing cash and balance
*/
function handlePlayerFundsRequest(data) {
console.log('Received funds data:', data);
// Parse the data if it's a string
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) {
console.error('Failed to parse data:', e);
return;
}
}
// Ensure we have valid numbers, default to 0 if null
bankState.wallet = data.cash !== null ? Number(data.cash) : 0;
bankState.account = data.balance !== null ? Number(data.balance) : 0;
updateBalanceDisplays();
}
/**
* Handle transaction history data received from the game engine
* @param {Object} data - Object containing transaction history
*/
function handleTransactionHistoryRequest(data) {
console.log('Received transaction history:', data);
// Parse the data if it's a string
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) {
console.error('Failed to parse transaction history:', e);
return;
}
}
// Initialize empty array if history is null
bankState.transactions = [];
updateTransactionHistory();
}
//=============================================================================
// #region UI UPDATES AND DISPLAY
//=============================================================================
/**
* Update balance displays in the header
*/
function updateBalanceDisplays() {
const walletElement = document.getElementById('walletBalance');
const accountElement = document.getElementById('accountBalance');
if (walletElement && accountElement) {
walletElement.textContent = `$${(bankState.wallet || 0).toLocaleString()}`;
accountElement.textContent = `$${(bankState.account || 0).toLocaleString()}`;
}
}
/**
* Populate the player selection dropdown
*/
function populatePlayerList() {
const playerSelect = document.getElementById('playerSelect');
playerSelect.innerHTML = '<option value="" disabled selected>Select Player</option>';
bankState.players.forEach(player => {
const option = document.createElement('option');
option.value = player.uid;
option.textContent = player.name;
playerSelect.appendChild(option);
});
}
/**
* Update the transaction history display
*/
function updateTransactionHistory() {
const historyList = document.getElementById('transactionHistory');
if (!historyList) return;
historyList.innerHTML = '';
if (!Array.isArray(bankState.transactions)) {
console.error('Transaction history is not an array:', bankState.transactions);
return;
}
if (bankState.transactions.length === 0) {
const li = document.createElement('li');
li.className = 'history-item empty';
li.textContent = 'No transactions yet';
historyList.appendChild(li);
return;
}
bankState.transactions.forEach(transaction => {
if (!transaction) return;
const li = document.createElement('li');
li.className = 'history-item';
const isNegative = ['transfer_out', 'to_wallet'].includes(transaction.type);
const amountClass = isNegative ? 'amount-negative' : 'amount-positive';
const amountPrefix = isNegative ? '-' : '+';
const amount = Math.abs(Number(transaction.amount) || 0);
li.innerHTML = `
<span class="transaction-type">${formatTransactionType(transaction.type)}</span>
<span class="transaction-details">${transaction.details || ''}</span>
<span class="amount ${amountClass}">${amountPrefix}$${amount.toLocaleString()}</span>
`;
historyList.appendChild(li);
});
}
/**
* Format transaction type for display
* @param {string} type - Transaction type code
* @returns {string} Formatted transaction type
*/
function formatTransactionType(type) {
const types = {
'to_wallet': 'To Wallet',
'to_account': 'To Account',
'transfer_out': 'Transfer Out',
'transfer_in': 'Transfer In',
'timesheet': 'Timesheet'
};
return types[type] || type;
}
//=============================================================================
// #region ACTION HANDLERS
//=============================================================================
/**
* Handle transfer between wallet and account
*/
function handleTransfer() {
const amount = parseInt(document.getElementById('transferAmount').value);
const transferType = document.getElementById('transferType').value;
if (amount <= 0) {
alert('Amount must be greater than 0');
return;
}
const event = transferType === 'to_wallet' ? 'WITHDRAW::FUNDS' : 'DEPOSIT::FUNDS';
const message = {
event: event,
data: {
amount: amount
}
};
A3API.SendAlert(JSON.stringify(message));
document.getElementById('transferAmount').value = '';
}
/**
* Handle transfer to another player
*/
function handlePlayerTransfer() {
const amount = parseInt(document.getElementById('playerTransferAmount').value);
const playerUid = document.getElementById('playerSelect').value;
if (amount <= 0) {
alert('Amount must be greater than 0');
return;
}
if (!playerUid) {
alert('Please select a player');
return;
}
const message = {
event: 'TRANSFER::FUNDS',
data: {
amount: amount,
uid: playerUid
}
};
A3API.SendAlert(JSON.stringify(message));
document.getElementById('playerTransferAmount').value = '';
}
/**
* Handle timesheet submission
*/
function handleTimesheet() {
const hours = parseFloat(document.getElementById('hoursWorked').value);
const rate = parseInt(document.getElementById('hourlyRate').value);
const amount = Math.floor(hours * rate);
if (amount <= 0) {
alert('Invalid timesheet amount');
return;
}
const message = {
event: 'DEPOSIT::FUNDS',
data: {
amount: amount
}
};
A3API.SendAlert(JSON.stringify(message));
document.getElementById('hoursWorked').value = '';
document.getElementById('hourlyRate').value = '';
}
//=============================================================================
// #region INITIALIZATION
//=============================================================================
/**
* Initialize when DOM is loaded
*/
document.addEventListener('DOMContentLoaded', initializeBank);