shipbuilding.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import {cachedFetchJSON} from './cache';
  2. const BUY = new Set([
  3. // definitely buy
  4. 'C', 'FLX', 'H', 'H2O', 'HAL', 'HCP', 'HE', 'LST', 'MG', 'N', 'NA', 'NCS', 'NS', 'O', 'PE', 'PG', 'S', 'TCL', 'THF',
  5. // maybe buy
  6. 'AIR', 'AU', 'BE', 'BRM', 'CU', 'FAN', 'FC', 'FE', 'HCC', 'HD', 'LDI', 'LI', 'MFK', 'MWF', 'REA', 'RG', 'RGO', 'ROM', 'SFK', 'SI', 'STL', 'TI', 'TPU',
  7. // import
  8. 'AAR', 'AWF', 'CAP', 'CF',
  9. // skip
  10. 'LFE', 'LHP', 'MFE', 'SFE', 'SSC',
  11. ])
  12. const blueprint = {
  13. 'FFC': 1,
  14. 'FSE': 1,
  15. 'LFE': 2,
  16. 'MFE': 2,
  17. 'QCR': 1,
  18. 'SFE': 1,
  19. 'LCB': 1,
  20. 'MFL': 1,
  21. 'MSL': 1,
  22. 'LHP': 94,
  23. 'SSC': 128,
  24. 'BR1': 1,
  25. 'CQM': 1,
  26. }
  27. const shipbuilders = [
  28. 'CraftsmanThirteen',
  29. 'EvoV',
  30. 'neke86',
  31. 'SurvivorBob',
  32. 'TRUEnterprises',
  33. ];
  34. render();
  35. async function render() {
  36. const main = document.querySelector('main.shipbuilding');
  37. if (!main)
  38. throw new Error('missing shipbuilding container');
  39. main.innerHTML = '<p>Loading...</p>';
  40. const [allPrices, recipes, buildings, knownCompanies, companyProductionById] = await Promise.all([
  41. cachedFetchJSON('https://refined-prun.github.io/refined-prices/all.json') as Promise<RawPrice[]>,
  42. recipeForMats(),
  43. cachedFetchJSON('https://api.prunplanner.org/data/buildings/') as Promise<Building[]>,
  44. cachedFetchJSON('https://pmmg-products.github.io/reports/data/knownCompanies.json') as Promise<Record<string, {Username: string}>>,
  45. pmmgMonthlyReport(),
  46. ]);
  47. const prices = Object.fromEntries(allPrices.filter((price) => price.ExchangeCode === 'IC1')
  48. .map((price) => [price.MaterialTicker, price]));
  49. const production: Production = {};
  50. const buy: Record<string, number> = {};
  51. const analysisNodes: AnalysisNode[] = [];
  52. let cost = 0;
  53. for (const [mat, amount] of Object.entries(blueprint)) {
  54. const { cost: matCost, node } = analyzeMat(mat, amount, production, buy, prices, recipes);
  55. cost += matCost;
  56. analysisNodes.push(node);
  57. }
  58. // requiredMats = buy + production
  59. const requiredMats: Record<string, number> = {...buy};
  60. for (const buildingProduction of Object.values(production))
  61. for (const [mat, amount] of Object.entries(buildingProduction))
  62. requiredMats[mat] = (requiredMats[mat] ?? 0) + amount;
  63. const expertiseGroups: Record<string, string[]> = {};
  64. for (const building of buildings) {
  65. if (!(building.building_ticker in production))
  66. continue;
  67. if (!expertiseGroups[building.expertise])
  68. expertiseGroups[building.expertise] = [];
  69. expertiseGroups[building.expertise].push(building.building_ticker);
  70. }
  71. main.innerHTML = '';
  72. main.append(
  73. renderAnalysis(analysisNodes),
  74. element('p', {textContent: `total cost: ${formatWhole(cost)}`}),
  75. renderProduction(expertiseGroups, production, prices),
  76. renderBuyMaterials(buy),
  77. renderShipbuilders(requiredMats, knownCompanies, companyProductionById),
  78. );
  79. }
  80. function renderBuyMaterials(buy: Record<string, number>): HTMLElement {
  81. const section = element('section');
  82. section.append(element('h2', {textContent: 'buy'}));
  83. const mats = Object.entries(buy).sort(([a], [b]) => a.localeCompare(b));
  84. section.append(element('p', {
  85. textContent: mats.map(([mat, amount]) => `${formatAmount(amount)}x${mat}`).join(', '),
  86. }));
  87. return section;
  88. }
  89. async function pmmgMonthlyReport(): Promise<PMMGCompanyProduction> {
  90. const constants = await fetch('https://raw.githubusercontent.com/PMMG-Products/pmmg-products.github.io/main/reports/src/staticData/constants.ts')
  91. .then((res) => res.text());
  92. const match = constants.match(/export const months = \[(.*?)\];/s);
  93. if (!match)
  94. throw new Error('failed to parse PMMG months');
  95. const months = match[1].split(',').map((m) => m.trim().replace(/^"|"$/g, ''));
  96. const latestMonth = months.at(-1);
  97. if (!latestMonth)
  98. throw new Error('missing PMMG month');
  99. const report = await cachedFetchJSON(`https://pmmg-products.github.io/reports/data/company-data-${latestMonth}.json`);
  100. return report['individual'];
  101. }
  102. function renderShipbuilders(requiredMats: Record<string, number>,
  103. knownCompanies: Record<string, {Username: string}>, companyProductionById: PMMGCompanyProduction): HTMLElement {
  104. const matTickers = Object.keys(requiredMats).sort();
  105. const shipbuilderSet = new Set(shipbuilders);
  106. const shipbuildersById: Record<string, string> = {};
  107. for (const [companyId, company] of Object.entries(knownCompanies))
  108. if (shipbuilderSet.has(company.Username))
  109. shipbuildersById[companyId] = company.Username;
  110. const missingShipbuilders = shipbuilders
  111. .filter((username) => !Object.values(shipbuildersById).includes(username));
  112. if (missingShipbuilders.length > 0)
  113. return element('h3', {textContent: `missing shipbuilders in PMMG report: ${missingShipbuilders.join(', ')}`});
  114. const section = element('section');
  115. section.append(element('h2', {textContent: 'shipbuilders'}));
  116. const table = element('table');
  117. const header = element('tr');
  118. header.append(element('th', {textContent: 'mat'}));
  119. header.append(element('th', {textContent: 'amount'}));
  120. for (const username of Object.values(shipbuildersById))
  121. header.append(element('th', {textContent: username}));
  122. table.append(header);
  123. for (const mat of matTickers) {
  124. const row = element('tr');
  125. row.append(element('td', {textContent: mat}));
  126. row.append(element('td', {textContent: formatAmount(requiredMats[mat])}));
  127. for (const companyId of Object.keys(shipbuildersById)) {
  128. const makes = mat in companyProductionById[companyId];
  129. row.append(element('td', {textContent: makes ? '' : 'x'}));
  130. }
  131. table.append(row);
  132. }
  133. section.append(table);
  134. return section;
  135. }
  136. async function recipeForMats(): Promise<Record<string, Recipe>> {
  137. const allRecipes: Recipe[] = await cachedFetchJSON('https://api.prunplanner.org/data/recipes/');
  138. const matRecipes: Record<string, Recipe[]> = {}; // all ways to make a mat
  139. for (const recipe of allRecipes)
  140. for (const output of recipe.outputs) {
  141. const recipes = matRecipes[output.material_ticker];
  142. if (recipes)
  143. recipes.push(recipe);
  144. else
  145. matRecipes[output.material_ticker] = [recipe];
  146. }
  147. const matRecipe: Record<string, Recipe> = {}; // mats for which there's only one recipe to make
  148. for (const [mat, recipes] of Object.entries(matRecipes))
  149. if (recipes.length === 1)
  150. matRecipe[mat] = recipes[0];
  151. return matRecipe;
  152. }
  153. function analyzeMat(mat: string, amount: number, production: Production, buy: Record<string, number>,
  154. prices: Record<string, RawPrice>, recipes: Record<string, Recipe>): { cost: number, node: AnalysisNode } {
  155. const price = prices[mat];
  156. if (!price)
  157. throw new Error(`missing price for ${mat}`);
  158. const traded = price.AverageTraded30D ?? 0;
  159. if (BUY.has(mat)) {
  160. if (price.Ask == null)
  161. throw new Error(`missing ask price for ${mat}`);
  162. buy[mat] = (buy[mat] ?? 0) + amount;
  163. return {
  164. cost: price.Ask * amount,
  165. node: { text: `${formatAmount(amount)}x${mat} buy: ${formatAmount(price.Ask)}, daily traded ${formatFixed(traded, 1)}`, children: [] },
  166. };
  167. }
  168. const recipe = recipes[mat];
  169. if (!recipe)
  170. return { cost: 0, node: { text: `${formatAmount(amount)}x${mat} make (unknown recipe)`, children: [] } };
  171. const building = recipe.building_ticker;
  172. if (!production[building])
  173. production[building] = {};
  174. production[building][mat] = (production[building][mat] ?? 0) + amount;
  175. const liquid = traded > amount * 2 ? 'liquid' : 'not liquid';
  176. let totalCost = 0;
  177. const children: AnalysisNode[] = [];
  178. for (const inputMat of recipe.inputs) {
  179. const inputAmount = inputMat.material_amount * amount / recipe.outputs[0].material_amount;
  180. const {cost, node} = analyzeMat(inputMat.material_ticker, inputAmount, production, buy, prices, recipes);
  181. totalCost += cost;
  182. children.push(node);
  183. }
  184. children.push({ text: `cost: ${formatWhole(totalCost)}`, children: [] });
  185. return {
  186. cost: totalCost,
  187. node: { text: `${formatAmount(amount)}x${mat} make (${building}, ${liquid})`, children },
  188. };
  189. }
  190. function renderAnalysis(nodes: AnalysisNode[]): HTMLElement {
  191. const section = element('section');
  192. for (const node of nodes)
  193. section.append(renderAnalysisNode(node));
  194. return section;
  195. }
  196. function renderAnalysisNode(node: AnalysisNode, level = 0): HTMLElement {
  197. let el;
  198. if (node.children.length === 0) {
  199. el = element('div', {textContent: node.text, className: 'analysis-node'});
  200. } else {
  201. el = element('details', {className: 'analysis-node', open: true});
  202. el.append(element('summary', {textContent: node.text}));
  203. for (const child of node.children)
  204. el.append(renderAnalysisNode(child, level + 1));
  205. }
  206. if (level === 0)
  207. el.classList.add('root');
  208. return el;
  209. }
  210. function renderProduction(expertiseGroups: Record<string, string[]>, production: Production,
  211. prices: Record<string, RawPrice>): HTMLElement {
  212. const section = element('section');
  213. section.append(element('h2', {textContent: 'production'}));
  214. for (const [expertise, buildings] of Object.entries(expertiseGroups)) {
  215. section.append(element('h3', {textContent: expertise}));
  216. for (const building of buildings) {
  217. const buildingRow = element('div', {className: 'building-row', textContent: building});
  218. const buildingMats = element('div');
  219. const mats = Object.entries(production[building]);
  220. for (const [index, [mat, amount]] of mats.entries()) {
  221. const traded = prices[mat]?.AverageTraded30D ?? 0;
  222. const span = element('span', {
  223. textContent: `${formatAmount(amount)}x${mat}`,
  224. });
  225. span.style.color = traded > amount * 2 ? '#6c6' : '#c66';
  226. buildingMats.append(span);
  227. if (index < mats.length - 1)
  228. buildingMats.append(document.createTextNode(' '));
  229. }
  230. buildingRow.append(buildingMats);
  231. section.append(buildingRow);
  232. }
  233. }
  234. return section;
  235. }
  236. function element<K extends keyof HTMLElementTagNameMap>(tagName: K,
  237. properties: Partial<HTMLElementTagNameMap[K]> = {}): HTMLElementTagNameMap[K] {
  238. const node = document.createElement(tagName);
  239. Object.assign(node, properties);
  240. return node;
  241. }
  242. function formatAmount(n: number): string {
  243. return n.toLocaleString(undefined, {maximumFractionDigits: 3});
  244. }
  245. function formatFixed(n: number, digits: number): string {
  246. return n.toLocaleString(undefined, {
  247. minimumFractionDigits: digits,
  248. maximumFractionDigits: digits,
  249. });
  250. }
  251. function formatWhole(n: number): string {
  252. return n.toLocaleString(undefined, {maximumFractionDigits: 0});
  253. }
  254. interface AnalysisNode {
  255. text: string
  256. children: AnalysisNode[]
  257. }
  258. interface Recipe {
  259. recipe_name: string
  260. building_ticker: string
  261. inputs: RecipeMat[]
  262. outputs: RecipeMat[]
  263. time_ms: number
  264. }
  265. interface RecipeMat {
  266. material_ticker: string
  267. material_amount: number
  268. }
  269. interface RawPrice {
  270. MaterialTicker: string
  271. ExchangeCode: string
  272. Ask: number | null
  273. AverageTraded30D: number | null
  274. Supply: number
  275. }
  276. interface Building {
  277. building_ticker: string
  278. expertise: string
  279. }
  280. type PMMGCompanyProduction = Record<string, Record<string, {amount: number}>>;
  281. type Production = Record<string, Record<string, number>>;