production.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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, 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, 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<Record<string, Recipe>> {
  91. const allRecipes: Recipe[] = await cachedFetchJSON('https://api.prunplanner.org/data/recipes/');
  92. const matRecipes: Record<string, Recipe[]> = {}; // all ways to make a mat
  93. for (const recipe of allRecipes)
  94. for (const output of recipe.outputs) {
  95. const recipes = matRecipes[output.material_ticker];
  96. if (recipes)
  97. recipes.push(recipe);
  98. else
  99. matRecipes[output.material_ticker] = [recipe];
  100. }
  101. const matRecipe: Record<string, Recipe> = {}; // mats for which there's only one recipe to make
  102. for (const [mat, recipes] of Object.entries(matRecipes))
  103. if (recipes.length === 1)
  104. matRecipe[mat] = recipes[0];
  105. return matRecipe;
  106. }
  107. function analyzeMat(mat: string, amount: number, production: Production, extract: Record<string, number>, buy: Record<string, number>,
  108. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>, storage: Record<string, number>): AnalysisNode {
  109. const price = prices[mat];
  110. if (!price)
  111. throw new Error(`missing price for ${mat}`);
  112. const traded = price.AverageTraded30D ?? 0;
  113. const inStorage = storage[mat] ?? 0;
  114. if (BUY.has(mat)) {
  115. const matPrice = price.VWAP30D ?? price.Ask;
  116. if (matPrice == null) throw new Error(`missing ask price for ${mat}`);
  117. buy[mat] = (buy[mat] ?? 0) + amount;
  118. return {
  119. ticker: mat,
  120. amount,
  121. inStorage,
  122. acquisition: `buy: ${formatAmount(matPrice)}, daily traded ${formatFixed(traded, 1)}`,
  123. children: [],
  124. cost: matPrice * amount,
  125. };
  126. }
  127. const recipe = recipes[mat];
  128. if (!recipe) {
  129. extract[mat] = (extract[mat] ?? 0) + amount;
  130. return {ticker: mat, amount, inStorage, acquisition: `extract`, children: [], cost: 0};
  131. }
  132. const building = recipe.building_ticker;
  133. if (!production[building])
  134. production[building] = {};
  135. production[building][mat] = (production[building][mat] ?? 0) + amount;
  136. const liquid = traded > amount * 2 ? 'liquid' : 'not liquid';
  137. let totalCost = 0;
  138. const children: AnalysisNode[] = [];
  139. for (const inputMat of recipe.inputs) {
  140. const inputAmount = inputMat.material_amount * amount / recipe.outputs[0].material_amount;
  141. const node = analyzeMat(inputMat.material_ticker, inputAmount, production, extract, buy, prices, recipes, storage);
  142. totalCost += node.cost;
  143. children.push(node);
  144. }
  145. return {
  146. ticker: mat,
  147. amount,
  148. inStorage,
  149. acquisition: `make (${building}, ${liquid})`,
  150. children,
  151. cost: totalCost,
  152. };
  153. }
  154. function renderAnalysis(nodes: AnalysisNode[]): HTMLElement {
  155. const section = element('section');
  156. for (const node of nodes)
  157. section.append(renderAnalysisNode(node));
  158. return section;
  159. }
  160. function renderAnalysisNode(node: AnalysisNode, level = 0): HTMLElement {
  161. const amountText = element('span', {textContent: `${formatAmount(node.amount)}x${node.ticker} `});
  162. const storageText = element('span', {textContent: `(${formatAmount(node.inStorage)})`});
  163. const percent = Math.min(node.inStorage / node.amount, 1);
  164. storageText.style.color = `color-mix(in xyz, #0aa ${percent * 100}%, #f80 )`;
  165. const acquisitionText = element('span', {textContent: ' ' + node.acquisition});
  166. let el;
  167. if (node.children.length === 0) {
  168. el = element('div', {className: 'analysis-node'});
  169. el.append(amountText, storageText, acquisitionText);
  170. } else {
  171. el = element('details', {className: 'analysis-node', open: level > 0 && percent < 1});
  172. const summary = element('summary');
  173. summary.append(amountText, storageText, acquisitionText);
  174. el.append(summary);
  175. for (const child of node.children)
  176. el.append(renderAnalysisNode(child, level + 1));
  177. el.append(document.createTextNode(`total cost: ${formatWhole(node.cost)}`));
  178. }
  179. if (level === 0)
  180. el.classList.add('root');
  181. return el;
  182. }
  183. const WORKER_CONSUMPTION: Record<'pioneers' | 'settlers' | 'technicians' | 'engineers' | 'scientists', Record<string, number>> = {
  184. pioneers: {'COF': 0.5, 'DW': 4, 'RAT': 4, 'OVE': 0.5, 'PWO': 0.2},
  185. settlers: {'DW': 5, 'RAT': 6, 'KOM': 1, 'EXO': 0.5, 'REP': 0.2, 'PT': 0.5},
  186. technicians: {'DW': 7.5, 'RAT': 7, 'ALE': 1, 'MED': 0.5, 'SC': 0.1, 'HMS': 0.5, 'SCN': 0.1},
  187. engineers: {'DW': 10, 'MED': 0.5, 'GIN': 1, 'FIM': 7, 'VG': 0.2, 'HSS': 0.2, 'PDA': 0.1},
  188. scientists: {'DW': 10, 'MED': 0.5, 'WIN': 1, 'MEA': 7, 'NST': 0.1, 'LC': 0.2, 'WS': 0.05},
  189. };
  190. function buildingDailyCost(building: Building, prices: Record<string, RawPrice>): number {
  191. let cost = 0;
  192. for (const [workerType, mats] of Object.entries(WORKER_CONSUMPTION)) {
  193. const workers = building[workerType as keyof typeof WORKER_CONSUMPTION];
  194. for (const [mat, per100] of Object.entries(mats)) {
  195. const price = prices[mat].VWAP30D;
  196. if (price == null) throw new Error(`no price for ${mat}`);
  197. cost += price * workers * per100 / 100;
  198. }
  199. }
  200. return cost;
  201. }
  202. function renderProduction(expertiseGroups: Record<string, string[]>, production: Production, storage: Record<string, number>,
  203. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>, buildings: Record<string, Building>): HTMLElement {
  204. const section = element('section');
  205. section.append(element('h2', {textContent: 'production'}));
  206. const matInputs: Record<string, {upstreamMat: string, amount: number}[]> = {};
  207. // mat → list of {outputMat, expertise, amount} that consume it as an input
  208. const matConsumers: Record<string, {downstreamMat: string, expertise: string, amount: number}[]> = {};
  209. for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
  210. for (const building of productionBuildings) {
  211. for (const [mat, totalAmount] of Object.entries(production[building])) {
  212. const recipe = recipes[mat];
  213. if (!matInputs[mat])
  214. matInputs[mat] = [];
  215. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  216. for (const input of recipe.inputs) {
  217. const ticker = input.material_ticker;
  218. const amount = input.material_amount * totalAmount / outputPerRun;
  219. matInputs[mat].push({upstreamMat: ticker, amount});
  220. if (!matConsumers[ticker])
  221. matConsumers[ticker] = [];
  222. matConsumers[ticker].push({downstreamMat: mat, expertise, amount});
  223. }
  224. }
  225. }
  226. }
  227. let totalConsumablesCost = 0;
  228. for (const [expertise, productionBuildings] of Object.entries(expertiseGroups)) {
  229. section.append(element('h3', {textContent: expertise.toLocaleLowerCase()}));
  230. const shipTo: Record<string, Record<string, number>> = {};
  231. for (const building of productionBuildings) {
  232. const buildingRow = element('div', {className: 'building-row'});
  233. const mats = Object.entries(production[building]);
  234. let buildingMins = 0;
  235. for (const [mat, amount] of mats) {
  236. buildingRow.append(document.createTextNode(' '));
  237. buildingRow.append(renderProductionBuildingMat(expertise, mat, amount, storage,
  238. matInputs, matConsumers, shipTo));
  239. const recipe = recipes[mat];
  240. const outputPerRun = recipe.outputs.find((o) => o.material_ticker === mat)!.material_amount;
  241. buildingMins += amount / outputPerRun * (recipe.time_ms / 1000 / 60);
  242. }
  243. const numBuildings = buildingMins / (24*60) / daysPerBundle / 1.605; // 160.5% efficiency
  244. const consumablesCost = buildingDailyCost(buildings[building], prices) * Math.round(Math.max(1, numBuildings));
  245. totalConsumablesCost += consumablesCost;
  246. buildingRow.prepend(document.createTextNode(
  247. `${formatFixed(numBuildings, 1)}x${building} (${formatWhole(consumablesCost)}/d)`));
  248. section.append(buildingRow);
  249. }
  250. const shipToDetails = element('details');
  251. shipToDetails.append(element('summary', {textContent: 'ship to'}));
  252. for (const [expertise, mats] of Object.entries(shipTo)) {
  253. const shipToRow = element('div', {textContent: expertise.toLocaleLowerCase() + ': '});
  254. shipToRow.textContent += Object.entries(mats).map(([mat, amount]) => `${amount}x${mat}`).join(' ');
  255. shipToDetails.append(shipToRow);
  256. }
  257. section.append(shipToDetails);
  258. }
  259. section.append(element('h4', {textContent: `total consumables cost: ${formatWhole(totalConsumablesCost)}/day,
  260. ${formatWhole(totalConsumablesCost * daysPerBundle)}/bundle`}));
  261. return section;
  262. }
  263. function renderProductionBuildingMat(expertise: string, mat: string, amount: number, storage: Record<string, number>,
  264. matInputs: Record<string, {upstreamMat: string, amount: number}[]>,
  265. matConsumers: Record<string, {downstreamMat: string, expertise: string, amount: number}[]>,
  266. shipTo: Record<string, Record<string, number>>): HTMLElement {
  267. const inStorage = storage[mat] ?? 0;
  268. const wrapper = element('span');
  269. const amountText = element('span', {textContent: `${formatAmount(amount)}x${mat}`});
  270. wrapper.append(amountText);
  271. const storageText = element('span', {textContent: ` (${formatAmount(inStorage)})`});
  272. wrapper.append(storageText);
  273. const percent = Math.min(inStorage / (amount * 2), 1);
  274. storageText.style.color = `color-mix(in xyz, #0aa ${percent * 100}%, #f80 )`;
  275. if (percent >= 1)
  276. amountText.style.color = '#777';
  277. else {
  278. const produceable = Object.values(matInputs[mat]).every((input) => storage[input.upstreamMat] ?? 0 >= input.amount);
  279. amountText.style.color = produceable ? '#0aa' : '#f80';
  280. }
  281. let tooltip = '';
  282. const inputs = matInputs[mat];
  283. if (inputs)
  284. tooltip += inputs.map((i) => `${formatAmount(i.amount)}x${i.upstreamMat} (${storage[i.upstreamMat] ?? 0}) → ` +
  285. `${formatAmount(amount)}x${mat}`).join('\n') + '\n';
  286. const consumers = matConsumers[mat];
  287. if (consumers) {
  288. tooltip += consumers
  289. .map((c) => `${formatAmount(c.amount)}x${mat} → ${c.downstreamMat} (${c.expertise.toLocaleLowerCase()})`)
  290. .join('\n');
  291. for (const consumer of consumers) {
  292. if (consumer.expertise == expertise) // we aren't shipping it anywhere
  293. continue;
  294. if (!shipTo[consumer.expertise])
  295. shipTo[consumer.expertise] = {};
  296. shipTo[consumer.expertise][mat] = (shipTo[consumer.expertise][mat] ?? 0) + consumer.amount;
  297. }
  298. }
  299. amountText.dataset.tooltip = tooltip;
  300. return wrapper;
  301. }
  302. async function fetchStorage(): Promise<Record<string, number>> {
  303. if (!apiKey.value)
  304. return {};
  305. const users = await fetch('https://api.punoted.net/v1/storages/', {headers: {'X-Data-Token': apiKey.value}})
  306. .then((r) => r.json()) as PUNUserStore[];
  307. const items: Record<string, number> = {};
  308. for (const user of users)
  309. for (const storage of user.Storages)
  310. for (const item of storage.StorageItems)
  311. items[item.MaterialTicker] = (items[item.MaterialTicker] ?? 0) + item.MaterialAmount;
  312. return items;
  313. }
  314. function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
  315. properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
  316. const node = document.createElement(tagName);
  317. Object.assign(node, properties);
  318. return node;
  319. }
  320. function formatAmount(n: number): string {
  321. return n.toLocaleString(undefined, {maximumFractionDigits: 3});
  322. }
  323. function formatFixed(n: number, digits: number): string {
  324. return n.toLocaleString(undefined, {
  325. minimumFractionDigits: digits,
  326. maximumFractionDigits: digits,
  327. });
  328. }
  329. function formatWhole(n: number): string {
  330. return n.toLocaleString(undefined, {maximumFractionDigits: 0});
  331. }
  332. interface AnalysisNode {
  333. ticker: string
  334. amount: number
  335. inStorage: number
  336. acquisition: string
  337. children: AnalysisNode[]
  338. cost: number
  339. }
  340. interface Recipe {
  341. recipe_name: string
  342. building_ticker: string
  343. inputs: RecipeMat[]
  344. outputs: RecipeMat[]
  345. time_ms: number
  346. }
  347. interface RecipeMat {
  348. material_ticker: string
  349. material_amount: number
  350. }
  351. interface RawPrice {
  352. MaterialTicker: string
  353. ExchangeCode: string
  354. Ask: number | null
  355. AverageTraded30D: number | null
  356. VWAP30D: number | null
  357. Supply: number
  358. }
  359. interface Building {
  360. building_ticker: string
  361. expertise: string
  362. pioneers: number
  363. settlers: number
  364. technicians: number
  365. engineers: number
  366. scientists: number
  367. }
  368. interface PUNUserStore {
  369. Storages: Array<{
  370. StorageItems: Array<{
  371. MaterialTicker: string
  372. MaterialAmount: number
  373. }>
  374. }>
  375. }
  376. type Production = Record<string, Record<string, number>>;