production.ts 15 KB

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