Streamlined Upkeep Manager 1.5

Manage and pay upkeeps more efficiently

  1. // ==UserScript==
  2. // @name Streamlined Upkeep Manager 1.5
  3. // @namespace upkeep,zero.torn
  4. // @version 1.5
  5. // @description Manage and pay upkeeps more efficiently
  6. // @author Combined by Aria and Jeff Bezas
  7. // @match https://www.torn.com/index.php
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=torn.com
  9. // @grant none
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. (function($) {
  14. 'use strict';
  15.  
  16. // API token management
  17. function manageApiToken() {
  18. let apiToken = localStorage.getItem('tornApiToken');
  19. if (!apiToken) {
  20. apiToken = prompt("Please enter your Torn API token key:");
  21. if (apiToken) {
  22. localStorage.setItem('tornApiToken', apiToken);
  23. }
  24. }
  25. return apiToken;
  26. }
  27. function getRFC() {
  28. var rfc = $.cookie('rfc_v');
  29. if (!rfc) {
  30. var cookies = document.cookie.split('; ');
  31. for (var i in cookies) {
  32. var cookie = cookies[i].split('=');
  33. if (cookie[0] == 'rfc_v') {
  34. return cookie[1];
  35. }
  36. }
  37. }
  38. return rfc;
  39. }
  40.  
  41. function addUpkeepButtons(apiToken, button) {
  42. console.log("Adding Buttons");
  43. if (button == 0) {
  44. const upkeepButton = $('<button id="Upkeep" style="color: var(--default-blue-color); cursor: pointer; margin-right: 10px;">Pay Upkeep</button>');
  45. $('div.content-title > h4').append(upkeepButton);
  46. upkeepButton.on('click', async () => {
  47. //alert("2 aler");
  48. let flag = localStorage.getItem('Flag');
  49. if (flag == 0){
  50. alert("Unable to do that while traveling abroad.");
  51. return;
  52. }
  53. const enteredAmount = Number($('#amountInput').val());
  54. if (enteredAmount > 0) {
  55. const propertyId = await fetchPropertyId(apiToken);
  56. pay(enteredAmount, propertyId);
  57. let currentAmt = localStorage.getItem('FeesAmount');
  58. let newVal = currentAmt - enteredAmount;
  59. //alert(newVal);
  60. localStorage.setItem('FeesAmount', newVal);
  61. alert("Payment successful");
  62. $('#Upkeep').text(`Pay Upkeep | Total: $${newVal}`);
  63. } else {
  64. alert("Please enter a valid amount.");
  65. }
  66. });
  67. return upkeepButton;
  68. }
  69. if (button == 1) {
  70. const upkeepButton2 = $('<button id="Upkeep2" style="color: var(--default-blue-color); cursor: pointer; margin-right: 10px;">Check Balance</button>');
  71. $('div.content-title > h4').append(upkeepButton2);
  72. upkeepButton2.on('click', () => {
  73. let balance = localStorage.getItem('Balance') || 0;
  74. let balance2 = balance.toString().replace(/,/g, ''); // Remove commas
  75.  
  76. let feesAmt2 = localStorage.getItem('FeesAmount'); //Attemot to get last fee amount before going over seas
  77. let number2 = feesAmt2.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  78. //Testing
  79.  
  80. balance = Number(balance);
  81. feesAmt2 = Number(feesAmt2);
  82. //alert(`Fees: ${feesAmt2} and Bal: ${number3}`);
  83. let dif = feesAmt2-balance; //Number4 = Upkeep Total - Balance, if this is less than 0, should equal to Upkeep Total
  84. if (dif < 0){
  85. balance2 = feesAmt2;
  86. }
  87. alert(balance2); // Check if upkeep-bal is less than 0, if so, pay upkeep instead
  88.  
  89. //let formattedAmount = balance.replace(/^.|.$/g, '').trim();
  90.  
  91. //alert(balance2);
  92. $('#amountInput').val(balance2);
  93. let feesAmt = localStorage.getItem('FeesAmount');
  94. let formattedNumber = feesAmt.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  95. $('#Upkeep').text(`Pay Upkeep | Total: $${formattedNumber}`);
  96.  
  97. //alert(`Current Balance: $${balance}`);
  98. });
  99. return upkeepButton2;
  100. }
  101. if (button == 2) {
  102. const resultSpan = $('<span id="Result" style="font-size: 12px; font-weight: 100;"></span>');
  103. $('div.content-title > h4').append(resultSpan);
  104. return resultSpan;
  105. }
  106. if (button == 3) {
  107. const resetButton = $('<button id="ResetKey" style="color: var(--default-red-color); cursor: pointer;">Reset API Key</button>');
  108. resetButton.on('click', () => {
  109. const newApiToken = prompt("Please enter your new Torn API token key:");
  110. if (newApiToken) {
  111. localStorage.setItem('tornApiToken', newApiToken);
  112. $('#Result').text('API token updated.').css('color', 'green');
  113. } else {
  114. $('#Result').text('No API token provided.').css('color', 'red');
  115. }
  116. });
  117. $('div.content-title > h4').append(resetButton);
  118. }
  119. }
  120. // Fetch Property ID
  121. async function fetchPropertyId(apiToken) {
  122. console.log("Fetching Property ID...");
  123. const apiURL = `https://api.torn.com/user/?key=${apiToken}&comment=StreamlinedUpkeepManager&selections=properties`;
  124. try {
  125. const response = await fetch(apiURL);
  126. const data = await response.json();
  127. const propertyIds = Object.keys(data.properties);
  128. //console.log("Fetched Property IDs:", propertyIds);
  129. return propertyIds.length > 0 ? propertyIds[0] : null;
  130. } catch (error) {
  131. console.error('Error fetching property ID:', error);
  132. return null;
  133. }
  134. }
  135.  
  136. // Pay upkeep function
  137. function pay(toPay, propertyID) {
  138. console.log(`Attempting to pay upkeep of: $${toPay} for Property ID: ${propertyID}`);
  139. $("#Upkeep").text("Processing...").prop("disabled", true);
  140.  
  141. $.post(`https://www.torn.com/properties.php?rfcv=${getRFC()}`, {
  142. step: "upkeepProperty",
  143. pay: toPay,
  144. ID: propertyID
  145. })
  146. .done(function(response) {
  147. response = JSON.parse(response);
  148. if (response.success) {
  149. console.log("Payment successful");
  150. //$("#Upkeep").text("Paid");
  151. } else {
  152. console.error("Payment failed:", response.error);
  153. alert("Payment failed:", response.error);
  154. //$("#U").text("Payment Failed");
  155. }
  156. })
  157. .fail(function() {
  158. console.error("Network error during payment");
  159. $("#Upkeep").text("Payment Failed");
  160. })
  161. .always(function() {
  162. $("#Upkeep").prop("disabled", false);
  163. });
  164. }
  165.  
  166. // Function to fetch and format amount
  167. function fetchAndFormatAmountFromFeesSpan(feesSpan) {
  168. const textContent = feesSpan.textContent;
  169. const amountMatch = textContent.match(/\$([\d,]+)/); // Updated regex to match dollar sign
  170.  
  171. if (amountMatch && amountMatch[1]) {
  172. const amount = amountMatch[1].replace(/,/g, ''); // Remove commas
  173. console.log("Extracted Amount: ", amount); // Log the number without commas
  174. localStorage.setItem('FeesAmount', amount); // Save to local storage
  175. return Number(amount);
  176. } else {
  177. console.log("Amount not found in text content.", amountMatch);
  178. return 0; // Return 0 if not found
  179. }
  180. }
  181.  
  182. // Main function to run the script
  183. async function main() {
  184. console.log("Starting...");
  185. const apiToken = manageApiToken();
  186. if (!apiToken) {
  187. //apiToken = 0;
  188. addUpkeepButtons(0, 2);
  189. $('#Result').text('No API token provided.').css('color', 'red');
  190. return;
  191. }
  192.  
  193. const bodyElement = document.querySelector("#body");
  194. if (bodyElement && bodyElement.getAttribute("data-traveling") === 'true' || (document.querySelector("#mainContainer > div.content-wrapper.autumn.travelling"))) { // Travel check
  195. //$('#Result').text("You can't do that while Traveling.").css('color', 'red');
  196. let feesAmt2 = localStorage.getItem('FeesAmount'); //Attemot to get last fee amount before going over seas
  197. let number2 = feesAmt2.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  198. //Testing
  199. let balance = localStorage.getItem("Balance");
  200. balance = balance.toString().replace(/,/g, '');
  201. balance = Number(balance);
  202. feesAmt2 = Number(feesAmt2);
  203. //alert(`Fees: ${feesAmt2} and Bal: ${number3}`);
  204. let dif = feesAmt2-balance; //Number4 = Upkeep Total - Balance, if this is less than 0, should equal to Upkeep Total
  205. //number4 = number4.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  206. //alert(dif);
  207.  
  208. const flag = 0;
  209. localStorage.setItem('Flag', flag);
  210. addUpkeepButtons(apiToken, 0);
  211. $('#Upkeep').text(`Current Upkeep: $${number2}\nYou can pay when you get back`);
  212. return; // Exit the function if traveling
  213. }
  214. const resultSpan = addUpkeepButtons(apiToken, 2); // Create result span
  215.  
  216.  
  217. const feesSpan = document.querySelector("#item20230685 > div.bottom-round > div > ul > li.last > span.desc");
  218. if (feesSpan) {
  219. const toPay = fetchAndFormatAmountFromFeesSpan(feesSpan); // Get the amount from feesSpan
  220.  
  221. console.log("To Pay: ", toPay); // Log the amount to pay
  222.  
  223.  
  224. // Create input field and buttons
  225. const upkeepButton = addUpkeepButtons(apiToken, 0); // Add the first upkeep button
  226. const upkeepButton2 = addUpkeepButtons(apiToken, 1); // Add the second upkeep button
  227. const inputField = $('<input type="number" id="amountInput" placeholder="Enter amount" />');
  228. $('div.content-title > h4').append(inputField);
  229. //addUpkeepButtons(apiToken, 0);
  230.  
  231. // Append input field and button to the result area
  232. //$('#Result').append(inputField);
  233.  
  234. // Event listener for Enter key press
  235. inputField.on('keypress', function(event) {
  236. if (event.which === 13) { // Enter key
  237. const enteredAmount = Number($(this).val());
  238. if (enteredAmount > 0) {
  239. pay(enteredAmount, propertyId); // Call pay function with entered amount
  240.  
  241. let newVal = toPay - enteredAmount;
  242. localStorage.setItem('FeesAmount', newVal);
  243. let formattedNumber = newVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  244. alert("Payment successful");
  245. $('#Upkeep').text(`Pay Upkeep | Total: $${formattedNumber}`);
  246. } else {
  247. alert("Please enter a valid amount.");
  248. }
  249. }
  250. });
  251.  
  252. // Initialize the Pay Upkeep button
  253. upkeepButton.on('click', function() {
  254. alert("1 aler");
  255. const enteredAmount = Number(inputField.val());
  256. if (enteredAmount > 0) {
  257. pay(enteredAmount, propertyId); // Call pay function with entered amount
  258. } else {
  259. alert("Please enter a valid amount.");
  260. }
  261. });
  262. } else {
  263. console.log("Fees span element not found.");
  264. }
  265.  
  266. const balSpan = document.querySelector("#user-money");
  267. if (balSpan) {
  268. let balance = balSpan.textContent;
  269. balance = balance.match(/\$([\d,]+)/);
  270. console.log("User Balance: ", balance[1]); //Remember to set value without commas, or always set with commas, only when need int, replace commas, then Number()
  271. localStorage.setItem('Balance', balance[1]);
  272. //addUpkeepButtons(apiToken, 1);
  273.  
  274. } else {
  275. console.log("Balance span element not found.");
  276. }
  277.  
  278. const propertyId = await fetchPropertyId(apiToken);
  279. if (!propertyId) {
  280. $('#Result').text('Failed to retrieve property ID.').css('color', 'red');
  281. return;
  282. }
  283. }
  284.  
  285. // Call main function to start the script
  286. main();
  287. })(jQuery);