roi.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 roundTripOption: string = localStorage.getItem('roi-round-trip') || 'omit';
  49. let showNegativeProfit: boolean = localStorage.getItem('roi-show-negative') !== 'false';
  50. let workingCapitalOption: string = localStorage.getItem('roi-working-capital-opt') || 'dynamic';
  51. let targetPermitOption: string = localStorage.getItem('roi-target-permit') || '2';
  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="show-negative"> Show Negative Profit
  74. </label>
  75. <label style="margin-right: 15px;">
  76. Round Trip (hrs): 
  77. <select id="round-trip">
  78. <option value="omit">Omit From Calculation</option>
  79. ${Array.from({length: 25}, (_, i) => `<option value="${i + 1}">${i + 1}</option>`).join('')}
  80. </select>
  81. </label>
  82. <label style="margin-right: 15px;">
  83. Days OpEx: 
  84. <select id="working-capital">
  85. <option value="omit">Omit From Calculation</option>
  86. <option value="dynamic">Max for Shipment (dynamic)</option>
  87. <option value="1">1</option>
  88. <option value="2">2</option>
  89. <option value="3">3</option>
  90. <option value="4">4</option>
  91. <option value="5">5</option>
  92. <option value="6">6</option>
  93. <option value="7">7</option>
  94. <option value="14">14</option>
  95. <option value="30">30</option>
  96. </select>
  97. </label>
  98. <label>
  99. Permit Number: 
  100. <select id="target-permit">
  101. <option value="omit">Omit From Calculation</option>
  102. ${Array.from({length: 49}, (_, i) => `<option value="${i + 2}">${i + 2}</option>`).join('')}
  103. </select>
  104. </label>
  105. `;
  106. const table = document.querySelector('table');
  107. if (table) table.parentNode?.insertBefore(controls, table);
  108. (document.getElementById('capex-metric') as HTMLSelectElement).value = capexMetric;
  109. (document.getElementById('opex-metric') as HTMLSelectElement).value = opexMetric;
  110. (document.getElementById('revenue-metric') as HTMLSelectElement).value = revenueMetric;
  111. (document.getElementById('show-negative') as HTMLInputElement).checked = showNegativeProfit;
  112. (document.getElementById('round-trip') as HTMLSelectElement).value = roundTripOption;
  113. (document.getElementById('working-capital') as HTMLSelectElement).value = workingCapitalOption;
  114. (document.getElementById('target-permit') as HTMLSelectElement).value = targetPermitOption;
  115. document.getElementById('capex-metric')!.addEventListener('change', (e) => {
  116. capexMetric = (e.target as HTMLSelectElement).value as MetricType;
  117. render();
  118. });
  119. document.getElementById('opex-metric')!.addEventListener('change', (e) => {
  120. opexMetric = (e.target as HTMLSelectElement).value as MetricType;
  121. render();
  122. });
  123. document.getElementById('revenue-metric')!.addEventListener('change', (e) => {
  124. revenueMetric = (e.target as HTMLSelectElement).value as MetricType;
  125. render();
  126. });
  127. document.getElementById('show-negative')!.addEventListener('change', (e) => {
  128. showNegativeProfit = (e.target as HTMLInputElement).checked;
  129. render();
  130. });
  131. document.getElementById('round-trip')!.addEventListener('change', (e) => {
  132. roundTripOption = (e.target as HTMLSelectElement).value;
  133. render();
  134. });
  135. document.getElementById('working-capital')!.addEventListener('change', (e) => {
  136. workingCapitalOption = (e.target as HTMLSelectElement).value;
  137. render();
  138. });
  139. document.getElementById('target-permit')!.addEventListener('change', (e) => {
  140. targetPermitOption = (e.target as HTMLSelectElement).value;
  141. render();
  142. });
  143. metricControlsInitialized = true;
  144. }
  145. if (!headersInitialized) {
  146. const ths = document.querySelectorAll('th');
  147. const keys: (keyof ProfitWithMetrics | 'outputs')[] = [
  148. 'outputs', 'expertise', 'profit_per_base', 'break_even', 
  149. 'capex_val', 'opex_val', 'normalized_logistics_per_base', 'market_capacity_base'
  150. ];
  151. const pctExplainer = '\n(Percentiles: Relative Volume / Absolute. 100.0% is the most desirable outcome. Relative rank is weighted by total market cash flow.)';
  152. ths.forEach((th, i) => {
  153. if (keys[i]) {
  154. th.style.cursor = 'pointer';
  155. th.title = ''; 
  156. if (keys[i] === 'profit_per_base') {
  157. th.textContent = 'Profit/Base';
  158. th.dataset.tooltip = 'Click to sort.\n\nDaily profit scaled to a full 500-area planetary base.' + pctExplainer;
  159. } else if (keys[i] === 'capex_val') {
  160. th.textContent = 'CapEx/Base';
  161. th.dataset.tooltip = 'Click to sort.\n\nTotal capital expenditure scaled to a full 500-area planetary base.\nIncludes base construction, and optional Working Capital, HQ Upgrades, and Ship CapEx (use "Omit From Calculation" to exclude).' + pctExplainer;
  162. } else if (keys[i] === 'opex_val') {
  163. th.textContent = 'OpEx/Base';
  164. th.dataset.tooltip = 'Click to sort.\n\nDaily operational expenditure (input materials + worker consumables) scaled to a full 500-area planetary base.' + pctExplainer;
  165. } else if (keys[i] === 'normalized_logistics_per_base') {
  166. th.textContent = 'Logistics/Base';
  167. 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³).' + pctExplainer;
  168. } else if (keys[i] === 'market_capacity_base') {
  169. th.textContent = 'Market Cap (Bases)';
  170. 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.' + pctExplainer;
  171. } else if (keys[i] === 'break_even') {
  172. th.dataset.tooltip = 'Click to sort.\n\nBreak Even: CapEx ÷ daily profit. Note that CapEx dynamically includes optional logistics and HQ upgrades to accurately reflect operational readiness.' + pctExplainer;
  173. } else {
  174. th.dataset.tooltip = 'Click to sort.';
  175. }
  176. th.addEventListener('click', () => {
  177. if (currentSortKey === keys[i]) {
  178. currentSortAsc = !currentSortAsc;
  179. } else {
  180. currentSortKey = keys[i];
  181. currentSortAsc = keys[i] === 'break_even' ? true : false;
  182. }
  183. render();
  184. });
  185. }
  186. });
  187. headersInitialized = true;
  188. }
  189. const buildingTickers = new Set(profits.map(p => p.building));
  190. const buildings: {ticker: string, expertise: keyof typeof expertise}[] = Array.from(buildingTickers)
  191. .map((building) => ({ticker: building, expertise: profits.find(p => p.building === building)!.expertise}))
  192. .sort((a, b) => a.ticker.localeCompare(b.ticker));
  193. let selectedBuilding = buildingSelect.value || savedBuilding;
  194. let buildingFound = false;
  195. buildingSelect.innerHTML = '<option value="">(all)</option>';
  196. for (const building of buildings)
  197. if (expertiseSelect.value === '' || expertiseSelect.value === building.expertise) {
  198. const option = document.createElement('option');
  199. option.value = building.ticker;
  200. option.textContent = building.ticker;
  201. if (building.ticker === selectedBuilding) {
  202. buildingFound = true;
  203. option.selected = true;
  204. }
  205. buildingSelect.appendChild(option);
  206. }
  207. if (!buildingFound)
  208. selectedBuilding = '';
  209. savedBuilding = ''; 
  210. const filteredProfits = profits.filter(p => {
  211. const volumeRatio = p.output_per_day / p.average_traded_7d;
  212. if (!lowVolume.checked && volumeRatio > 0.05) return false;
  213. if (expertiseSelect.value !== '' && p.expertise !== expertiseSelect.value) return false;
  214. if (selectedBuilding !== '' && p.building !== selectedBuilding) return false;
  215. return true;
  216. });
  217. let profitsWithMetrics: ProfitWithMetrics[] = filteredProfits.map(p => {
  218. const bases = p.area / 500;
  219. const opex_val = p.opex[opexMetric] / bases;
  220. const revenue_val = p.revenue[revenueMetric] / bases;
  221. let capex_val = p.capex[capexMetric] / bases;
  222. let activeWorkingCapitalDays = 0;
  223. if (workingCapitalOption !== 'omit') {
  224. if (workingCapitalOption === 'dynamic') {
  225. activeWorkingCapitalDays = p.normalized_logistics_per_base > 0 
  226. ? 1 / p.normalized_logistics_per_base 
  227. : 0;
  228. } else {
  229. activeWorkingCapitalDays = parseInt(workingCapitalOption, 10);
  230. }
  231. capex_val += (opex_val * activeWorkingCapitalDays);
  232. }
  233. let hq_capex = 0;
  234. if (targetPermitOption !== 'omit') {
  235. const targetPermit = parseInt(targetPermitOption, 10);
  236. if (targetPermit >= 3) {
  237. const hqLevelStr = (targetPermit - 1).toString();
  238. if (p.hq_costs && p.hq_costs[hqLevelStr]) {
  239. hq_capex = p.hq_costs[hqLevelStr][capexMetric];
  240. capex_val += hq_capex;
  241. }
  242. }
  243. }
  244. let shipsNeeded = 0;
  245. let activeShipCapex = 0;
  246. if (roundTripOption !== 'omit') {
  247. const roundTripHours = parseInt(roundTripOption, 10);
  248. shipsNeeded = p.normalized_logistics_per_base * (roundTripHours / 24);
  249. activeShipCapex = shipsNeeded * 800_000;
  250. capex_val += activeShipCapex;
  251. }
  252. const profit_per_base = revenue_val - opex_val;
  253. const break_even = profit_per_base > 0 ? capex_val / profit_per_base : Infinity;
  254. // EXTREME DETAIL: We determine the specific market weight of this recipe line.
  255. // Multiplying the revenue (value per day per base) by the market capacity (max bases allowed)
  256. // yields the total cash flow value of all available trades in the global FIO market for this bottleneck.
  257. const market_cash_flow = revenue_val * p.market_capacity_base;
  258. return { 
  259. ...p, 
  260. capex_val, 
  261. opex_val, 
  262. revenue_val, 
  263. profit_per_base, 
  264. break_even, 
  265. hq_capex,
  266. activeWorkingCapitalDays,
  267. activeShipCapex,
  268. shipsNeeded,
  269. market_cash_flow
  270. };
  271. });
  272. if (!showNegativeProfit) {
  273. profitsWithMetrics = profitsWithMetrics.filter(p => p.profit_per_base > 0);
  274. }
  275. // EXTREME DETAIL: Overhauled the extraction arrays to store both the numerical value AND the weight parameter.
  276. const numSortObj = (a: {val: number, weight: number}, b: {val: number, weight: number}) => (a.val < b.val ? -1 : a.val > b.val ? 1 : 0);
  277. const arrProfit = profitsWithMetrics.map(p => ({val: p.profit_per_base, weight: p.market_cash_flow})).sort(numSortObj);
  278. const arrBreak = profitsWithMetrics.map(p => ({val: p.break_even, weight: p.market_cash_flow})).sort(numSortObj);
  279. const arrCapex = profitsWithMetrics.map(p => ({val: p.capex_val, weight: p.market_cash_flow})).sort(numSortObj);
  280. const arrOpex = profitsWithMetrics.map(p => ({val: p.opex_val, weight: p.market_cash_flow})).sort(numSortObj);
  281. const arrLog = profitsWithMetrics.map(p => ({val: p.normalized_logistics_per_base, weight: p.market_cash_flow})).sort(numSortObj);
  282. const arrCap = profitsWithMetrics.map(p => ({val: p.market_capacity_base, weight: p.market_cash_flow})).sort(numSortObj);
  283. profitsWithMetrics.sort((a, b) => {
  284. let valA: any = a[currentSortKey as keyof ProfitWithMetrics];
  285. let valB: any = b[currentSortKey as keyof ProfitWithMetrics];
  286. if (currentSortKey === 'outputs') {
  287. valA = a.outputs.map(o => o.ticker).join(', ');
  288. valB = b.outputs.map(o => o.ticker).join(', ');
  289. }
  290. if (valA < valB) return currentSortAsc ? -1 : 1;
  291. if (valA > valB) return currentSortAsc ? 1 : -1;
  292. return 0;
  293. });
  294. for (const p of profitsWithMetrics) {
  295. const tr = document.createElement('tr');
  296. // Map the raw value to both absolute and relative percentile ranks.
  297. const pctProfit = getPercentiles(p.profit_per_base, arrProfit, false);
  298. const pctBreak = getPercentiles(p.break_even, arrBreak, true);
  299. const pctCapex = getPercentiles(p.capex_val, arrCapex, true);
  300. const pctOpex = getPercentiles(p.opex_val, arrOpex, true);
  301. const pctLog = getPercentiles(p.normalized_logistics_per_base, arrLog, true);
  302. const pctCap = getPercentiles(p.market_capacity_base, arrCap, false);
  303. // Interplate the Rel/Abs format string requested directly into the <small> span wrapper.
  304. tr.innerHTML = `
  305. <td>${p.outputs.map(o => o.ticker).join(', ')}</td>
  306. <td>${expertise[p.expertise]}</td>
  307. <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.rel} / ${pctProfit.abs})</span></td>
  308. <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.rel} / ${pctBreak.abs})</span></td>
  309. <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.rel} / ${pctCapex.abs})</span></td>
  310. <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.rel} / ${pctOpex.abs})</span></td>
  311. <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.rel} / ${pctLog.abs})</span></td>
  312. <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.rel} / ${pctCap.abs})</span></td>
  313. `;
  314. const output = tr.querySelector('td')!;
  315. output.dataset.tooltip = p.recipe;
  316. const profitCell = tr.querySelectorAll('td')[2];
  317. const runs_per_base = p.runs_per_day / (p.area / 500);
  318. profitCell.dataset.tooltip = formatMatPrices(p.outputs, revenueMetric, runs_per_base) + '\n\n' +
  319. formatMatPrices(p.input_costs, opexMetric, runs_per_base) + '\n' +
  320. '+ worker consumables\n\n' +
  321. `(${formatSigFig(p.revenue_val)} - ${formatSigFig(p.opex_val)}) = ${formatSigFig(p.profit_per_base)}`;
  322. const capexCell = tr.querySelectorAll('td')[4];
  323. capexCell.dataset.tooltip = `Base Construction: ${formatSigFig(p.capex[capexMetric] / (p.area / 500))}`;
  324. if (workingCapitalOption !== 'omit') {
  325. capexCell.dataset.tooltip += `\nWorking Capital (${formatSigFig(p.activeWorkingCapitalDays)} days): ${formatSigFig(p.opex_val * p.activeWorkingCapitalDays)}`;
  326. }
  327. if (targetPermitOption !== 'omit' && p.hq_capex > 0) {
  328. capexCell.dataset.tooltip += `\nHQ Upgrade (Permit ${targetPermitOption}): ${formatSigFig(p.hq_capex)}`;
  329. }
  330. if (roundTripOption !== 'omit') {
  331. capexCell.dataset.tooltip += `\nShip CapEx: ${formatSigFig(p.activeShipCapex)} (${formatSigFig(p.shipsNeeded)} ships)`;
  332. }
  333. const marketCell = tr.querySelectorAll('td')[7];
  334. 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`;
  335. tbody.appendChild(tr);
  336. }
  337. document.getElementById('last-updated')!.textContent =
  338. `last updated: ${lastModified.toLocaleString(undefined, {dateStyle: 'full', timeStyle: 'long', hour12: false})}`;
  339. saveState();
  340. }
  341. // EXTREME DETAIL: Overhauled function to calculate both Absolute and Relative Volume-Weighted Percentiles.
  342. // To ensure the mathematical max bounds cleanly hit 100.0%, the denominator is extracted dynamically 
  343. // relative to the highest data point present in the array.
  344. function getPercentiles(val: number, sortedArr: {val: number, weight: number}[], invert: boolean = false): {abs: string, rel: string} {
  345. if (sortedArr.length < 2) return {abs: "100.0%", rel: "100.0%"};
  346. let lessCount = 0;
  347. let lessWeight = 0;
  348. for (let i = 0; i < sortedArr.length; i++) {
  349. if (sortedArr[i].val < val) {
  350. lessCount++;
  351. lessWeight += sortedArr[i].weight;
  352. } else {
  353. break; 
  354. }
  355. }
  356. const maxVal = sortedArr[sortedArr.length - 1].val;
  357. let maxLessCount = 0;
  358. let maxLessWeight = 0;
  359. for (let i = 0; i < sortedArr.length; i++) {
  360. if (sortedArr[i].val < maxVal) {
  361. maxLessCount++;
  362. maxLessWeight += sortedArr[i].weight;
  363. } else {
  364. break;
  365. }
  366. }
  367. let absDecimal = maxLessCount > 0 ? lessCount / maxLessCount : 1.0;
  368. let relDecimal = maxLessWeight > 0 ? lessWeight / maxLessWeight : 1.0;
  369. if (invert) {
  370. absDecimal = 1.0 - absDecimal;
  371. relDecimal = 1.0 - relDecimal;
  372. }
  373. return {
  374. abs: (absDecimal * 100).toFixed(1) + "%",
  375. rel: (relDecimal * 100).toFixed(1) + "%"
  376. };
  377. }
  378. function saveState() {
  379. localStorage.setItem('roi-cx', cxSelect.value);
  380. localStorage.setItem('roi-expertise', expertiseSelect.value);
  381. localStorage.setItem('roi-building', buildingSelect.value);
  382. localStorage.setItem('roi-low-volume', lowVolume.checked.toString());
  383. localStorage.setItem('roi-sort-key', currentSortKey);
  384. localStorage.setItem('roi-sort-asc', currentSortAsc.toString());
  385. localStorage.setItem('roi-capex-metric', capexMetric);
  386. localStorage.setItem('roi-opex-metric', opexMetric);
  387. localStorage.setItem('roi-revenue-metric', revenueMetric);
  388. localStorage.setItem('roi-show-negative', showNegativeProfit.toString());
  389. localStorage.setItem('roi-round-trip', roundTripOption);
  390. localStorage.setItem('roi-working-capital-opt', workingCapitalOption);
  391. localStorage.setItem('roi-target-permit', targetPermitOption);
  392. }
  393. function color(n: number, low: number, high: number): string {
  394. const scale = Math.min(Math.max((n - low) / (high - low), 0), 1);
  395. return `color-mix(in xyz, #0aa ${scale * 100}%, #f80)`;
  396. }
  397. function formatMatPrices(matPrices: MatPrice[], metric: MetricType, runs_per_day: number): string {
  398. return matPrices.map(({ticker, amount, vwap_7d, bid, ask}) => {
  399. const val = metric === 'vwap' ? vwap_7d : metric === 'bid' ? (bid ?? vwap_7d) : (ask ?? vwap_7d);
  400. const daily_amount = amount * runs_per_day;
  401. return `${ticker}: ${formatSigFig(daily_amount)} × ${formatSigFig(val)} = ${formatSigFig(daily_amount * val)}`;
  402. }).join('\n');
  403. }
  404. setupPopover();
  405. lowVolume.addEventListener('change', render);
  406. cxSelect.addEventListener('change', render);
  407. expertiseSelect.addEventListener('change', render);
  408. buildingSelect.addEventListener('change', render);
  409. render();
  410. interface Metrics {
  411. vwap: number;
  412. bid: number;
  413. ask: number;
  414. }
  415. interface Profit {
  416. outputs: MatPrice[]
  417. recipe: string
  418. expertise: keyof typeof expertise
  419. building: string
  420. area: number
  421. capex: Metrics
  422. opex: Metrics
  423. revenue: Metrics
  424. input_costs: MatPrice[]
  425. runs_per_day: number
  426. logistics_per_base: number
  427. normalized_logistics_per_base: number
  428. logistics_bottleneck: string
  429. output_per_day: number
  430. average_traded_7d: number
  431. market_capacity_base: number
  432. hq_costs: Record<string, Metrics>
  433. }
  434. interface ProfitWithMetrics extends Profit {
  435. capex_val: number;
  436. opex_val: number;
  437. revenue_val: number;
  438. profit_per_day: number;
  439. profit_per_base: number;
  440. break_even: number;
  441. hq_capex: number;
  442. activeWorkingCapitalDays: number;
  443. activeShipCapex: number;
  444. shipsNeeded: number;
  445. market_cash_flow: number; // Exported weight tracker
  446. }
  447. interface MatPrice {
  448. ticker: string
  449. amount: number
  450. vwap_7d: number
  451. bid: number | null
  452. ask: number | null
  453. }
  454. interface Building {
  455. building_type: 'INFRASTRUCTURE' | 'PLANETARY' | 'PRODUCTION';
  456. building_ticker: string;
  457. expertise: keyof typeof expertise;
  458. }