roi.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. const lowVolume = document.querySelector('input#low-volume') as HTMLInputElement;
  10. const cxSelect = document.querySelector('select#cx') as HTMLSelectElement;
  11. const expertise = {
  12. AGRICULTURE: 'agri',
  13. CHEMISTRY: 'chem',
  14. CONSTRUCTION: 'const',
  15. ELECTRONICS: 'elec',
  16. FOOD_INDUSTRIES: 'food ind',
  17. FUEL_REFINING: 'fuel',
  18. MANUFACTURING: 'mfg',
  19. METALLURGY: 'metal',
  20. RESOURCE_EXTRACTION: 'res ext',
  21. } as const;
  22. const expertiseSelect = document.querySelector('select#expertise') as HTMLSelectElement;
  23. for (const key of Object.keys(expertise)) {
  24. const option = document.createElement('option');
  25. option.value = key;
  26. option.textContent = key.replace('_', ' ').toLowerCase();
  27. expertiseSelect.appendChild(option);
  28. }
  29. const buildingSelect = document.querySelector('select#building') as HTMLSelectElement;
  30. const formatDecimal = new Intl.NumberFormat(undefined,
  31. {maximumFractionDigits: 2, maximumSignificantDigits: 6, roundingPriority: 'lessPrecision'}).format;
  32. const formatWhole = new Intl.NumberFormat(undefined, {maximumFractionDigits: 0}).format;
  33. let currentSortKey: keyof ProfitWithMetrics | 'outputs' = 'break_even';
  34. let currentSortAsc: boolean = true;
  35. let headersInitialized = false;
  36. let metricControlsInitialized = false;
  37. // EXTREME DETAIL: Global state trackers to determine which pricing metric is applied to which column mathematically.
  38. type MetricType = 'vwap' | 'bid' | 'ask';
  39. let capexMetric: MetricType = 'vwap';
  40. let opexMetric: MetricType = 'vwap';
  41. let revenueMetric: MetricType = 'vwap';
  42. async function render() {
  43. const tbody = document.querySelector('tbody')!;
  44. tbody.innerHTML = '';
  45. const cx = cxSelect.value;
  46. if (!roiCache[cx])
  47. roiCache[cx] = getROI(cx);
  48. const {lastModified, profits} = await roiCache[cx];
  49. // EXTREME DETAIL: We dynamically inject three select dropdowns prior to rendering the table.
  50. // We bind event listeners to them to update the global MetricType states and force a re-render.
  51. if (!metricControlsInitialized) {
  52. const controls = document.createElement('div');
  53. controls.style.marginBottom = '15px';
  54. controls.innerHTML = `
  55. <label style="margin-right: 15px;">CapEx Price:
  56. <select id="capex-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  57. </label>
  58. <label style="margin-right: 15px;">OpEx Price:
  59. <select id="opex-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  60. </label>
  61. <label>Revenue (Outputs) Price:
  62. <select id="revenue-metric"><option value="vwap">VWAP</option><option value="bid">Bid</option><option value="ask">Ask</option></select>
  63. </label>
  64. `;
  65. const table = document.querySelector('table');
  66. if (table) table.parentNode?.insertBefore(controls, table);
  67. document.getElementById('capex-metric')!.addEventListener('change', (e) => {
  68. capexMetric = (e.target as HTMLSelectElement).value as MetricType;
  69. render();
  70. });
  71. document.getElementById('opex-metric')!.addEventListener('change', (e) => {
  72. opexMetric = (e.target as HTMLSelectElement).value as MetricType;
  73. render();
  74. });
  75. document.getElementById('revenue-metric')!.addEventListener('change', (e) => {
  76. revenueMetric = (e.target as HTMLSelectElement).value as MetricType;
  77. render();
  78. });
  79. metricControlsInitialized = true;
  80. }
  81. if (!headersInitialized) {
  82. const ths = document.querySelectorAll('th');
  83. // Note that 'capex' and 'cost_per_day' here map dynamically to the newly derived states later in the file.
  84. const keys: (keyof ProfitWithMetrics | 'outputs')[] = [
  85. 'outputs', 'expertise', 'profit_per_area', 'break_even',
  86. 'capex_val', 'opex_val', 'logistics_per_area', 'market_capacity_area'
  87. ];
  88. ths.forEach((th, i) => {
  89. if (keys[i]) {
  90. th.style.cursor = 'pointer';
  91. th.title = 'Click to sort';
  92. th.addEventListener('click', () => {
  93. if (currentSortKey === keys[i]) {
  94. currentSortAsc = !currentSortAsc;
  95. } else {
  96. currentSortKey = keys[i];
  97. currentSortAsc = keys[i] === 'break_even' ? true : false;
  98. }
  99. render();
  100. });
  101. }
  102. });
  103. headersInitialized = true;
  104. }
  105. const buildingTickers = new Set(profits.map(p => p.building));
  106. const buildings: {ticker: string, expertise: keyof typeof expertise}[] = Array.from(buildingTickers)
  107. .map((building) => ({ticker: building, expertise: profits.find(p => p.building === building)!.expertise}))
  108. .sort((a, b) => a.ticker.localeCompare(b.ticker));
  109. let selectedBuilding = buildingSelect.value;
  110. let buildingFound = false;
  111. buildingSelect.innerHTML = '<option value="">(all)</option>';
  112. for (const building of buildings)
  113. if (expertiseSelect.value === '' || expertiseSelect.value === building.expertise) {
  114. const option = document.createElement('option');
  115. option.value = building.ticker;
  116. option.textContent = building.ticker;
  117. if (building.ticker === selectedBuilding) {
  118. buildingFound = true;
  119. option.selected = true;
  120. }
  121. buildingSelect.appendChild(option);
  122. }
  123. if (!buildingFound)
  124. selectedBuilding = '';
  125. const filteredProfits = profits.filter(p => {
  126. const volumeRatio = p.output_per_day / p.average_traded_7d;
  127. if (!lowVolume.checked && volumeRatio > 0.05) return false;
  128. if (expertiseSelect.value !== '' && p.expertise !== expertiseSelect.value) return false;
  129. if (selectedBuilding !== '' && p.building !== selectedBuilding) return false;
  130. return true;
  131. });
  132. // EXTREME DETAIL: We map over the filtered array to compute the final derivation.
  133. // By executing this map BEFORE the sort algorithm runs, the columns dynamically organize themselves
  134. // perfectly around whichever permutations the user selected in the dropdowns.
  135. const profitsWithMetrics: ProfitWithMetrics[] = filteredProfits.map(p => {
  136. const capex_val = p.capex[capexMetric];
  137. const opex_val = p.opex[opexMetric];
  138. const revenue_val = p.revenue[revenueMetric];
  139. const profit_per_day = revenue_val - opex_val;
  140. const profit_per_area = profit_per_day / p.area;
  141. const break_even = profit_per_day > 0 ? (capex_val + 3 * opex_val) / profit_per_day : Infinity;
  142. return { ...p, capex_val, opex_val, revenue_val, profit_per_day, profit_per_area, break_even };
  143. });
  144. profitsWithMetrics.sort((a, b) => {
  145. let valA: any = a[currentSortKey as keyof ProfitWithMetrics];
  146. let valB: any = b[currentSortKey as keyof ProfitWithMetrics];
  147. if (currentSortKey === 'outputs') {
  148. valA = a.outputs.map(o => o.ticker).join(', ');
  149. valB = b.outputs.map(o => o.ticker).join(', ');
  150. }
  151. if (valA < valB) return currentSortAsc ? -1 : 1;
  152. if (valA > valB) return currentSortAsc ? 1 : -1;
  153. return 0;
  154. });
  155. for (const p of profitsWithMetrics) {
  156. const volumeRatio = p.output_per_day / p.average_traded_7d;
  157. const tr = document.createElement('tr');
  158. tr.innerHTML = `
  159. <td>${p.outputs.map(o => o.ticker).join(', ')}</td>
  160. <td>${expertise[p.expertise]}</td>
  161. <td style="color: ${color(p.profit_per_area, 0, 300)}">${formatDecimal(p.profit_per_area)}</td>
  162. <td><span style="color: ${color(p.break_even, 30, 3)}">${formatDecimal(p.break_even)}</span>d</td>
  163. <td style="color: ${color(p.capex_val, 300_000, 40_000)}">${formatWhole(p.capex_val)}</td>
  164. <td style="color: ${color(p.opex_val, 40_000, 1_000)}">${formatWhole(p.opex_val)}</td>
  165. <td style="color: ${color(p.logistics_per_area, 2, 0.2)}">${formatDecimal(p.logistics_per_area)}</td>
  166. <td style="color: ${color(p.market_capacity_area, 20, 500)}">${formatWhole(p.market_capacity_area)}</td>
  167. `;
  168. const output = tr.querySelector('td')!;
  169. output.dataset.tooltip = p.recipe;
  170. const profitCell = tr.querySelectorAll('td')[2];
  171. profitCell.dataset.tooltip = formatMatPrices(p.outputs, revenueMetric, p.runs_per_day) + '\n\n' +
  172. formatMatPrices(p.input_costs, opexMetric, p.runs_per_day) + '\n' +
  173. `(${formatWhole(p.revenue_val)} - ${formatWhole(p.opex_val)}) = ${formatDecimal(p.profit_per_day)}\n` +
  174. `${formatDecimal(p.profit_per_day)} / ${formatWhole(p.area)} area = ${formatDecimal(p.profit_per_area)}`;
  175. const marketCell = tr.querySelectorAll('td')[7];
  176. 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`;
  177. tbody.appendChild(tr);
  178. }
  179. }
  180. function color(n: number, low: number, high: number): string {
  181. const scale = Math.min(Math.max((n - low) / (high - low), 0), 1);
  182. return `color-mix(in xyz, #0aa ${scale * 100}%, #f80)`;
  183. }
  184. // EXTREME DETAIL: formatMatPrices relies on evaluating the user's selected metric ('vwap', 'bid', or 'ask').
  185. // To avoid math crashes, if a user requests a Bid/Ask display for an item lacking that specific liquidity,
  186. // the fallback logic defaults to the standard 7-day VWAP.
  187. function formatMatPrices(matPrices: MatPrice[], metric: MetricType, runs_per_day: number): string {
  188. return matPrices.map(({ticker, amount, vwap_7d, bid, ask}) => {
  189. const val = metric === 'vwap' ? vwap_7d : metric === 'bid' ? (bid ?? vwap_7d) : (ask ?? vwap_7d);
  190. const daily_amount = amount * runs_per_day;
  191. return `${ticker}: ${formatDecimal(daily_amount)} × ${formatDecimal(val)} = ${formatWhole(daily_amount * val)}`;
  192. }).join('\n');
  193. }
  194. setupPopover();
  195. lowVolume.addEventListener('change', render);
  196. cxSelect.addEventListener('change', render);
  197. expertiseSelect.addEventListener('change', render);
  198. buildingSelect.addEventListener('change', render);
  199. render();
  200. interface Metrics {
  201. vwap: number;
  202. bid: number;
  203. ask: number;
  204. }
  205. interface Profit {
  206. outputs: MatPrice[]
  207. recipe: string
  208. expertise: keyof typeof expertise
  209. building: string
  210. area: number
  211. capex: Metrics
  212. opex: Metrics
  213. revenue: Metrics
  214. input_costs: MatPrice[]
  215. runs_per_day: number
  216. logistics_per_area: number
  217. output_per_day: number
  218. average_traded_7d: number
  219. market_capacity_area: number
  220. }
  221. // Interface extension utilized for the dynamic frontend mapping array
  222. interface ProfitWithMetrics extends Profit {
  223. capex_val: number;
  224. opex_val: number;
  225. revenue_val: number;
  226. profit_per_day: number;
  227. profit_per_area: number;
  228. break_even: number;
  229. }
  230. interface MatPrice {
  231. ticker: string
  232. amount: number
  233. vwap_7d: number
  234. bid: number | null
  235. ask: number | null
  236. }
  237. interface Building {
  238. building_type: 'INFRASTRUCTURE' | 'PLANETARY' | 'PRODUCTION';
  239. building_ticker: string;
  240. expertise: keyof typeof expertise;
  241. }