production.ts 19 KB

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