roi.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. // EXTREME DETAIL: We replace the distinct `formatWhole` and `formatDecimal` formatters with a unified
  32. // `formatSigFig` formatter. Utilizing the `compact` notation automatically caps the output at
  33. // 3 significant figures and organically appends "K", "M", etc. to large numbers.
  34. const formatSigFig = new Intl.NumberFormat(undefined, {
  35. notation: 'compact',
  36. maximumSignificantDigits: 3,
  37. }).format;
  38. if (localStorage.getItem('roi-cx')) cxSelect.value = localStorage.getItem('roi-cx')!;
  39. if (localStorage.getItem('roi-expertise')) expertiseSelect.value = localStorage.getItem('roi-expertise')!;
  40. if (localStorage.getItem('roi-low-volume')) lowVolume.checked = localStorage.getItem('roi-low-volume') === 'true';
  41. let savedBuilding = localStorage.getItem('roi-building') || '';
  42. let currentSortKey: keyof ProfitWithMetrics | 'outputs' = (localStorage.getItem('roi-sort-key') as any) || 'break_even';
  43. let currentSortAsc: boolean = localStorage.getItem('roi-sort-asc') !== 'false';
  44. let headersInitialized = false;
  45. let metricControlsInitialized = false;
  46. let capexMetric: MetricType = (localStorage.getItem('roi-capex-metric') as MetricType) || 'vwap';
  47. let opexMetric: MetricType = (localStorage.getItem('roi-opex-metric') as MetricType) || 'vwap';
  48. let revenueMetric: MetricType = (localStorage.getItem('roi-revenue-metric') as MetricType) || 'vwap';
  49. let includeShips: boolean = localStorage.getItem('roi-include-ships') === 'true';
  50. // EXTREME DETAIL: Track the state of the user's working capital input. Default to 3 days.
  51. let workingCapitalDays: number = parseInt(localStorage.getItem('roi-working-capital') || '3', 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. // EXTREME DETAIL: Added the numerical input `<input type="number">` allowing users to configure
  63. // exactly how many days of OpEx should be buffered into their CapEx.
  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>
  78. <input type="number" id="working-capital" min="0" step="1" style="width: 50px;"> Days OpEx
  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('capex-metric')!.addEventListener('change', (e) => {
  89. capexMetric = (e.target as HTMLSelectElement).value as MetricType;
  90. render();
  91. });
  92. document.getElementById('opex-metric')!.addEventListener('change', (e) => {
  93. opexMetric = (e.target as HTMLSelectElement).value as MetricType;
  94. render();
  95. });
  96. document.getElementById('revenue-metric')!.addEventListener('change', (e) => {
  97. revenueMetric = (e.target as HTMLSelectElement).value as MetricType;
  98. render();
  99. });
  100. document.getElementById('include-ships')!.addEventListener('change', (e) => {
  101. includeShips = (e.target as HTMLInputElement).checked;
  102. render();
  103. });
  104. document.getElementById('working-capital')!.addEventListener('change', (e) => {
  105. workingCapitalDays = parseInt((e.target as HTMLInputElement).value, 10);
  106. render();
  107. });
  108. metricControlsInitialized = true;
  109. }
  110. if (!headersInitialized) {
  111. const ths = document.querySelectorAll('th');
  112. const keys: (keyof ProfitWithMetrics | 'outputs')[] = [
  113. 'outputs', 'expertise', 'profit_per_base', 'break_even',
  114. 'capex_val', 'opex_val', 'logistics_per_base', 'market_capacity_base'
  115. ];
  116. ths.forEach((th, i) => {
  117. if (keys[i]) {
  118. th.style.cursor = 'pointer';
  119. th.title = '';
  120. if (keys[i] === 'profit_per_base') {
  121. th.textContent = 'Profit/Base';
  122. th.dataset.tooltip = 'Click to sort.\n\nDaily profit scaled to a full 500-area planetary base.';
  123. } else if (keys[i] === 'capex_val') {
  124. th.textContent = 'CapEx/Base';
  125. 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), and optional Ship CapEx.';
  126. } else if (keys[i] === 'opex_val') {
  127. th.textContent = 'OpEx/Base';
  128. th.dataset.tooltip = 'Click to sort.\n\nDaily operational expenditure (input materials + worker consumables) scaled to a full 500-area planetary base.';
  129. } else if (keys[i] === 'logistics_per_base') {
  130. th.textContent = 'Logistics/Base';
  131. 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.';
  132. } else if (keys[i] === 'market_capacity_base') {
  133. th.textContent = 'Market Cap (Bases)';
  134. 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.';
  135. } else if (keys[i] === 'break_even') {
  136. th.dataset.tooltip = 'Click to sort.\n\nBreak Even: CapEx ÷ daily profit. Note that CapEx dynamically includes working capital (days of OpEx) to accurately reflect operational readiness.';
  137. } else {
  138. th.dataset.tooltip = 'Click to sort.';
  139. }
  140. th.addEventListener('click', () => {
  141. if (currentSortKey === keys[i]) {
  142. currentSortAsc = !currentSortAsc;
  143. } else {
  144. currentSortKey = keys[i];
  145. currentSortAsc = keys[i] === 'break_even' ? true : false;
  146. }
  147. render();
  148. });
  149. }
  150. });
  151. headersInitialized = true;
  152. }
  153. const buildingTickers = new Set(profits.map(p => p.building));
  154. const buildings: {ticker: string, expertise: keyof typeof expertise}[] = Array.from(buildingTickers)
  155. .map((building) => ({ticker: building, expertise: profits.find(p => p.building === building)!.expertise}))
  156. .sort((a, b) => a.ticker.localeCompare(b.ticker));
  157. let selectedBuilding = buildingSelect.value || savedBuilding;
  158. let buildingFound = false;
  159. buildingSelect.innerHTML = '<option value="">(all)</option>';
  160. for (const building of buildings)
  161. if (expertiseSelect.value === '' || expertiseSelect.value === building.expertise) {
  162. const option = document.createElement('option');
  163. option.value = building.ticker;
  164. option.textContent = building.ticker;
  165. if (building.ticker === selectedBuilding) {
  166. buildingFound = true;
  167. option.selected = true;
  168. }
  169. buildingSelect.appendChild(option);
  170. }
  171. if (!buildingFound)
  172. selectedBuilding = '';
  173. savedBuilding = '';
  174. const filteredProfits = profits.filter(p => {
  175. const volumeRatio = p.output_per_day / p.average_traded_7d;
  176. if (!lowVolume.checked && volumeRatio > 0.05) return false;
  177. if (expertiseSelect.value !== '' && p.expertise !== expertiseSelect.value) return false;
  178. if (selectedBuilding !== '' && p.building !== selectedBuilding) return false;
  179. return true;
  180. });
  181. const profitsWithMetrics: ProfitWithMetrics[] = filteredProfits.map(p => {
  182. const bases = p.area / 500;
  183. const opex_val = p.opex[opexMetric] / bases;
  184. const revenue_val = p.revenue[revenueMetric] / bases;
  185. // EXTREME DETAIL: CapEx now completely absorbs the working capital (days of OpEx).
  186. // Because we moved the addition directly into `capex_val`, it will be explicitly rendered
  187. // inside the CapEx column on the dashboard, making the break-even math visually apparent.
  188. let capex_val = (p.capex[capexMetric] / bases) + (opex_val * workingCapitalDays);
  189. if (includeShips) {
  190. capex_val += p.ship_capex_per_base;
  191. }
  192. const profit_per_base = revenue_val - opex_val;
  193. const break_even = profit_per_base > 0 ? capex_val / profit_per_base : Infinity;
  194. return { ...p, capex_val, opex_val, revenue_val, profit_per_base, break_even };
  195. });
  196. profitsWithMetrics.sort((a, b) => {
  197. let valA: any = a[currentSortKey as keyof ProfitWithMetrics];
  198. let valB: any = b[currentSortKey as keyof ProfitWithMetrics];
  199. if (currentSortKey === 'outputs') {
  200. valA = a.outputs.map(o => o.ticker).join(', ');
  201. valB = b.outputs.map(o => o.ticker).join(', ');
  202. }
  203. if (valA < valB) return currentSortAsc ? -1 : 1;
  204. if (valA > valB) return currentSortAsc ? 1 : -1;
  205. return 0;
  206. });
  207. for (const p of profitsWithMetrics) {
  208. const volumeRatio = p.output_per_day / p.average_traded_7d;
  209. const tr = document.createElement('tr');
  210. // EXTREME DETAIL: We replaced all formatDecimal/formatWhole calls with formatSigFig.
  211. // Additionally, we append the newly generated bottleneck string onto the Logistics cell.
  212. tr.innerHTML = `
  213. <td>${p.outputs.map(o => o.ticker).join(', ')}</td>
  214. <td>${expertise[p.expertise]}</td>
  215. <td style="color: ${color(p.profit_per_base, 0, 150000)}">${formatSigFig(p.profit_per_base)}</td>
  216. <td><span style="color: ${color(p.break_even, 30, 3)}">${formatSigFig(p.break_even)}</span>d</td>
  217. <td style="color: ${color(p.capex_val, 3_000_000, 400_000)}">${formatSigFig(p.capex_val)}</td>
  218. <td style="color: ${color(p.opex_val, 400_000, 10_000)}">${formatSigFig(p.opex_val)}</td>
  219. <td style="color: ${color(p.logistics_per_base, 1000, 100)}">${formatSigFig(p.logistics_per_base)} ${p.logistics_bottleneck}</td>
  220. <td style="color: ${color(p.market_capacity_base, 0.04, 1)}">${formatSigFig(p.market_capacity_base)}</td>
  221. `;
  222. const output = tr.querySelector('td')!;
  223. output.dataset.tooltip = p.recipe;
  224. const profitCell = tr.querySelectorAll('td')[2];
  225. const runs_per_base = p.runs_per_day / (p.area / 500);
  226. profitCell.dataset.tooltip = formatMatPrices(p.outputs, revenueMetric, runs_per_base) + '\n\n' +
  227. formatMatPrices(p.input_costs, opexMetric, runs_per_base) + '\n' +
  228. '+ worker consumables\n\n' +
  229. `(${formatSigFig(p.revenue_val)} - ${formatSigFig(p.opex_val)}) = ${formatSigFig(p.profit_per_base)}`;
  230. // EXTREME DETAIL: Because working capital is now part of CapEx, we break down
  231. // the constituent components in the tooltip so the math is transparent.
  232. const capexCell = tr.querySelectorAll('td')[4];
  233. capexCell.dataset.tooltip = `Base Construction: ${formatSigFig(p.capex[capexMetric] / (p.area / 500))}`;
  234. capexCell.dataset.tooltip += `\nWorking Capital (${workingCapitalDays} days): ${formatSigFig(p.opex_val * workingCapitalDays)}`;
  235. if (includeShips) {
  236. capexCell.dataset.tooltip += `\nShip CapEx: ${formatSigFig(p.ship_capex_per_base)} (${formatSigFig(p.ship_capex_per_base / 800_000)} ships)`;
  237. }
  238. const marketCell = tr.querySelectorAll('td')[7];
  239. 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`;
  240. tbody.appendChild(tr);
  241. }
  242. document.getElementById('last-updated')!.textContent =
  243. `last updated: ${lastModified.toLocaleString(undefined, {dateStyle: 'full', timeStyle: 'long', hour12: false})}`;
  244. saveState();
  245. }
  246. function saveState() {
  247. localStorage.setItem('roi-cx', cxSelect.value);
  248. localStorage.setItem('roi-expertise', expertiseSelect.value);
  249. localStorage.setItem('roi-building', buildingSelect.value);
  250. localStorage.setItem('roi-low-volume', lowVolume.checked.toString());
  251. localStorage.setItem('roi-sort-key', currentSortKey);
  252. localStorage.setItem('roi-sort-asc', currentSortAsc.toString());
  253. localStorage.setItem('roi-capex-metric', capexMetric);
  254. localStorage.setItem('roi-opex-metric', opexMetric);
  255. localStorage.setItem('roi-revenue-metric', revenueMetric);
  256. localStorage.setItem('roi-include-ships', includeShips.toString());
  257. localStorage.setItem('roi-working-capital', workingCapitalDays.toString());
  258. }
  259. function color(n: number, low: number, high: number): string {
  260. const scale = Math.min(Math.max((n - low) / (high - low), 0), 1);
  261. return `color-mix(in xyz, #0aa ${scale * 100}%, #f80)`;
  262. }
  263. function formatMatPrices(matPrices: MatPrice[], metric: MetricType, runs_per_day: number): string {
  264. return matPrices.map(({ticker, amount, vwap_7d, bid, ask}) => {
  265. const val = metric === 'vwap' ? vwap_7d : metric === 'bid' ? (bid ?? vwap_7d) : (ask ?? vwap_7d);
  266. const daily_amount = amount * runs_per_day;
  267. return `${ticker}: ${formatSigFig(daily_amount)} × ${formatSigFig(val)} = ${formatSigFig(daily_amount * val)}`;
  268. }).join('\n');
  269. }
  270. setupPopover();
  271. lowVolume.addEventListener('change', render);
  272. cxSelect.addEventListener('change', render);
  273. expertiseSelect.addEventListener('change', render);
  274. buildingSelect.addEventListener('change', render);
  275. render();
  276. interface Metrics {
  277. vwap: number;
  278. bid: number;
  279. ask: number;
  280. }
  281. interface Profit {
  282. outputs: MatPrice[]
  283. recipe: string
  284. expertise: keyof typeof expertise
  285. building: string
  286. area: number
  287. capex: Metrics
  288. opex: Metrics
  289. revenue: Metrics
  290. input_costs: MatPrice[]
  291. runs_per_day: number
  292. logistics_per_base: number
  293. logistics_bottleneck: string // Extracted from backend
  294. output_per_day: number
  295. average_traded_7d: number
  296. market_capacity_base: number
  297. ship_capex_per_base: number
  298. }
  299. interface ProfitWithMetrics extends Profit {
  300. capex_val: number;
  301. opex_val: number;
  302. revenue_val: number;
  303. profit_per_day: number;
  304. profit_per_base: number;
  305. break_even: number;
  306. }
  307. interface MatPrice {
  308. ticker: string
  309. amount: number
  310. vwap_7d: number
  311. bid: number | null
  312. ask: number | null
  313. }
  314. interface Building {
  315. building_type: 'INFRASTRUCTURE' | 'PLANETARY' | 'PRODUCTION';
  316. building_ticker: string;
  317. expertise: keyof typeof expertise;
  318. }