production.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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, storage, 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, storage: Record<string, number>,
  196. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>, buildings: Record<string, Building>): HTMLElement {
  197. const section = element('section');
  198. section.append(element('h2', {textContent: 'production'}));
  199. const matInputs: Record<string, {upstreamMat: string, amount: number}[]> = {};
  200. // mat → list of {outputMat, expertise, amount} that consume it as an input
  201. const matConsumers: Record<string, {downstreamMat: string, expertise: string, amount: number}[]> = {};
  202. for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
  203. for (const building of productionBuildings) {
  204. for (const [mat, totalAmount] of Object.entries(production[building])) {
  205. const recipe = recipes[mat];
  206. if (!matInputs[mat])
  207. matInputs[mat] = [];
  208. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  209. for (const input of recipe.inputs) {
  210. const ticker = input.material_ticker;
  211. const amount = input.material_amount * totalAmount / outputPerRun;
  212. matInputs[mat].push({upstreamMat: ticker, amount});
  213. if (!matConsumers[ticker])
  214. matConsumers[ticker] = [];
  215. matConsumers[ticker].push({downstreamMat: mat, expertise, amount});
  216. }
  217. }
  218. }
  219. }
  220. let totalConsumablesCost = 0;
  221. for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
  222. section.append(element('h3', {textContent: expertise.toLocaleLowerCase()}));
  223. const shipTo: Record<string, Record<string, number>> = {};
  224. for (const building of productionBuildings) {
  225. const buildingMats = element('div');
  226. const mats = Object.entries(production[building]);
  227. let buildingMins = 0;
  228. for (const [mat, amount] of mats) {
  229. buildingMats.append(document.createTextNode(' '));
  230. buildingMats.append(renderProductionBuildingMat(expertise, mat, amount, storage,
  231. matInputs, matConsumers, shipTo));
  232. const recipe = recipes[mat];
  233. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  234. buildingMins += amount / outputPerRun * (recipe.time_ms / 1000 / 60);
  235. }
  236. const numBuildings = buildingMins / (24*60) / 5 / 1.605; // one ship every 5 days, 160.5% efficiency
  237. const consumablesCost = buildingDailyCost(buildings[building], prices) * Math.round(Math.max(1, numBuildings));
  238. totalConsumablesCost += consumablesCost;
  239. const buildingRow = element('div', {className: 'building-row',
  240. textContent: `${formatFixed(numBuildings, 1)}x${building} (${formatWhole(consumablesCost)}/d)`});
  241. buildingRow.append(buildingMats);
  242. section.append(buildingRow);
  243. }
  244. const shipToDetails = element('details');
  245. shipToDetails.append(element('summary', {textContent: 'ship to'}));
  246. for (const [expertise, mats] of Object.entries(shipTo)) {
  247. const shipToRow = element('div', {textContent: expertise.toLocaleLowerCase() + ': '});
  248. shipToRow.textContent += Object.entries(mats).map(([mat, amount]) => `${amount}x${mat}`).join(' ');
  249. shipToDetails.append(shipToRow);
  250. }
  251. section.append(shipToDetails);
  252. }
  253. section.append(element('h4', {textContent: `total consumables cost: ${formatWhole(totalConsumablesCost)}/day,
  254. ${formatWhole(totalConsumablesCost * 5)}/ship`}));
  255. return section;
  256. }
  257. function renderProductionBuildingMat(expertise: string, mat: string, amount: number, storage: Record<string, number>,
  258. matInputs: Record<string, {upstreamMat: string, amount: number}[]>,
  259. matConsumers: Record<string, {downstreamMat: string, expertise: string, amount: number}[]>,
  260. shipTo: Record<string, Record<string, number>>): HTMLElement {
  261. const inStorage = storage[mat] ?? 0;
  262. const span = element('span', {textContent: `${formatAmount(amount)}x${mat} (${inStorage})`});
  263. const percent = Math.min(inStorage / (amount * 2), 1);
  264. span.style.color = `color-mix(in xyz, #0aa ${percent * 100}%, #f80 )`;
  265. let tooltip = '';
  266. const inputs = matInputs[mat];
  267. if (inputs)
  268. tooltip += inputs.map((i) => `${formatAmount(i.amount)}x${i.upstreamMat} (${storage[i.upstreamMat] ?? 0}) → ` +
  269. `${formatAmount(amount)}x${mat}`).join('\n') + '\n';
  270. const consumers = matConsumers[mat];
  271. if (consumers) {
  272. tooltip += consumers
  273. .map((c) => `${formatAmount(c.amount)}x${mat} → ${c.downstreamMat} (${c.expertise.toLocaleLowerCase()})`)
  274. .join('\n');
  275. for (const consumer of consumers) {
  276. if (consumer.expertise == expertise) // we aren't shipping it anywhere
  277. continue;
  278. if (!shipTo[consumer.expertise])
  279. shipTo[consumer.expertise] = {};
  280. shipTo[consumer.expertise][mat] = (shipTo[consumer.expertise][mat] ?? 0) + consumer.amount;
  281. }
  282. }
  283. span.dataset.tooltip = tooltip;
  284. return span;
  285. }
  286. async function fetchStorage(): Promise<Record<string, number>> {
  287. if (!apiKey.value)
  288. return {};
  289. const users = await fetch('https://api.punoted.net/v1/storages/', {headers: {'X-Data-Token': apiKey.value}})
  290. .then((r) => r.json()) as PUNUserStore[];
  291. const items: Record<string, number> = {};
  292. for (const user of users)
  293. for (const storage of user.Storages)
  294. for (const item of storage.StorageItems)
  295. items[item.MaterialTicker] = (items[item.MaterialTicker] ?? 0) + item.MaterialAmount;
  296. return items;
  297. }
  298. function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
  299. properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
  300. const node = document.createElement(tagName);
  301. Object.assign(node, properties);
  302. return node;
  303. }
  304. function formatAmount(n: number): string {
  305. return n.toLocaleString(undefined, {maximumFractionDigits: 3});
  306. }
  307. function formatFixed(n: number, digits: number): string {
  308. return n.toLocaleString(undefined, {
  309. minimumFractionDigits: digits,
  310. maximumFractionDigits: digits,
  311. });
  312. }
  313. function formatWhole(n: number): string {
  314. return n.toLocaleString(undefined, {maximumFractionDigits: 0});
  315. }
  316. interface AnalysisNode {
  317. ticker: string
  318. amount: number
  319. inStorage: number
  320. acquisition: string
  321. children: AnalysisNode[]
  322. cost: number
  323. }
  324. interface Recipe {
  325. recipe_name: string
  326. building_ticker: string
  327. inputs: RecipeMat[]
  328. outputs: RecipeMat[]
  329. time_ms: number
  330. }
  331. interface RecipeMat {
  332. material_ticker: string
  333. material_amount: number
  334. }
  335. interface RawPrice {
  336. MaterialTicker: string
  337. ExchangeCode: string
  338. Ask: number | null
  339. AverageTraded30D: number | null
  340. VWAP30D: number | null
  341. Supply: number
  342. }
  343. interface Building {
  344. building_ticker: string
  345. expertise: string
  346. pioneers: number
  347. settlers: number
  348. technicians: number
  349. engineers: number
  350. scientists: number
  351. }
  352. interface PUNUserStore {
  353. Storages: Array<{
  354. StorageItems: Array<{
  355. MaterialTicker: string
  356. MaterialAmount: number
  357. }>
  358. }>
  359. }
  360. type Production = Record<string, Record<string, number>>;