production.ts 14 KB

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