production.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import {cachedFetchJSON} from './cache';
  2. import {setupPopover} from './popover';
  3. let blueprint: Record<string, number>;
  4. let BUY: Set<string>;
  5. let renderTarget: Element;
  6. let cx: string;
  7. let daysPerBundle: number;
  8. const apiKey = document.querySelector('#api-key') as HTMLInputElement;
  9. export function setupProduction(bp: Record<string, number>, buy: Set<string>, cxCode: string, days: number, target: Element) {
  10. blueprint = bp;
  11. BUY = buy;
  12. cx = cxCode;
  13. daysPerBundle = days;
  14. renderTarget = target;
  15. const storedApiKey = localStorage.getItem('punoted-api-key');
  16. if (storedApiKey)
  17. apiKey.value = storedApiKey;
  18. document.querySelector('#fetch')!.addEventListener('click', render);
  19. setupPopover();
  20. render();
  21. }
  22. async function render() {
  23. const loader = document.querySelector('#loader') as HTMLElement;
  24. loader.style.display = 'block';
  25. try {
  26. await _render();
  27. if (apiKey.value)
  28. localStorage.setItem('punoted-api-key', apiKey.value);
  29. } catch (e) {
  30. renderTarget.innerHTML = e instanceof Error ? e.message : String(e);
  31. }
  32. loader.style.display = 'none';
  33. }
  34. async function _render() {
  35. const [allPrices, {recipes, extractables}, buildingList, storage] = await Promise.all([
  36. cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json') as Promise<RawPrice[]>,
  37. recipeForMats(),
  38. cachedFetchJSON('https://api.prunplanner.org/data/buildings/') as Promise<Building[]>,
  39. fetchStorage(),
  40. ]);
  41. const prices = Object.fromEntries(allPrices.filter((price) => price.ExchangeCode === cx)
  42. .map((price) => [price.MaterialTicker, price]));
  43. const buildings = Object.fromEntries(buildingList.map((b) => [b.building_ticker, b]));
  44. const production: Production = {};
  45. const extract: Record<string, number> = {};
  46. const buy: Record<string, number> = {};
  47. const analysisNodes: AnalysisNode[] = [];
  48. let cost = 0;
  49. for (const [mat, amount] of Object.entries(blueprint)) {
  50. const node = analyzeMat(mat, amount, production, extract, buy, prices, recipes, extractables, storage);
  51. cost += node.cost;
  52. analysisNodes.push(node);
  53. }
  54. // requiredMats = buy + production
  55. const requiredMats: Record<string, number> = {...buy};
  56. for (const buildingProduction of Object.values(production))
  57. for (const [mat, amount] of Object.entries(buildingProduction))
  58. requiredMats[mat] = (requiredMats[mat] ?? 0) + amount;
  59. const expertiseGroups: Record<string, string[]> = {};
  60. for (const building of buildingList) {
  61. if (!(building.building_ticker in production))
  62. continue;
  63. if (!expertiseGroups[building.expertise])
  64. expertiseGroups[building.expertise] = [];
  65. expertiseGroups[building.expertise].push(building.building_ticker);
  66. }
  67. renderTarget.innerHTML = '';
  68. renderTarget.append(
  69. renderAnalysis(analysisNodes),
  70. element('p', {textContent: `total cost: ${formatWhole(cost)}`}),
  71. renderProduction(expertiseGroups, production, storage, prices, recipes, buildings),
  72. renderMatList('extract', extract, storage),
  73. renderMatList('buy', buy, storage),
  74. );
  75. }
  76. function renderMatList(header: string, mats: Record<string, number>, storage: Record<string, number>): HTMLElement {
  77. const section = element('section');
  78. section.append(element('h2', {textContent: header}));
  79. const matsSorted = Object.entries(mats).sort(([a], [b]) => a.localeCompare(b));
  80. for (const [mat, amount] of matsSorted) {
  81. const div = element('div', {textContent: `${formatAmount(amount)}x${mat}`});
  82. const storageText = element('span', {textContent: ` (${formatAmount(storage[mat] ?? 0)})`});
  83. const percent = Math.min((storage[mat] ?? 0) / (amount * 2), 1);
  84. storageText.style.color = `color-mix(in xyz, #0aa ${percent * 100}%, #f80 )`;
  85. div.append(storageText);
  86. section.append(div);
  87. }
  88. return section;
  89. }
  90. async function recipeForMats(): Promise<{recipes: Record<string, Recipe>, extractables: Set<string>}> {
  91. const [allRecipes, materials]: [Recipe[], Material[]] = await Promise.all([
  92. cachedFetchJSON('https://api.prunplanner.org/data/recipes/'),
  93. cachedFetchJSON('https://api.prunplanner.org/data/materials/'),
  94. ]);
  95. const extractables = new Set(materials.filter(
  96. (m) => ['ores', 'minerals', 'liquids', 'gases'].includes(m.category_name)).map((m) => m.ticker));
  97. const chosenRecipes: Record<string, string> = {
  98. 'AL': '6xALO 1xO 1xC 1xFLX=>4xAL',
  99. 'C': '4xHCP=>4xC',
  100. 'DRF': '50xNFI 1xDCS=>1xDRF',
  101. 'FE': '6xFEO 1xC 1xO 1xFLX=>4xFE',
  102. 'GL': '2xSIO 1xNA 1xSEN=>10xGL',
  103. 'HCP': '14xH2O 1xNS=>8xHCP',
  104. 'RE': '8xREO 1xC 1xO 1xFLX=>5xRE',
  105. 'RG': '10xGL 15xPG 1xSEN=>10xRG',
  106. 'SI': '3xSIO 1xC 1xO 1xFLX=>1xSI',
  107. }
  108. const matRecipes: Record<string, Recipe[]> = {}; // all ways to make a mat
  109. for (const recipe of allRecipes)
  110. for (const output of recipe.outputs) {
  111. if (extractables.has(output.material_ticker))
  112. continue;
  113. if (chosenRecipes[output.material_ticker] && recipe.recipe_name != chosenRecipes[output.material_ticker])
  114. continue;
  115. const recipes = matRecipes[output.material_ticker];
  116. if (recipes)
  117. recipes.push(recipe);
  118. else
  119. matRecipes[output.material_ticker] = [recipe];
  120. }
  121. const matRecipe: Record<string, Recipe> = {};
  122. for (const [mat, recipes] of Object.entries(matRecipes))
  123. if (recipes.length === 1)
  124. matRecipe[mat] = recipes[0];
  125. return {recipes: matRecipe, extractables};
  126. }
  127. function analyzeMat(mat: string, amount: number, production: Production, extract: Record<string, number>, buy: Record<string, number>,
  128. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>, extractables: Set<string>, storage: Record<string, number>): AnalysisNode {
  129. const price = prices[mat];
  130. if (!price)
  131. throw new Error(`missing price for ${mat}`);
  132. const traded = price.AverageTraded30D ?? 0;
  133. const inStorage = storage[mat] ?? 0;
  134. if (BUY.has(mat)) {
  135. const matPrice = price.VWAP30D ?? price.Ask;
  136. if (matPrice == null) throw new Error(`missing ask price for ${mat}`);
  137. buy[mat] = (buy[mat] ?? 0) + amount;
  138. return {
  139. ticker: mat,
  140. amount,
  141. inStorage,
  142. acquisition: `buy: ${formatAmount(matPrice)}, daily traded ${formatFixed(traded, 1)}`,
  143. children: [],
  144. cost: matPrice * amount,
  145. };
  146. }
  147. if (extractables.has(mat)) {
  148. extract[mat] = (extract[mat] ?? 0) + amount;
  149. return {ticker: mat, amount, inStorage, acquisition: `extract`, children: [], cost: 0};
  150. }
  151. const recipe = recipes[mat];
  152. if (!recipe)
  153. throw new Error(`no recipe for ${mat}`);
  154. const building = recipe.building_ticker;
  155. if (!production[building])
  156. production[building] = {};
  157. production[building][mat] = (production[building][mat] ?? 0) + amount;
  158. const liquid = traded > amount * 2 ? 'liquid' : 'not liquid';
  159. let totalCost = 0;
  160. const children: AnalysisNode[] = [];
  161. for (const inputMat of recipe.inputs) {
  162. const inputAmount = inputMat.material_amount * amount / recipe.outputs[0].material_amount;
  163. const node = analyzeMat(inputMat.material_ticker, inputAmount, production, extract, buy, prices, recipes, extractables, storage);
  164. totalCost += node.cost;
  165. children.push(node);
  166. }
  167. return {
  168. ticker: mat,
  169. amount,
  170. inStorage,
  171. acquisition: `make (${building}, ${liquid})`,
  172. children,
  173. cost: totalCost,
  174. };
  175. }
  176. function renderAnalysis(nodes: AnalysisNode[]): HTMLElement {
  177. const section = element('section');
  178. for (const node of nodes)
  179. section.append(renderAnalysisNode(node));
  180. return section;
  181. }
  182. function renderAnalysisNode(node: AnalysisNode, level = 0): HTMLElement {
  183. const amountText = element('span', {textContent: `${formatAmount(node.amount)}x${node.ticker} `});
  184. const storageText = element('span', {textContent: `(${formatAmount(node.inStorage)})`});
  185. const percent = Math.min(node.inStorage / node.amount, 1);
  186. storageText.style.color = `color-mix(in xyz, #0aa ${percent * 100}%, #f80 )`;
  187. const acquisitionText = element('span', {textContent: ' ' + node.acquisition});
  188. let el;
  189. if (node.children.length === 0) {
  190. el = element('div', {className: 'analysis-node'});
  191. el.append(amountText, storageText, acquisitionText);
  192. } else {
  193. el = element('details', {className: 'analysis-node', open: level > 0 && percent < 1});
  194. const summary = element('summary');
  195. summary.append(amountText, storageText, acquisitionText);
  196. el.append(summary);
  197. for (const child of node.children)
  198. el.append(renderAnalysisNode(child, level + 1));
  199. el.append(document.createTextNode(`total cost: ${formatWhole(node.cost)}`));
  200. }
  201. if (level === 0)
  202. el.classList.add('root');
  203. return el;
  204. }
  205. const WORKER_CONSUMPTION: Record<'pioneers' | 'settlers' | 'technicians' | 'engineers' | 'scientists', Record<string, number>> = {
  206. pioneers: {'COF': 0.5, 'DW': 4, 'RAT': 4, 'OVE': 0.5, 'PWO': 0.2},
  207. settlers: {'DW': 5, 'RAT': 6, 'KOM': 1, 'EXO': 0.5, 'REP': 0.2, 'PT': 0.5},
  208. technicians: {'DW': 7.5, 'RAT': 7, 'ALE': 1, 'MED': 0.5, 'SC': 0.1, 'HMS': 0.5, 'SCN': 0.1},
  209. engineers: {'DW': 10, 'MED': 0.5, 'GIN': 1, 'FIM': 7, 'VG': 0.2, 'HSS': 0.2, 'PDA': 0.1},
  210. scientists: {'DW': 10, 'MED': 0.5, 'WIN': 1, 'MEA': 7, 'NST': 0.1, 'LC': 0.2, 'WS': 0.05},
  211. };
  212. function buildingDailyCost(building: Building, prices: Record<string, RawPrice>): number {
  213. let cost = 0;
  214. for (const [workerType, mats] of Object.entries(WORKER_CONSUMPTION)) {
  215. const workers = building[workerType as keyof typeof WORKER_CONSUMPTION];
  216. for (const [mat, per100] of Object.entries(mats)) {
  217. const price = prices[mat].VWAP30D;
  218. if (price == null) throw new Error(`no price for ${mat}`);
  219. cost += price * workers * per100 / 100;
  220. }
  221. }
  222. return cost;
  223. }
  224. function renderProduction(expertiseGroups: Record<string, string[]>, production: Production, storage: Record<string, number>,
  225. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>, buildings: Record<string, Building>): HTMLElement {
  226. const section = element('section');
  227. section.append(element('h2', {textContent: 'production'}));
  228. const matInputs: Record<string, {upstreamMat: string, amount: number}[]> = {};
  229. // mat → list of {outputMat, expertise, amount} that consume it as an input
  230. const matConsumers: Record<string, {downstreamMat: string, expertise: string, amount: number}[]> = {};
  231. for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
  232. for (const building of productionBuildings) {
  233. for (const [mat, totalAmount] of Object.entries(production[building])) {
  234. const recipe = recipes[mat];
  235. if (!matInputs[mat])
  236. matInputs[mat] = [];
  237. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  238. for (const input of recipe.inputs) {
  239. const ticker = input.material_ticker;
  240. const amount = input.material_amount * totalAmount / outputPerRun;
  241. matInputs[mat].push({upstreamMat: ticker, amount});
  242. if (!matConsumers[ticker])
  243. matConsumers[ticker] = [];
  244. matConsumers[ticker].push({downstreamMat: mat, expertise, amount});
  245. }
  246. }
  247. }
  248. }
  249. let totalConsumablesCost = 0;
  250. for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
  251. section.append(element('h3', {textContent: expertise.toLocaleLowerCase()}));
  252. const imports: Record<string, number> = {};
  253. const exportTo: Record<string, Record<string, number>> = {};
  254. for (const building of productionBuildings) {
  255. const buildingRow = element('div', {className: 'building-row'});
  256. const mats = Object.entries(production[building]);
  257. let buildingMins = 0;
  258. for (const [mat, amount] of mats) {
  259. buildingRow.append(document.createTextNode(' '));
  260. buildingRow.append(renderProductionBuildingMat(expertise, mat, amount, storage,
  261. matInputs, matConsumers, imports, exportTo));
  262. const recipe = recipes[mat];
  263. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  264. buildingMins += amount / outputPerRun * (recipe.time_ms / 1000 / 60);
  265. }
  266. const numBuildings = buildingMins / (24*60) / daysPerBundle / 1.605; // 160.5% efficiency
  267. const consumablesCost = buildingDailyCost(buildings[building], prices) * Math.round(Math.max(1, numBuildings));
  268. totalConsumablesCost += consumablesCost;
  269. buildingRow.prepend(document.createTextNode(
  270. `${formatFixed(numBuildings, 1)}x${building} (${formatWhole(consumablesCost)}/d)`));
  271. section.append(buildingRow);
  272. }
  273. const importDetails = element('details');
  274. importDetails.append(element('summary', {textContent: 'imports'}));
  275. for (const [mat, amount] of Object.entries(imports)) {
  276. if (recipes[mat] && buildings[recipes[mat].building_ticker].expertise == expertise)
  277. continue;
  278. importDetails.append(element('div', {textContent: `${formatAmount(amount)}x${mat}`}));
  279. }
  280. section.append(importDetails);
  281. const exportDetails = element('details');
  282. exportDetails.append(element('summary', {textContent: 'exports'}));
  283. for (const [expertise, mats] of Object.entries(exportTo)) {
  284. const exportToRow = element('div', {textContent: expertise.toLocaleLowerCase() + ': '});
  285. exportToRow.textContent += Object.entries(mats).map(([mat, amount]) => `${amount}x${mat}`).join(' ');
  286. exportDetails.append(exportToRow);
  287. }
  288. section.append(exportDetails);
  289. }
  290. section.append(element('h4', {textContent: `total consumables cost: ${formatWhole(totalConsumablesCost)}/day,
  291. ${formatWhole(totalConsumablesCost * daysPerBundle)}/bundle`}));
  292. return section;
  293. }
  294. function renderProductionBuildingMat(expertise: string, mat: string, amount: number, storage: Record<string, number>,
  295. matInputs: Record<string, {upstreamMat: string, amount: number}[]>,
  296. matConsumers: Record<string, {downstreamMat: string, expertise: string, amount: number}[]>,
  297. imports: Record<string, number>, exportTo: Record<string, Record<string, number>>): HTMLElement {
  298. const inStorage = storage[mat] ?? 0;
  299. const wrapper = element('span');
  300. const amountText = element('span', {textContent: `${formatAmount(amount)}x${mat}`});
  301. wrapper.append(amountText);
  302. const storageText = element('span', {textContent: ` (${formatAmount(inStorage)})`});
  303. wrapper.append(storageText);
  304. const percent = Math.min(inStorage / (amount * 2), 1);
  305. storageText.style.color = `color-mix(in xyz, #0aa ${percent * 100}%, #f80 )`;
  306. if (percent >= 1)
  307. amountText.style.color = '#777';
  308. else {
  309. const produceable = Object.values(matInputs[mat]).every((input) => storage[input.upstreamMat] ?? 0 >= input.amount);
  310. amountText.style.color = produceable ? '#0aa' : '#f80';
  311. }
  312. let tooltip = '';
  313. const inputs = matInputs[mat];
  314. if (inputs) {
  315. tooltip += inputs.map((i) => `${formatAmount(i.amount)}x${i.upstreamMat} (${storage[i.upstreamMat] ?? 0}) → ` +
  316. `${formatAmount(amount)}x${mat}`).join('\n') + '\n';
  317. for (const input of inputs)
  318. imports[input.upstreamMat] = (imports[input.upstreamMat] ?? 0) + input.amount;
  319. }
  320. const consumers = matConsumers[mat];
  321. if (consumers) {
  322. tooltip += consumers
  323. .map((c) => `${formatAmount(c.amount)}x${mat} → ${c.downstreamMat} (${c.expertise.toLocaleLowerCase()})`)
  324. .join('\n');
  325. for (const consumer of consumers) {
  326. if (consumer.expertise == expertise) // we aren't shipping it anywhere
  327. continue;
  328. if (!exportTo[consumer.expertise])
  329. exportTo[consumer.expertise] = {};
  330. exportTo[consumer.expertise][mat] = (exportTo[consumer.expertise][mat] ?? 0) + consumer.amount;
  331. }
  332. }
  333. amountText.dataset.tooltip = tooltip;
  334. return wrapper;
  335. }
  336. async function fetchStorage(): Promise<Record<string, number>> {
  337. if (!apiKey.value)
  338. return {};
  339. const users = await fetch('https://api.punoted.net/v1/storages/', {headers: {'X-Data-Token': apiKey.value}})
  340. .then((r) => r.json()) as PUNUserStore[];
  341. const items: Record<string, number> = {};
  342. for (const user of users)
  343. for (const storage of user.Storages)
  344. for (const item of storage.StorageItems)
  345. items[item.MaterialTicker] = (items[item.MaterialTicker] ?? 0) + item.MaterialAmount;
  346. return items;
  347. }
  348. function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
  349. properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
  350. const node = document.createElement(tagName);
  351. Object.assign(node, properties);
  352. return node;
  353. }
  354. function formatAmount(n: number): string {
  355. return n.toLocaleString(undefined, {maximumFractionDigits: 3});
  356. }
  357. function formatFixed(n: number, digits: number): string {
  358. return n.toLocaleString(undefined, {
  359. minimumFractionDigits: digits,
  360. maximumFractionDigits: digits,
  361. });
  362. }
  363. function formatWhole(n: number): string {
  364. return n.toLocaleString(undefined, {maximumFractionDigits: 0});
  365. }
  366. interface AnalysisNode {
  367. ticker: string
  368. amount: number
  369. inStorage: number
  370. acquisition: string
  371. children: AnalysisNode[]
  372. cost: number
  373. }
  374. interface Recipe {
  375. recipe_name: string
  376. building_ticker: string
  377. inputs: RecipeMat[]
  378. outputs: RecipeMat[]
  379. time_ms: number
  380. }
  381. interface RecipeMat {
  382. material_ticker: string
  383. material_amount: number
  384. }
  385. interface Material {
  386. ticker: string
  387. category_name: string
  388. }
  389. interface RawPrice {
  390. MaterialTicker: string
  391. ExchangeCode: string
  392. Ask: number | null
  393. AverageTraded30D: number | null
  394. VWAP30D: number | null
  395. Supply: number
  396. }
  397. interface Building {
  398. building_ticker: string
  399. expertise: string
  400. pioneers: number
  401. settlers: number
  402. technicians: number
  403. engineers: number
  404. scientists: number
  405. }
  406. interface PUNUserStore {
  407. Storages: Array<{
  408. StorageItems: Array<{
  409. MaterialTicker: string
  410. MaterialAmount: number
  411. }>
  412. }>
  413. }
  414. type Production = Record<string, Record<string, number>>;