diff --git a/includes/utilities.php b/includes/utilities.php index 788307b..5ea4211 100644 --- a/includes/utilities.php +++ b/includes/utilities.php @@ -283,3 +283,52 @@ function consoleLog( $data ) { echo 'console.log(' . json_encode($data) . ')'; echo ''; } + +/** + * Backfill the running_balance column for any user rows that have NULL. + * + * The v2 API's `data.balance` field is the vault balance after each entry. + * If the column is missing for a row, treating it as NULL means + * MAX(running_balance) ignores it. This routine fetches the latest entry's + * balance from the API and broadcasts it to all NULL rows of the user, + * so the displayed balance becomes accurate after the first sync following + * the schema upgrade. + * + * @param PDO $pdo Database connection. + * @param string $user The user whose NULL rows should be backfilled. + * + * @return void + */ +function backfillRunningBalances($pdo, $user) { + if (!array_key_exists($user, USER_KEYS)) { + throw new ApiKeyMissingException("User does not have an API key configured."); + } + + $countStmt = $pdo->prepare('SELECT COUNT(*) FROM vault WHERE user = :user AND running_balance IS NULL'); + $countStmt->bindValue(':user', $user); + $countStmt->execute(); + + if ((int)$countStmt->fetchColumn() === 0) { + return; + } + + $url = 'https://api.torn.com/v2/user?selections=log&log=5850,5851&limit=1&sort=DESC'; + $responseData = executeApiCall($url, USER_KEYS[$user]); + validateApiResponse($responseData); + + if (empty($responseData['log'])) { + return; + } + + $latest = $responseData['log'][0]; + if (!isset($latest['data']['balance'])) { + return; + } + + $balance = (int)$latest['data']['balance']; + + $updateStmt = $pdo->prepare('UPDATE vault SET running_balance = :balance WHERE user = :user AND running_balance IS NULL'); + $updateStmt->bindValue(':balance', $balance); + $updateStmt->bindValue(':user', $user); + $updateStmt->execute(); +}