roi.ts 18 KB

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