roi.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import {setupPopover} from './popover';
  2. const roiCache: Record<string, Promise<{lastModified: Date, profits: Profit[]}>> = {};
  3. async function getROI(cx: string) {
  4. const response = await fetch(`/roi_${cx.toLowerCase()}.json`);
  5. const lastModified = new Date(response.headers.get('last-modified')!);
  6. const profits = await response.json();
  7. return {lastModified, profits};
  8. }
  9. type MetricType = 'vwap' | 'bid' | 'ask';
  10. const lowVolume = document.querySelector('input#low-volume') as HTMLInputElement;
  11. const cxSelect = document.querySelector('select#cx') as HTMLSelectElement;
  12. const expertise = {
  13. AGRICULTURE: 'agri',
  14. CHEMISTRY: 'chem',
  15. CONSTRUCTION: 'const',
  16. ELECTRONICS: 'elec',
  17. FOOD_INDUSTRIES: 'food ind',
  18. FUEL_REFINING: 'fuel',
  19. MANUFACTURING: 'mfg',
  20. METALLURGY: 'metal',
  21. RESOURCE_EXTRACTION: 'res ext',
  22. } as const;
  23. const expertiseSelect = document.querySelector('select#expertise') as HTMLSelectElement;
  24. for (const key of Object.keys(expertise)) {
  25. const option = document.createElement('option');
  26. option.value = key;
  27. option.textContent = key.replace('_', ' ').toLowerCase();
  28. expertiseSelect.appendChild(option);
  29. }
  30. const buildingSelect = document.querySelector('select#building') as HTMLSelectElement;
  31. const formatSigFig = new Intl.NumberFormat(undefined, {
  32. notation: 'compact',
  33. maximumSignificantDigits: 3,
  34. }).format;
  35. if (localStorage.getItem('roi-cx')) cxSelect.value = localStorage.getItem('roi-cx')!;
  36. if (localStorage.getItem('roi-expertise')) expertiseSelect.value = localStorage.getItem('roi-expertise')!;
  37. if (localStorage.getItem('roi-low-volume')) lowVolume.checked = localStorage.getItem('roi-low-volume') === 'true';
  38. let savedBuilding = localStorage.getItem('roi-building') || '';
  39. let currentSortKey: keyof ProfitWithMetrics | 'outputs' = (localStorage.getItem('roi-sort-key') as any) || 'break_even';
  40. let currentSortAsc: boolean = localStorage.getItem('roi-sort-asc') !== 'false';
  41. let headersInitialized = false;
  42. let metricControlsInitialized = false;
  43. let capexMetric: MetricType = (localStorage.getItem('roi-capex-metric') as MetricType) || 'vwap';
  44. let opexMetric: MetricType = (localStorage.getItem('roi-opex-metric') as MetricType) || 'vwap';
  45. let revenueMetric: MetricType = (localStorage.getItem('roi-revenue-metric') as MetricType) || 'vwap';
  46. let includeShips: boolean = localStorage.getItem('roi-include-ships') === 'true';
  47. let workingCapitalDays: number = parseInt(localStorage.getItem('roi-working-capital') || '3', 10);
  48. // EXTREME DETAIL: Track the state of the Target Permit. Defaults to 2 (the standard starting permits in PRUN).
  49. let targetPermit: number = parseInt(localStorage.getItem('roi-target-permit') || '2', 10);
  50. async function render() {
  51. const tbody = document.querySelector('tbody')!;
  52. tbody.innerHTML = '';
  53. const cx = cxSelect.value;
  54. if (!roiCache[cx])
  55. roiCache[cx] = getROI(cx);
  56. const {lastModified, profits} = await roiCache[cx];
  57. if (!metricControlsInitialized) {
  58. const controls = document.createElement('div');
  59. controls.style.marginBottom = '15px';
  60. // EXTREME DETAIL: Injected the new `<input type="number">` for Target Permit.
  61. controls.innerHTML = `
  62. <label style="margin-right: 15px;">CapEx Price:
  63. <select id="capex-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  64. </label>
  65. <label style="margin-right: 15px;">OpEx Price:
  66. <select id="opex-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  67. </label>
  68. <label style="margin-right: 15px;">Revenue Price:
  69. <select id="revenue-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  70. </label>
  71. <label style="margin-right: 15px;">
  72. <input type="checkbox" id="include-ships"> Include Ship CapEx
  73. </label>
  74. <label style="margin-right: 15px;">
  75. <input type="number" id="working-capital" min="0" step="1" style="width: 50px;"> Days OpEx
  76. </label>
  77. <label>
  78. <input type="number" id="target-permit" min="1" step="1" style="width: 50px;"> Target Permit
  79. </label>
  80. `;
  81. const table = document.querySelector('table');
  82. if (table) table.parentNode?.insertBefore(controls, table);
  83. (document.getElementById('capex-metric') as HTMLSelectElement).value = capexMetric;
  84. (document.getElementById('opex-metric') as HTMLSelectElement).value = opexMetric;
  85. (document.getElementById('revenue-metric') as HTMLSelectElement).value = revenueMetric;
  86. (document.getElementById('include-ships') as HTMLInputElement).checked = includeShips;
  87. (document.getElementById('working-capital') as HTMLInputElement).value = workingCapitalDays.toString();
  88. (document.getElementById('target-permit') as HTMLInputElement).value = targetPermit.toString();
  89. document.getElementById('capex-metric')!.addEventListener('change', (e) => {
  90. capexMetric = (e.target as HTMLSelectElement).value as MetricType;
  91. render();
  92. });
  93. document.getElementById('opex-metric')!.addEventListener('change', (e) => {
  94. opexMetric = (e.target as HTMLSelectElement).value as MetricType;
  95. render();
  96. });
  97. document.getElementById('revenue-metric')!.addEventListener('change', (e) => {
  98. revenueMetric = (e.target as HTMLSelectElement).value as MetricType;
  99. render();
  100. });
  101. document.getElementById('include-ships')!.addEventListener('change', (e) => {
  102. includeShips = (e.target as HTMLInputElement).checked;
  103. render();
  104. });
  105. document.getElementById('working-capital')!.addEventListener('change', (e) => {
  106. workingCapitalDays = parseInt((e.target as HTMLInputElement).value, 10);
  107. render();
  108. });
  109. document.getElementById('target-permit')!.addEventListener('change', (e) => {
  110. targetPermit = parseInt((e.target as HTMLInputElement).value, 10);
  111. render();
  112. });
  113. metricControlsInitialized = true;
  114. }
  115. if (!headersInitialized) {
  116. const ths = document.querySelectorAll('th');
  117. const keys: (keyof ProfitWithMetrics | 'outputs')[] = [
  118. 'outputs', 'expertise', 'profit_per_base', 'break_even',
  119. 'capex_val', 'opex_val', 'logistics_per_base', 'market_capacity_base'
  120. ];
  121. ths.forEach((th, i) => {
  122. if (keys[i]) {
  123. th.style.cursor = 'pointer';
  124. th.title = '';
  125. if (keys[i] === 'profit_per_base') {
  126. th.textContent = 'Profit/Base';
  127. th.dataset.tooltip = 'Click to sort.\n\nDaily profit scaled to a full 500-area planetary base.';
  128. } else if (keys[i] === 'capex_val') {
  129. th.textContent = 'CapEx/Base';
  130. th.dataset.tooltip = 'Click to sort.\n\nTotal capital expenditure scaled to a full 500-area planetary base.\nIncludes base construction, working capital (days of OpEx), optional HQ Upgrade materials for the target permit, and optional Ship CapEx.';
  131. } else if (keys[i] === 'opex_val') {
  132. th.textContent = 'OpEx/Base';
  133. th.dataset.tooltip = 'Click to sort.\n\nDaily operational expenditure (input materials + worker consumables) scaled to a full 500-area planetary base.';
  134. } else if (keys[i] === 'logistics_per_base') {
  135. th.textContent = 'Logistics/Base';
  136. th.dataset.tooltip = 'Click to sort.\n\nDaily logistics bottleneck scaled to a full 500-area planetary base. The suffix indicates whether Weight (t) or Volume (m³) of Inputs (I) or Outputs (O) is the limiting bottleneck.';
  137. } else if (keys[i] === 'market_capacity_base') {
  138. th.textContent = 'Market Cap (Bases)';
  139. th.dataset.tooltip = 'Click to sort.\n\nMarket Capacity: 7-day average traded volume ÷ daily output per base. Indicates how many full 500-area bases you can build before saturating the market.';
  140. } else if (keys[i] === 'break_even') {
  141. th.dataset.tooltip = 'Click to sort.\n\nBreak Even: CapEx ÷ daily profit. Note that CapEx dynamically includes working capital and HQ upgrades to accurately reflect operational readiness.';
  142. } else {
  143. th.dataset.tooltip = 'Click to sort.';
  144. }
  145. th.addEventListener('click', () => {
  146. if (currentSortKey === keys[i]) {
  147. currentSortAsc = !currentSortAsc;
  148. } else {
  149. currentSortKey = keys[i];
  150. currentSortAsc = keys[i] === 'break_even' ? true : false;
  151. }
  152. render();
  153. });
  154. }
  155. });
  156. headersInitialized = true;
  157. }
  158. const buildingTickers = new Set(profits.map(p => p.building));
  159. const buildings: {ticker: string, expertise: keyof typeof expertise}[] = Array.from(buildingTickers)
  160. .map((building) => ({ticker: building, expertise: profits.find(p => p.building === building)!.expertise}))
  161. .sort((a, b) => a.ticker.localeCompare(b.ticker));
  162. let selectedBuilding = buildingSelect.value || savedBuilding;
  163. let buildingFound = false;
  164. buildingSelect.innerHTML = '<option value="">(all)</option>';
  165. for (const building of buildings)
  166. if (expertiseSelect.value === '' || expertiseSelect.value === building.expertise) {
  167. const option = document.createElement('option');
  168. option.value = building.ticker;
  169. option.textContent = building.ticker;
  170. if (building.ticker === selectedBuilding) {
  171. buildingFound = true;
  172. option.selected = true;
  173. }
  174. buildingSelect.appendChild(option);
  175. }
  176. if (!buildingFound)
  177. selectedBuilding = '';
  178. savedBuilding = '';
  179. const filteredProfits = profits.filter(p => {
  180. const volumeRatio = p.output_per_day / p.average_traded_7d;
  181. if (!lowVolume.checked && volumeRatio > 0.05) return false;
  182. if (expertiseSelect.value !== '' && p.expertise !== expertiseSelect.value) return false;
  183. if (selectedBuilding !== '' && p.building !== selectedBuilding) return false;
  184. return true;
  185. });
  186. const profitsWithMetrics: ProfitWithMetrics[] = filteredProfits.map(p => {
  187. const bases = p.area / 500;
  188. const opex_val = p.opex[opexMetric] / bases;
  189. const revenue_val = p.revenue[revenueMetric] / bases;
  190. let capex_val = (p.capex[capexMetric] / bases) + (opex_val * workingCapitalDays);
  191. // EXTREME DETAIL: We intercept the HQ permit cost here.
  192. // Permits 1 & 2 are free. To unlock permit 3, you must upgrade HQ to Level 2.
  193. // We map the user input directly to the JSON string keys retrieved from GitHub.
  194. let hq_capex = 0;
  195. if (targetPermit >= 3) {
  196. const hqLevelStr = (targetPermit - 1).toString();
  197. if (p.hq_costs && p.hq_costs[hqLevelStr]) {
  198. hq_capex = p.hq_costs[hqLevelStr][capexMetric];
  199. capex_val += hq_capex;
  200. }
  201. }
  202. if (includeShips) {
  203. capex_val += p.ship_capex_per_base;
  204. }
  205. const profit_per_base = revenue_val - opex_val;
  206. const break_even = profit_per_base > 0 ? capex_val / profit_per_base : Infinity;
  207. return { ...p, capex_val, opex_val, revenue_val, profit_per_base, break_even, hq_capex };
  208. });
  209. profitsWithMetrics.sort((a, b) => {
  210. let valA: any = a[currentSortKey as keyof ProfitWithMetrics];
  211. let valB: any = b[currentSortKey as keyof ProfitWithMetrics];
  212. if (currentSortKey === 'outputs') {
  213. valA = a.outputs.map(o => o.ticker).join(', ');
  214. valB = b.outputs.map(o => o.ticker).join(', ');
  215. }
  216. if (valA < valB) return currentSortAsc ? -1 : 1;
  217. if (valA > valB) return currentSortAsc ? 1 : -1;
  218. return 0;
  219. });
  220. for (const p of profitsWithMetrics) {
  221. const tr = document.createElement('tr');
  222. tr.innerHTML = `
  223. <td>${p.outputs.map(o => o.ticker).join(', ')}</td>
  224. <td>${expertise[p.expertise]}</td>
  225. <td style="color: ${color(p.profit_per_base, 0, 150000)}">${formatSigFig(p.profit_per_base)}</td>
  226. <td><span style="color: ${color(p.break_even, 30, 3)}">${formatSigFig(p.break_even)}</span>d</td>
  227. <td style="color: ${color(p.capex_val, 3_000_000, 400_000)}">${formatSigFig(p.capex_val)}</td>
  228. <td style="color: ${color(p.opex_val, 400_000, 10_000)}">${formatSigFig(p.opex_val)}</td>
  229. <td style="color: ${color(p.logistics_per_base, 1000, 100)}">${formatSigFig(p.logistics_per_base)} ${p.logistics_bottleneck}</td>
  230. <td style="color: ${color(p.market_capacity_base, 0.04, 1)}">${formatSigFig(p.market_capacity_base)}</td>
  231. `;
  232. const output = tr.querySelector('td')!;
  233. output.dataset.tooltip = p.recipe;
  234. const profitCell = tr.querySelectorAll('td')[2];
  235. const runs_per_base = p.runs_per_day / (p.area / 500);
  236. profitCell.dataset.tooltip = formatMatPrices(p.outputs, revenueMetric, runs_per_base) + '\n\n' +
  237. formatMatPrices(p.input_costs, opexMetric, runs_per_base) + '\n' +
  238. '+ worker consumables\n\n' +
  239. `(${formatSigFig(p.revenue_val)} - ${formatSigFig(p.opex_val)}) = ${formatSigFig(p.profit_per_base)}`;
  240. const capexCell = tr.querySelectorAll('td')[4];
  241. capexCell.dataset.tooltip = `Base Construction: ${formatSigFig(p.capex[capexMetric] / (p.area / 500))}`;
  242. capexCell.dataset.tooltip += `\nWorking Capital (${workingCapitalDays} days): ${formatSigFig(p.opex_val * workingCapitalDays)}`;
  243. // EXTREME DETAIL: Dynamically inject the HQ cost into the tooltip if the user requested Permit 3 or higher.
  244. if (p.hq_capex > 0) {
  245. capexCell.dataset.tooltip += `\nHQ Upgrade (Permit ${targetPermit}): ${formatSigFig(p.hq_capex)}`;
  246. }
  247. if (includeShips) {
  248. capexCell.dataset.tooltip += `\nShip CapEx: ${formatSigFig(p.ship_capex_per_base)} (${formatSigFig(p.ship_capex_per_base / 800_000)} ships)`;
  249. }
  250. const marketCell = tr.querySelectorAll('td')[7];
  251. marketCell.dataset.tooltip = `Market Capacity: ${formatSigFig(p.average_traded_7d)} traded/day ÷ ${formatSigFig(p.output_per_day / (p.area / 500))} produced/day/base = ${formatSigFig(p.market_capacity_base)} equivalent bases`;
  252. tbody.appendChild(tr);
  253. }
  254. document.getElementById('last-updated')!.textContent =
  255. `last updated: ${lastModified.toLocaleString(undefined, {dateStyle: 'full', timeStyle: 'long', hour12: false})}`;
  256. saveState();
  257. }
  258. function saveState() {
  259. localStorage.setItem('roi-cx', cxSelect.value);
  260. localStorage.setItem('roi-expertise', expertiseSelect.value);
  261. localStorage.setItem('roi-building', buildingSelect.value);
  262. localStorage.setItem('roi-low-volume', lowVolume.checked.toString());
  263. localStorage.setItem('roi-sort-key', currentSortKey);
  264. localStorage.setItem('roi-sort-asc', currentSortAsc.toString());
  265. localStorage.setItem('roi-capex-metric', capexMetric);
  266. localStorage.setItem('roi-opex-metric', opexMetric);
  267. localStorage.setItem('roi-revenue-metric', revenueMetric);
  268. localStorage.setItem('roi-include-ships', includeShips.toString());
  269. localStorage.setItem('roi-working-capital', workingCapitalDays.toString());
  270. localStorage.setItem('roi-target-permit', targetPermit.toString());
  271. }
  272. function color(n: number, low: number, high: number): string {
  273. const scale = Math.min(Math.max((n - low) / (high - low), 0), 1);
  274. return `color-mix(in xyz, #0aa ${scale * 100}%, #f80)`;
  275. }
  276. function formatMatPrices(matPrices: MatPrice[], metric: MetricType, runs_per_day: number): string {
  277. return matPrices.map(({ticker, amount, vwap_7d, bid, ask}) => {
  278. const val = metric === 'vwap' ? vwap_7d : metric === 'bid' ? (bid ?? vwap_7d) : (ask ?? vwap_7d);
  279. const daily_amount = amount * runs_per_day;
  280. return `${ticker}: ${formatSigFig(daily_amount)} × ${formatSigFig(val)} = ${formatSigFig(daily_amount * val)}`;
  281. }).join('\n');
  282. }
  283. setupPopover();
  284. lowVolume.addEventListener('change', render);
  285. cxSelect.addEventListener('change', render);
  286. expertiseSelect.addEventListener('change', render);
  287. buildingSelect.addEventListener('change', render);
  288. render();
  289. interface Metrics {
  290. vwap: number;
  291. bid: number;
  292. ask: number;
  293. }
  294. interface Profit {
  295. outputs: MatPrice[]
  296. recipe: string
  297. expertise: keyof typeof expertise
  298. building: string
  299. area: number
  300. capex: Metrics
  301. opex: Metrics
  302. revenue: Metrics
  303. input_costs: MatPrice[]
  304. runs_per_day: number
  305. logistics_per_base: number
  306. logistics_bottleneck: string
  307. output_per_day: number
  308. average_traded_7d: number
  309. market_capacity_base: number
  310. ship_capex_per_base: number
  311. hq_costs: Record<string, Metrics> // Added typing for the precalculated HQ pricing dictionary
  312. }
  313. interface ProfitWithMetrics extends Profit {
  314. capex_val: number;
  315. opex_val: number;
  316. revenue_val: number;
  317. profit_per_day: number;
  318. profit_per_base: number;
  319. break_even: number;
  320. hq_capex: number; // Added to interface to pass to the tooltip generator
  321. }
  322. interface MatPrice {
  323. ticker: string
  324. amount: number
  325. vwap_7d: number
  326. bid: number | null
  327. ask: number | null
  328. }
  329. interface Building {
  330. building_type: 'INFRASTRUCTURE' | 'PLANETARY' | 'PRODUCTION';
  331. building_ticker: string;
  332. expertise: keyof typeof expertise;
  333. }