roi.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 storedSortKey = localStorage.getItem('roi-sort-key') as any;
  40. if (storedSortKey === 'logistics_per_base') storedSortKey = 'normalized_logistics_per_base';
  41. let currentSortKey: keyof ProfitWithMetrics | 'outputs' = storedSortKey || 'break_even';
  42. let currentSortAsc: boolean = localStorage.getItem('roi-sort-asc') !== 'false';
  43. let headersInitialized = false;
  44. let metricControlsInitialized = false;
  45. let capexMetric: MetricType = (localStorage.getItem('roi-capex-metric') as MetricType) || 'vwap';
  46. let opexMetric: MetricType = (localStorage.getItem('roi-opex-metric') as MetricType) || 'vwap';
  47. let revenueMetric: MetricType = (localStorage.getItem('roi-revenue-metric') as MetricType) || 'vwap';
  48. let includeShips: boolean = localStorage.getItem('roi-include-ships') === 'true';
  49. let showNegativeProfit: boolean = localStorage.getItem('roi-show-negative') !== 'false';
  50. let workingCapitalDays: number = parseInt(localStorage.getItem('roi-working-capital') || '3', 10);
  51. let targetPermit: number = parseInt(localStorage.getItem('roi-target-permit') || '2', 10);
  52. async function render() {
  53. const tbody = document.querySelector('tbody')!;
  54. tbody.innerHTML = '';
  55. const cx = cxSelect.value;
  56. if (!roiCache[cx])
  57. roiCache[cx] = getROI(cx);
  58. const {lastModified, profits} = await roiCache[cx];
  59. if (!metricControlsInitialized) {
  60. const controls = document.createElement('div');
  61. controls.style.marginBottom = '15px';
  62. controls.innerHTML = `
  63. <label style="margin-right: 15px;">CapEx Price:
  64. <select id="capex-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  65. </label>
  66. <label style="margin-right: 15px;">OpEx Price:
  67. <select id="opex-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  68. </label>
  69. <label style="margin-right: 15px;">Revenue Price:
  70. <select id="revenue-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  71. </label>
  72. <label style="margin-right: 15px;">
  73. <input type="checkbox" id="include-ships"> Include Ship CapEx
  74. </label>
  75. <label style="margin-right: 15px;">
  76. <input type="checkbox" id="show-negative"> Show Negative Profit
  77. </label>
  78. <label style="margin-right: 15px;">
  79. Days OpEx: <input type="number" id="working-capital" min="0" step="1" style="width: 50px;">
  80. </label>
  81. <label>
  82. Permit Number: <input type="number" id="target-permit" min="1" step="1" style="width: 50px;">
  83. </label>
  84. `;
  85. const table = document.querySelector('table');
  86. if (table) table.parentNode?.insertBefore(controls, table);
  87. (document.getElementById('capex-metric') as HTMLSelectElement).value = capexMetric;
  88. (document.getElementById('opex-metric') as HTMLSelectElement).value = opexMetric;
  89. (document.getElementById('revenue-metric') as HTMLSelectElement).value = revenueMetric;
  90. (document.getElementById('include-ships') as HTMLInputElement).checked = includeShips;
  91. (document.getElementById('show-negative') as HTMLInputElement).checked = showNegativeProfit;
  92. (document.getElementById('working-capital') as HTMLInputElement).value = workingCapitalDays.toString();
  93. (document.getElementById('target-permit') as HTMLInputElement).value = targetPermit.toString();
  94. document.getElementById('capex-metric')!.addEventListener('change', (e) => {
  95. capexMetric = (e.target as HTMLSelectElement).value as MetricType;
  96. render();
  97. });
  98. document.getElementById('opex-metric')!.addEventListener('change', (e) => {
  99. opexMetric = (e.target as HTMLSelectElement).value as MetricType;
  100. render();
  101. });
  102. document.getElementById('revenue-metric')!.addEventListener('change', (e) => {
  103. revenueMetric = (e.target as HTMLSelectElement).value as MetricType;
  104. render();
  105. });
  106. document.getElementById('include-ships')!.addEventListener('change', (e) => {
  107. includeShips = (e.target as HTMLInputElement).checked;
  108. render();
  109. });
  110. document.getElementById('show-negative')!.addEventListener('change', (e) => {
  111. showNegativeProfit = (e.target as HTMLInputElement).checked;
  112. render();
  113. });
  114. document.getElementById('working-capital')!.addEventListener('change', (e) => {
  115. workingCapitalDays = parseInt((e.target as HTMLInputElement).value, 10);
  116. render();
  117. });
  118. document.getElementById('target-permit')!.addEventListener('change', (e) => {
  119. targetPermit = parseInt((e.target as HTMLInputElement).value, 10);
  120. render();
  121. });
  122. metricControlsInitialized = true;
  123. }
  124. if (!headersInitialized) {
  125. const ths = document.querySelectorAll('th');
  126. const keys: (keyof ProfitWithMetrics | 'outputs')[] = [
  127. 'outputs', 'expertise', 'profit_per_base', 'break_even',
  128. 'capex_val', 'opex_val', 'normalized_logistics_per_base', 'market_capacity_base'
  129. ];
  130. ths.forEach((th, i) => {
  131. if (keys[i]) {
  132. th.style.cursor = 'pointer';
  133. th.title = '';
  134. // EXTREME DETAIL: Updated the tooltip legend to explain that 100.0% is universally good.
  135. if (keys[i] === 'profit_per_base') {
  136. th.textContent = 'Profit/Base';
  137. th.dataset.tooltip = 'Click to sort.\n\nDaily profit scaled to a full 500-area planetary base.\n(Percentiles rank 100.0% as the most desirable outcome, i.e., highest profit or lowest cost.)';
  138. } else if (keys[i] === 'capex_val') {
  139. th.textContent = 'CapEx/Base';
  140. 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.';
  141. } else if (keys[i] === 'opex_val') {
  142. th.textContent = 'OpEx/Base';
  143. th.dataset.tooltip = 'Click to sort.\n\nDaily operational expenditure (input materials + worker consumables) scaled to a full 500-area planetary base.';
  144. } else if (keys[i] === 'normalized_logistics_per_base') {
  145. th.textContent = 'Logistics/Base';
  146. 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.\nSorts and percentiles are strictly normalized based on ship capacity limits (3000t or 1000m³).';
  147. } else if (keys[i] === 'market_capacity_base') {
  148. th.textContent = 'Market Cap (Bases)';
  149. 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.';
  150. } else if (keys[i] === 'break_even') {
  151. 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.';
  152. } else {
  153. th.dataset.tooltip = 'Click to sort.';
  154. }
  155. th.addEventListener('click', () => {
  156. if (currentSortKey === keys[i]) {
  157. currentSortAsc = !currentSortAsc;
  158. } else {
  159. currentSortKey = keys[i];
  160. currentSortAsc = keys[i] === 'break_even' ? true : false;
  161. }
  162. render();
  163. });
  164. }
  165. });
  166. headersInitialized = true;
  167. }
  168. const buildingTickers = new Set(profits.map(p => p.building));
  169. const buildings: {ticker: string, expertise: keyof typeof expertise}[] = Array.from(buildingTickers)
  170. .map((building) => ({ticker: building, expertise: profits.find(p => p.building === building)!.expertise}))
  171. .sort((a, b) => a.ticker.localeCompare(b.ticker));
  172. let selectedBuilding = buildingSelect.value || savedBuilding;
  173. let buildingFound = false;
  174. buildingSelect.innerHTML = '<option value="">(all)</option>';
  175. for (const building of buildings)
  176. if (expertiseSelect.value === '' || expertiseSelect.value === building.expertise) {
  177. const option = document.createElement('option');
  178. option.value = building.ticker;
  179. option.textContent = building.ticker;
  180. if (building.ticker === selectedBuilding) {
  181. buildingFound = true;
  182. option.selected = true;
  183. }
  184. buildingSelect.appendChild(option);
  185. }
  186. if (!buildingFound)
  187. selectedBuilding = '';
  188. savedBuilding = '';
  189. const filteredProfits = profits.filter(p => {
  190. const volumeRatio = p.output_per_day / p.average_traded_7d;
  191. if (!lowVolume.checked && volumeRatio > 0.05) return false;
  192. if (expertiseSelect.value !== '' && p.expertise !== expertiseSelect.value) return false;
  193. if (selectedBuilding !== '' && p.building !== selectedBuilding) return false;
  194. return true;
  195. });
  196. let profitsWithMetrics: ProfitWithMetrics[] = filteredProfits.map(p => {
  197. const bases = p.area / 500;
  198. const opex_val = p.opex[opexMetric] / bases;
  199. const revenue_val = p.revenue[revenueMetric] / bases;
  200. let capex_val = (p.capex[capexMetric] / bases) + (opex_val * workingCapitalDays);
  201. let hq_capex = 0;
  202. if (targetPermit >= 3) {
  203. const hqLevelStr = (targetPermit - 1).toString();
  204. if (p.hq_costs && p.hq_costs[hqLevelStr]) {
  205. hq_capex = p.hq_costs[hqLevelStr][capexMetric];
  206. capex_val += hq_capex;
  207. }
  208. }
  209. if (includeShips) {
  210. capex_val += p.ship_capex_per_base;
  211. }
  212. const profit_per_base = revenue_val - opex_val;
  213. const break_even = profit_per_base > 0 ? capex_val / profit_per_base : Infinity;
  214. return { ...p, capex_val, opex_val, revenue_val, profit_per_base, break_even, hq_capex };
  215. });
  216. if (!showNegativeProfit) {
  217. profitsWithMetrics = profitsWithMetrics.filter(p => p.profit_per_base > 0);
  218. }
  219. const numSort = (a: number, b: number) => (a < b ? -1 : a > b ? 1 : 0);
  220. const arrProfit = profitsWithMetrics.map(p => p.profit_per_base).sort(numSort);
  221. const arrBreak = profitsWithMetrics.map(p => p.break_even).sort(numSort);
  222. const arrCapex = profitsWithMetrics.map(p => p.capex_val).sort(numSort);
  223. const arrOpex = profitsWithMetrics.map(p => p.opex_val).sort(numSort);
  224. const arrLog = profitsWithMetrics.map(p => p.normalized_logistics_per_base).sort(numSort);
  225. const arrCap = profitsWithMetrics.map(p => p.market_capacity_base).sort(numSort);
  226. profitsWithMetrics.sort((a, b) => {
  227. let valA: any = a[currentSortKey as keyof ProfitWithMetrics];
  228. let valB: any = b[currentSortKey as keyof ProfitWithMetrics];
  229. if (currentSortKey === 'outputs') {
  230. valA = a.outputs.map(o => o.ticker).join(', ');
  231. valB = b.outputs.map(o => o.ticker).join(', ');
  232. }
  233. if (valA < valB) return currentSortAsc ? -1 : 1;
  234. if (valA > valB) return currentSortAsc ? 1 : -1;
  235. return 0;
  236. });
  237. for (const p of profitsWithMetrics) {
  238. const tr = document.createElement('tr');
  239. // EXTREME DETAIL: We explicitly route each column to its correct `invert` state.
  240. // Profit and Market Cap use `false` (highest numerical value = 100%).
  241. // Break Even, CapEx, OpEx, and Logistics use `true` (lowest numerical value = 100%).
  242. const pctProfit = getPercentile(p.profit_per_base, arrProfit, false);
  243. const pctBreak = getPercentile(p.break_even, arrBreak, true);
  244. const pctCapex = getPercentile(p.capex_val, arrCapex, true);
  245. const pctOpex = getPercentile(p.opex_val, arrOpex, true);
  246. const pctLog = getPercentile(p.normalized_logistics_per_base, arrLog, true);
  247. const pctCap = getPercentile(p.market_capacity_base, arrCap, false);
  248. tr.innerHTML = `
  249. <td>${p.outputs.map(o => o.ticker).join(', ')}</td>
  250. <td>${expertise[p.expertise]}</td>
  251. <td style="color: ${color(p.profit_per_base, 0, 150000)}">${formatSigFig(p.profit_per_base)} <span style="font-size: 0.85em; opacity: 0.6;">(${pctProfit})</span></td>
  252. <td><span style="color: ${color(p.break_even, 30, 3)}">${formatSigFig(p.break_even)}</span>d <span style="font-size: 0.85em; opacity: 0.6;">(${pctBreak})</span></td>
  253. <td style="color: ${color(p.capex_val, 3_000_000, 400_000)}">${formatSigFig(p.capex_val)} <span style="font-size: 0.85em; opacity: 0.6;">(${pctCapex})</span></td>
  254. <td style="color: ${color(p.opex_val, 400_000, 10_000)}">${formatSigFig(p.opex_val)} <span style="font-size: 0.85em; opacity: 0.6;">(${pctOpex})</span></td>
  255. <td style="color: ${color(p.normalized_logistics_per_base, 1.0, 0.1)}">${formatSigFig(p.logistics_per_base)} ${p.logistics_bottleneck} <span style="font-size: 0.85em; opacity: 0.6;">(${pctLog})</span></td>
  256. <td style="color: ${color(p.market_capacity_base, 0.04, 1)}">${formatSigFig(p.market_capacity_base)} <span style="font-size: 0.85em; opacity: 0.6;">(${pctCap})</span></td>
  257. `;
  258. const output = tr.querySelector('td')!;
  259. output.dataset.tooltip = p.recipe;
  260. const profitCell = tr.querySelectorAll('td')[2];
  261. const runs_per_base = p.runs_per_day / (p.area / 500);
  262. profitCell.dataset.tooltip = formatMatPrices(p.outputs, revenueMetric, runs_per_base) + '\n\n' +
  263. formatMatPrices(p.input_costs, opexMetric, runs_per_base) + '\n' +
  264. '+ worker consumables\n\n' +
  265. `(${formatSigFig(p.revenue_val)} - ${formatSigFig(p.opex_val)}) = ${formatSigFig(p.profit_per_base)}`;
  266. const capexCell = tr.querySelectorAll('td')[4];
  267. capexCell.dataset.tooltip = `Base Construction: ${formatSigFig(p.capex[capexMetric] / (p.area / 500))}`;
  268. capexCell.dataset.tooltip += `\nWorking Capital (${workingCapitalDays} days): ${formatSigFig(p.opex_val * workingCapitalDays)}`;
  269. if (p.hq_capex > 0) {
  270. capexCell.dataset.tooltip += `\nHQ Upgrade (Permit ${targetPermit}): ${formatSigFig(p.hq_capex)}`;
  271. }
  272. if (includeShips) {
  273. capexCell.dataset.tooltip += `\nShip CapEx: ${formatSigFig(p.ship_capex_per_base)} (${formatSigFig(p.ship_capex_per_base / 800_000)} ships)`;
  274. }
  275. const marketCell = tr.querySelectorAll('td')[7];
  276. 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`;
  277. tbody.appendChild(tr);
  278. }
  279. document.getElementById('last-updated')!.textContent =
  280. `last updated: ${lastModified.toLocaleString(undefined, {dateStyle: 'full', timeStyle: 'long', hour12: false})}`;
  281. saveState();
  282. }
  283. // EXTREME DETAIL: Added 'invert' boolean to flip logic for cost metrics.
  284. // Returns a heavily formatted string e.g., '99.0%'.
  285. function getPercentile(val: number, sortedArr: number[], invert: boolean = false): string {
  286. if (sortedArr.length < 2) return "100.0%";
  287. let less = 0;
  288. for (let i = 0; i < sortedArr.length; i++) {
  289. if (sortedArr[i] < val) less++;
  290. else break;
  291. }
  292. let decimal = less / (sortedArr.length - 1);
  293. if (invert) {
  294. decimal = 1.0 - decimal;
  295. }
  296. return (decimal * 100).toFixed(1) + "%";
  297. }
  298. function saveState() {
  299. localStorage.setItem('roi-cx', cxSelect.value);
  300. localStorage.setItem('roi-expertise', expertiseSelect.value);
  301. localStorage.setItem('roi-building', buildingSelect.value);
  302. localStorage.setItem('roi-low-volume', lowVolume.checked.toString());
  303. localStorage.setItem('roi-sort-key', currentSortKey);
  304. localStorage.setItem('roi-sort-asc', currentSortAsc.toString());
  305. localStorage.setItem('roi-capex-metric', capexMetric);
  306. localStorage.setItem('roi-opex-metric', opexMetric);
  307. localStorage.setItem('roi-revenue-metric', revenueMetric);
  308. localStorage.setItem('roi-include-ships', includeShips.toString());
  309. localStorage.setItem('roi-show-negative', showNegativeProfit.toString());
  310. localStorage.setItem('roi-working-capital', workingCapitalDays.toString());
  311. localStorage.setItem('roi-target-permit', targetPermit.toString());
  312. }
  313. function color(n: number, low: number, high: number): string {
  314. const scale = Math.min(Math.max((n - low) / (high - low), 0), 1);
  315. return `color-mix(in xyz, #0aa ${scale * 100}%, #f80)`;
  316. }
  317. function formatMatPrices(matPrices: MatPrice[], metric: MetricType, runs_per_day: number): string {
  318. return matPrices.map(({ticker, amount, vwap_7d, bid, ask}) => {
  319. const val = metric === 'vwap' ? vwap_7d : metric === 'bid' ? (bid ?? vwap_7d) : (ask ?? vwap_7d);
  320. const daily_amount = amount * runs_per_day;
  321. return `${ticker}: ${formatSigFig(daily_amount)} × ${formatSigFig(val)} = ${formatSigFig(daily_amount * val)}`;
  322. }).join('\n');
  323. }
  324. setupPopover();
  325. lowVolume.addEventListener('change', render);
  326. cxSelect.addEventListener('change', render);
  327. expertiseSelect.addEventListener('change', render);
  328. buildingSelect.addEventListener('change', render);
  329. render();
  330. interface Metrics {
  331. vwap: number;
  332. bid: number;
  333. ask: number;
  334. }
  335. interface Profit {
  336. outputs: MatPrice[]
  337. recipe: string
  338. expertise: keyof typeof expertise
  339. building: string
  340. area: number
  341. capex: Metrics
  342. opex: Metrics
  343. revenue: Metrics
  344. input_costs: MatPrice[]
  345. runs_per_day: number
  346. logistics_per_base: number
  347. normalized_logistics_per_base: number
  348. logistics_bottleneck: string
  349. output_per_day: number
  350. average_traded_7d: number
  351. market_capacity_base: number
  352. ship_capex_per_base: number
  353. hq_costs: Record<string, Metrics>
  354. }
  355. interface ProfitWithMetrics extends Profit {
  356. capex_val: number;
  357. opex_val: number;
  358. revenue_val: number;
  359. profit_per_day: number;
  360. profit_per_base: number;
  361. break_even: number;
  362. hq_capex: number;
  363. }
  364. interface MatPrice {
  365. ticker: string
  366. amount: number
  367. vwap_7d: number
  368. bid: number | null
  369. ask: number | null
  370. }
  371. interface Building {
  372. building_type: 'INFRASTRUCTURE' | 'PLANETARY' | 'PRODUCTION';
  373. building_ticker: string;
  374. expertise: keyof typeof expertise;
  375. }