roi.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 formatDecimal = new Intl.NumberFormat(undefined,
  32. {maximumFractionDigits: 2, maximumSignificantDigits: 6, roundingPriority: 'lessPrecision'}).format;
  33. const formatWhole = new Intl.NumberFormat(undefined, {maximumFractionDigits: 0}).format;
  34. if (localStorage.getItem('roi-cx')) cxSelect.value = localStorage.getItem('roi-cx')!;
  35. if (localStorage.getItem('roi-expertise')) expertiseSelect.value = localStorage.getItem('roi-expertise')!;
  36. if (localStorage.getItem('roi-low-volume')) lowVolume.checked = localStorage.getItem('roi-low-volume') === 'true';
  37. let savedBuilding = localStorage.getItem('roi-building') || '';
  38. let currentSortKey: keyof ProfitWithMetrics | 'outputs' = (localStorage.getItem('roi-sort-key') as any) || 'break_even';
  39. let currentSortAsc: boolean = localStorage.getItem('roi-sort-asc') !== 'false';
  40. let headersInitialized = false;
  41. let metricControlsInitialized = false;
  42. let capexMetric: MetricType = (localStorage.getItem('roi-capex-metric') as MetricType) || 'vwap';
  43. let opexMetric: MetricType = (localStorage.getItem('roi-opex-metric') as MetricType) || 'vwap';
  44. let revenueMetric: MetricType = (localStorage.getItem('roi-revenue-metric') as MetricType) || 'vwap';
  45. async function render() {
  46. const tbody = document.querySelector('tbody')!;
  47. tbody.innerHTML = '';
  48. const cx = cxSelect.value;
  49. if (!roiCache[cx])
  50. roiCache[cx] = getROI(cx);
  51. const {lastModified, profits} = await roiCache[cx];
  52. if (!metricControlsInitialized) {
  53. const controls = document.createElement('div');
  54. controls.style.marginBottom = '15px';
  55. controls.innerHTML = `
  56. <label style="margin-right: 15px;">CapEx Price:
  57. <select id="capex-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  58. </label>
  59. <label style="margin-right: 15px;">OpEx Price:
  60. <select id="opex-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  61. </label>
  62. <label>Revenue (Outputs) Price:
  63. <select id="revenue-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  64. </label>
  65. `;
  66. const table = document.querySelector('table');
  67. if (table) table.parentNode?.insertBefore(controls, table);
  68. (document.getElementById('capex-metric') as HTMLSelectElement).value = capexMetric;
  69. (document.getElementById('opex-metric') as HTMLSelectElement).value = opexMetric;
  70. (document.getElementById('revenue-metric') as HTMLSelectElement).value = revenueMetric;
  71. document.getElementById('capex-metric')!.addEventListener('change', (e) => {
  72. capexMetric = (e.target as HTMLSelectElement).value as MetricType;
  73. render();
  74. });
  75. document.getElementById('opex-metric')!.addEventListener('change', (e) => {
  76. opexMetric = (e.target as HTMLSelectElement).value as MetricType;
  77. render();
  78. });
  79. document.getElementById('revenue-metric')!.addEventListener('change', (e) => {
  80. revenueMetric = (e.target as HTMLSelectElement).value as MetricType;
  81. render();
  82. });
  83. metricControlsInitialized = true;
  84. }
  85. if (!headersInitialized) {
  86. const ths = document.querySelectorAll('th');
  87. const keys: (keyof ProfitWithMetrics | 'outputs')[] = [
  88. 'outputs', 'expertise', 'profit_per_area', 'break_even',
  89. 'capex_val', 'opex_val', 'logistics_per_area', 'market_capacity_area'
  90. ];
  91. ths.forEach((th, i) => {
  92. if (keys[i]) {
  93. th.style.cursor = 'pointer';
  94. th.title = ''; // Remove native title to prevent double-tooltips
  95. // EXTREME DETAIL: We inject dynamic string content and custom tooltips directly into the DOM headers.
  96. // By routing these explanations into `dataset.tooltip`, the existing popover engine picks them up
  97. // automatically, rendering a clean, stylized popup on hover.
  98. if (keys[i] === 'market_capacity_area') {
  99. th.textContent = 'Market Cap (Areas)';
  100. th.dataset.tooltip = 'Click to sort.\n\nMarket Capacity: 7-day average traded volume ÷ daily output per area. Indicates how many areas you can build before saturating the market.';
  101. } else if (keys[i] === 'break_even') {
  102. th.dataset.tooltip = 'Click to sort.\n\nBreak Even: (CapEx + 3 days of OpEx) ÷ daily profit. Includes 3 days of operating costs as working capital.';
  103. } else {
  104. th.dataset.tooltip = 'Click to sort.';
  105. }
  106. th.addEventListener('click', () => {
  107. if (currentSortKey === keys[i]) {
  108. currentSortAsc = !currentSortAsc;
  109. } else {
  110. currentSortKey = keys[i];
  111. currentSortAsc = keys[i] === 'break_even' ? true : false;
  112. }
  113. render();
  114. });
  115. }
  116. });
  117. headersInitialized = true;
  118. }
  119. const buildingTickers = new Set(profits.map(p => p.building));
  120. const buildings: {ticker: string, expertise: keyof typeof expertise}[] = Array.from(buildingTickers)
  121. .map((building) => ({ticker: building, expertise: profits.find(p => p.building === building)!.expertise}))
  122. .sort((a, b) => a.ticker.localeCompare(b.ticker));
  123. let selectedBuilding = buildingSelect.value || savedBuilding;
  124. let buildingFound = false;
  125. buildingSelect.innerHTML = '<option value="">(all)</option>';
  126. for (const building of buildings)
  127. if (expertiseSelect.value === '' || expertiseSelect.value === building.expertise) {
  128. const option = document.createElement('option');
  129. option.value = building.ticker;
  130. option.textContent = building.ticker;
  131. if (building.ticker === selectedBuilding) {
  132. buildingFound = true;
  133. option.selected = true;
  134. }
  135. buildingSelect.appendChild(option);
  136. }
  137. if (!buildingFound)
  138. selectedBuilding = '';
  139. savedBuilding = '';
  140. const filteredProfits = profits.filter(p => {
  141. const volumeRatio = p.output_per_day / p.average_traded_7d;
  142. if (!lowVolume.checked && volumeRatio > 0.05) return false;
  143. if (expertiseSelect.value !== '' && p.expertise !== expertiseSelect.value) return false;
  144. if (selectedBuilding !== '' && p.building !== selectedBuilding) return false;
  145. return true;
  146. });
  147. const profitsWithMetrics: ProfitWithMetrics[] = filteredProfits.map(p => {
  148. const capex_val = p.capex[capexMetric];
  149. const opex_val = p.opex[opexMetric];
  150. const revenue_val = p.revenue[revenueMetric];
  151. const profit_per_day = revenue_val - opex_val;
  152. const profit_per_area = profit_per_day / p.area;
  153. const break_even = profit_per_day > 0 ? (capex_val + 3 * opex_val) / profit_per_day : Infinity;
  154. return { ...p, capex_val, opex_val, revenue_val, profit_per_day, profit_per_area, break_even };
  155. });
  156. profitsWithMetrics.sort((a, b) => {
  157. let valA: any = a[currentSortKey as keyof ProfitWithMetrics];
  158. let valB: any = b[currentSortKey as keyof ProfitWithMetrics];
  159. if (currentSortKey === 'outputs') {
  160. valA = a.outputs.map(o => o.ticker).join(', ');
  161. valB = b.outputs.map(o => o.ticker).join(', ');
  162. }
  163. if (valA < valB) return currentSortAsc ? -1 : 1;
  164. if (valA > valB) return currentSortAsc ? 1 : -1;
  165. return 0;
  166. });
  167. for (const p of profitsWithMetrics) {
  168. const tr = document.createElement('tr');
  169. tr.innerHTML = `
  170. <td>${p.outputs.map(o => o.ticker).join(', ')}</td>
  171. <td>${expertise[p.expertise]}</td>
  172. <td style="color: ${color(p.profit_per_area, 0, 300)}">${formatDecimal(p.profit_per_area)}</td>
  173. <td><span style="color: ${color(p.break_even, 30, 3)}">${formatDecimal(p.break_even)}</span>d</td>
  174. <td style="color: ${color(p.capex_val, 300_000, 40_000)}">${formatWhole(p.capex_val)}</td>
  175. <td style="color: ${color(p.opex_val, 40_000, 1_000)}">${formatWhole(p.opex_val)}</td>
  176. <td style="color: ${color(p.logistics_per_area, 2, 0.2)}">${formatDecimal(p.logistics_per_area)}</td>
  177. <td style="color: ${color(p.market_capacity_area, 20, 500)}">${formatWhole(p.market_capacity_area)}</td>
  178. `;
  179. const output = tr.querySelector('td')!;
  180. output.dataset.tooltip = p.recipe;
  181. const profitCell = tr.querySelectorAll('td')[2];
  182. profitCell.dataset.tooltip = formatMatPrices(p.outputs, revenueMetric, p.runs_per_day) + '\n\n' +
  183. formatMatPrices(p.input_costs, opexMetric, p.runs_per_day) + '\n' +
  184. `(${formatWhole(p.revenue_val)} - ${formatWhole(p.opex_val)}) = ${formatDecimal(p.profit_per_day)}\n` +
  185. `${formatDecimal(p.profit_per_day)} / ${formatWhole(p.area)} area = ${formatDecimal(p.profit_per_area)}`;
  186. const marketCell = tr.querySelectorAll('td')[7];
  187. marketCell.dataset.tooltip = `Market Capacity: ${formatWhole(p.average_traded_7d)} traded/day ÷ ${formatDecimal(p.output_per_day / p.area)} produced/day/area = ${formatWhole(p.market_capacity_area)} equivalent areas`;
  188. tbody.appendChild(tr);
  189. }
  190. document.getElementById('last-updated')!.textContent =
  191. `last updated: ${lastModified.toLocaleString(undefined, {dateStyle: 'full', timeStyle: 'long', hour12: false})}`;
  192. saveState();
  193. }
  194. function saveState() {
  195. localStorage.setItem('roi-cx', cxSelect.value);
  196. localStorage.setItem('roi-expertise', expertiseSelect.value);
  197. localStorage.setItem('roi-building', buildingSelect.value);
  198. localStorage.setItem('roi-low-volume', lowVolume.checked.toString());
  199. localStorage.setItem('roi-sort-key', currentSortKey);
  200. localStorage.setItem('roi-sort-asc', currentSortAsc.toString());
  201. localStorage.setItem('roi-capex-metric', capexMetric);
  202. localStorage.setItem('roi-opex-metric', opexMetric);
  203. localStorage.setItem('roi-revenue-metric', revenueMetric);
  204. }
  205. function color(n: number, low: number, high: number): string {
  206. const scale = Math.min(Math.max((n - low) / (high - low), 0), 1);
  207. return `color-mix(in xyz, #0aa ${scale * 100}%, #f80)`;
  208. }
  209. function formatMatPrices(matPrices: MatPrice[], metric: MetricType, runs_per_day: number): string {
  210. return matPrices.map(({ticker, amount, vwap_7d, bid, ask}) => {
  211. const val = metric === 'vwap' ? vwap_7d : metric === 'bid' ? (bid ?? vwap_7d) : (ask ?? vwap_7d);
  212. const daily_amount = amount * runs_per_day;
  213. return `${ticker}: ${formatDecimal(daily_amount)} × ${formatDecimal(val)} = ${formatWhole(daily_amount * val)}`;
  214. }).join('\n');
  215. }
  216. setupPopover();
  217. lowVolume.addEventListener('change', render);
  218. cxSelect.addEventListener('change', render);
  219. expertiseSelect.addEventListener('change', render);
  220. buildingSelect.addEventListener('change', render);
  221. render();
  222. interface Metrics {
  223. vwap: number;
  224. bid: number;
  225. ask: number;
  226. }
  227. interface Profit {
  228. outputs: MatPrice[]
  229. recipe: string
  230. expertise: keyof typeof expertise
  231. building: string
  232. area: number
  233. capex: Metrics
  234. opex: Metrics
  235. revenue: Metrics
  236. input_costs: MatPrice[]
  237. runs_per_day: number
  238. logistics_per_area: number
  239. output_per_day: number
  240. average_traded_7d: number
  241. market_capacity_area: number
  242. }
  243. interface ProfitWithMetrics extends Profit {
  244. capex_val: number;
  245. opex_val: number;
  246. revenue_val: number;
  247. profit_per_day: number;
  248. profit_per_area: number;
  249. break_even: number;
  250. }
  251. interface MatPrice {
  252. ticker: string
  253. amount: number
  254. vwap_7d: number
  255. bid: number | null
  256. ask: number | null
  257. }
  258. interface Building {
  259. building_type: 'INFRASTRUCTURE' | 'PLANETARY' | 'PRODUCTION';
  260. building_ticker: string;
  261. expertise: keyof typeof expertise;
  262. }