Replace firstRun/getLog with backfillUserLogs/syncUserLogs

This commit is contained in:
Keith Solomon
2026-08-03 13:40:12 -05:00
parent cb584e9d3a
commit d6aef3da42
+31 -76
View File
@@ -52,102 +52,57 @@ function getDatabaseConnection() {
}
/**
* Pulls and stores all vault transaction logs for a user from the Torn API.
* Pulls and stores the full vault transaction log history for a user.
*
* This function retrieves all transaction logs related to vault deposits and
* withdrawals for a specified user. It continues fetching logs until no more
* entries are available, and stores each entry in the database. Each log entry
* is uniquely identified by its ID and includes details such as timestamp,
* description, and amount. The function requires the user's API key to
* authenticate requests to the Torn API.
* Pages through the v2 Torn API using `_metadata.links.next` until the
* API reports no further pages. Intended for first-run use when the
* local database is empty. Idempotent: re-running on a partially
* populated database inserts only new entries (ON CONFLICT DO NOTHING).
*
* @param string $user The user whose transaction logs are to be retrieved and stored.
*
* @throws ApiKeyMissingException If the user does not have an API key configured.
* @throws CurlErrorException If there is an error during the API call.
* @throws Exception If there is an error decoding the JSON response or if the response is invalid.
* @param string $user The user whose logs should be fetched.
*
* @return void
*/
function firstRun($user) {
$apiKey = USER_KEYS[$user];
function backfillUserLogs($user) {
$url = 'https://api.torn.com/v2/user?selections=log&log=5850,5851';
$pdo = getDatabaseConnection();
$to = time();
do {
$url = "https://api.torn.com/v2/user?selections=log&log=5850,5851&to=$to";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch, CURLOPT_HTTPHEADER, [
'accept: application/json',
"Authorization: ApiKey $apiKey"
]
);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (empty($data['log'])) {
break;
}
foreach ($data['log'] as $key => $entry) {
$description = $entry['title'];
$timestamp = $entry['timestamp'];
$amount = isset($entry['data']['deposited']) ? $entry['data']['deposited'] : -$entry['data']['withdrawn'];
$stmt = $pdo->prepare('INSERT INTO vault (ID, user, timestamp, description, amount) VALUES (:id, :user, :timestamp, :description, :amount)');
$stmt->bindValue(':id', $key);
$stmt->bindValue(':user', $user);
$stmt->bindValue(':timestamp', $timestamp);
$stmt->bindValue(':description', $description);
$stmt->bindValue(':amount', $amount);
$stmt->execute();
}
$to = end($data['log'])['timestamp'];
} while (true);
$next = fetchAndStoreLogPage($pdo, $user, $url);
$url = $next;
} while ($next !== null);
}
/**
* Retrieves the user's log entries from the Torn API
* Synchronizes recent vault transactions for a user.
*
* @param string $user The user to retrieve the log for
* @param boolean $debug Whether to output debug information (default: false)
* On a non-empty database, fetches only entries newer than the user's
* most recent row. Falls back to full backfill when the database is
* empty.
*
* @throws Exception If the user does not have an API key configured,
* if the API call fails, or if the log data is invalid
* @param string $user The user whose logs should be synced.
*
* @return void
*/
function getLog($user, $debug = false) {
function syncUserLogs($user) {
if (dbNew()) {
backfillUserLogs($user);
return;
}
$pdo = getDatabaseConnection();
ensureUserHasApiKey($user);
$stmt = $pdo->prepare('SELECT MAX(timestamp) AS max_ts FROM vault WHERE user = :user');
$stmt->bindValue(':user', $user);
$stmt->execute();
$lastTs = (int)$stmt->fetch(PDO::FETCH_ASSOC)['max_ts'];
$stmt = $pdo->query("SELECT MAX(timestamp) AS max_timestamp FROM vault WHERE user = '$user'");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$url = "https://api.torn.com/v2/user?selections=log&log=5850,5851&from=" . ($lastTs + 1);
$from = $row['max_timestamp'];
$to = time();
$apiKey = USER_KEYS[$user];
$apiEndpoint = "https://api.torn.com/user/?selections=log&log=5850,5851&to=$to&from=$from&key=$apiKey";
$responseData = executeApiCall($apiEndpoint);
validateApiResponse($responseData);
$checkStmt = prepareCheckStatement($pdo);
$insertStmt = prepareInsertStatement($pdo);
processLogEntries($responseData['log'], $user, $checkStmt, $insertStmt, $debug);
do {
$next = fetchAndStoreLogPage($pdo, $user, $url);
$url = $next;
} while ($next !== null);
}
/**