shipbuilding.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import {cachedFetchJSON} from './cache';
  2. const buy = new Set([
  3. // definitely buy
  4. 'C', 'FLX', 'H', 'H2O', 'HAL', 'HCP', 'HE', 'LST', 'MG', 'N', 'NA', 'NCS', 'NS', 'O', 'PE', 'PG', 'S', 'TCL', 'THF',
  5. // maybe buy
  6. 'AIR', 'AU', 'BE', 'BRM', 'CU', 'FAN', 'FC', 'FE', 'HCC', 'HD', 'LDI', 'LI', 'MFK', 'MWF', 'REA', 'RG', 'RGO', 'ROM', 'SFK', 'SI', 'STL', 'TI', 'TPU',
  7. // import
  8. 'AAR', 'AWF', 'CAP', 'CF',
  9. // skip
  10. 'LFE', 'LHP', 'MFE', 'SFE', 'SSC',
  11. ])
  12. const blueprint = {
  13. 'FFC': 1,
  14. 'FSE': 1,
  15. 'LFE': 2,
  16. 'MFE': 2,
  17. 'QCR': 1,
  18. 'SFE': 1,
  19. 'LCB': 1,
  20. 'MFL': 1,
  21. 'MSL': 1,
  22. 'LHP': 94,
  23. 'SSC': 128,
  24. 'BR1': 1,
  25. 'CQM': 1,
  26. }
  27. render();
  28. async function render() {
  29. const main = document.querySelector('main.shipbuilding');
  30. if (!main)
  31. throw new Error('missing shipbuilding container');
  32. main.innerHTML = '<p>Loading...</p>';
  33. const [allPrices, recipes, buildings] = await Promise.all([
  34. cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json') as Promise<RawPrice[]>,
  35. recipeForMats(),
  36. cachedFetchJSON('https://api.prunplanner.org/data/buildings/') as Promise<Building[]>,
  37. ]);
  38. const prices = Object.fromEntries(allPrices.filter((price) => price.ExchangeCode === 'IC1')
  39. .map((price) => [price.MaterialTicker, price]));
  40. const production: Production = {};
  41. const analysisNodes: AnalysisNode[] = [];
  42. let cost = 0;
  43. for (const [mat, amount] of Object.entries(blueprint)) {
  44. const { cost: matCost, node } = analyzeMat(mat, amount, production, prices, recipes);
  45. cost += matCost;
  46. analysisNodes.push(node);
  47. }
  48. const expertiseGroups: Record<string, string[]> = {};
  49. for (const building of buildings) {
  50. if (!(building.building_ticker in production))
  51. continue;
  52. if (!expertiseGroups[building.expertise])
  53. expertiseGroups[building.expertise] = [];
  54. expertiseGroups[building.expertise].push(building.building_ticker);
  55. }
  56. main.innerHTML = '';
  57. main.append(
  58. renderAnalysis(analysisNodes),
  59. element('p', {textContent: `total cost: ${formatWhole(cost)}`}),
  60. renderProduction(expertiseGroups, production, prices),
  61. element('h2', {textContent: 'buy'}),
  62. element('p', {textContent: Array.from(buy).join(', ')}),
  63. );
  64. }
  65. async function recipeForMats(): Promise<Record<string, Recipe>> {
  66. const allRecipes: Recipe[] = await cachedFetchJSON('https://api.prunplanner.org/data/recipes/');
  67. const matRecipes: Record<string, Recipe[]> = {}; // all ways to make a mat
  68. for (const recipe of allRecipes)
  69. for (const output of recipe.outputs) {
  70. const recipes = matRecipes[output.material_ticker];
  71. if (recipes)
  72. recipes.push(recipe);
  73. else
  74. matRecipes[output.material_ticker] = [recipe];
  75. }
  76. const matRecipe: Record<string, Recipe> = {}; // mats for which there's only one recipe to make
  77. for (const [mat, recipes] of Object.entries(matRecipes))
  78. if (recipes.length === 1)
  79. matRecipe[mat] = recipes[0];
  80. return matRecipe;
  81. }
  82. function analyzeMat(mat: string, amount: number, production: Production,
  83. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>): { cost: number, node: AnalysisNode } {
  84. const price = prices[mat];
  85. if (!price)
  86. throw new Error(`missing price for ${mat}`);
  87. const traded = price.AverageTraded30D ?? 0;
  88. if (buy.has(mat)) {
  89. if (price.Ask == null)
  90. throw new Error(`missing ask price for ${mat}`);
  91. return {
  92. cost: price.Ask * amount,
  93. node: { text: `${formatAmount(amount)}x${mat} buy: ${formatAmount(price.Ask)}, daily traded ${formatFixed(traded, 1)}`, children: [] },
  94. };
  95. }
  96. const recipe = recipes[mat];
  97. if (!recipe)
  98. return { cost: 0, node: { text: `${formatAmount(amount)}x${mat} make (unknown recipe)`, children: [] } };
  99. const building = recipe.building_ticker;
  100. if (!production[building])
  101. production[building] = {};
  102. production[building][mat] = (production[building][mat] ?? 0) + amount;
  103. const liquid = traded > amount * 2 ? 'liquid' : 'not liquid';
  104. let totalCost = 0;
  105. const children: AnalysisNode[] = [];
  106. for (const inputMat of recipe.inputs) {
  107. const inputAmount = inputMat.material_amount * amount / recipe.outputs[0].material_amount;
  108. const { cost, node } = analyzeMat(inputMat.material_ticker, inputAmount, production, prices, recipes);
  109. totalCost += cost;
  110. children.push(node);
  111. }
  112. children.push({ text: `cost: ${formatWhole(totalCost)}`, children: [] });
  113. return {
  114. cost: totalCost,
  115. node: { text: `${formatAmount(amount)}x${mat} make (${building}, ${liquid})`, children },
  116. };
  117. }
  118. function renderAnalysis(nodes: AnalysisNode[]): HTMLElement {
  119. const section = element('section');
  120. for (const node of nodes)
  121. section.append(renderAnalysisNode(node));
  122. return section;
  123. }
  124. function renderAnalysisNode(node: AnalysisNode, level = 0): HTMLElement {
  125. let el;
  126. if (node.children.length === 0) {
  127. el = element('div', {textContent: node.text, className: 'analysis-node'});
  128. } else {
  129. el = element('details', {className: 'analysis-node', open: true});
  130. el.append(element('summary', {textContent: node.text}));
  131. for (const child of node.children)
  132. el.append(renderAnalysisNode(child, level + 1));
  133. }
  134. if (level === 0)
  135. el.classList.add('root');
  136. return el;
  137. }
  138. function renderProduction(expertiseGroups: Record<string, string[]>, production: Production,
  139. prices: Record<string, RawPrice>): HTMLElement {
  140. const section = element('section');
  141. section.append(element('h2', {textContent: 'production'}));
  142. for (const [expertise, buildings] of Object.entries(expertiseGroups)) {
  143. section.append(element('h3', {textContent: expertise}));
  144. for (const building of buildings) {
  145. const buildingRow = element('div', {className: 'building-row', textContent: building});
  146. const buildingMats = element('div');
  147. const mats = Object.entries(production[building]);
  148. for (const [index, [mat, amount]] of mats.entries()) {
  149. const traded = prices[mat]?.AverageTraded30D ?? 0;
  150. const span = element('span', {
  151. textContent: `${formatAmount(amount)}x${mat}`,
  152. });
  153. span.style.color = traded > amount * 2 ? '#6c6' : '#c66';
  154. buildingMats.append(span);
  155. if (index < mats.length - 1)
  156. buildingMats.append(document.createTextNode(' '));
  157. }
  158. buildingRow.append(buildingMats);
  159. section.append(buildingRow);
  160. }
  161. }
  162. return section;
  163. }
  164. function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
  165. properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
  166. const node = document.createElement(tagName);
  167. Object.assign(node, properties);
  168. return node;
  169. }
  170. function formatAmount(n: number): string {
  171. return n.toLocaleString(undefined, {maximumFractionDigits: 3});
  172. }
  173. function formatFixed(n: number, digits: number): string {
  174. return n.toLocaleString(undefined, {
  175. minimumFractionDigits: digits,
  176. maximumFractionDigits: digits,
  177. });
  178. }
  179. function formatWhole(n: number): string {
  180. return n.toLocaleString(undefined, {maximumFractionDigits: 0});
  181. }
  182. interface AnalysisNode {
  183. text: string
  184. children: AnalysisNode[]
  185. }
  186. interface Recipe {
  187. recipe_name: string
  188. building_ticker: string
  189. inputs: RecipeMat[]
  190. outputs: RecipeMat[]
  191. time_ms: number
  192. }
  193. interface RecipeMat {
  194. material_ticker: string
  195. material_amount: number
  196. }
  197. interface RawPrice {
  198. MaterialTicker: string
  199. ExchangeCode: string
  200. Ask: number | null
  201. AverageTraded30D: number | null
  202. Supply: number
  203. }
  204. interface Building {
  205. building_ticker: string
  206. expertise: string
  207. }
  208. type Production = Record<string, Record<string, number>>;