refactor main view to table and add production, import and export information per planet

This commit is contained in:
Calli
2023-07-16 19:02:11 +03:00
parent bc0c2f83a2
commit 4c392533da
11 changed files with 1906 additions and 15 deletions

1
pi.json Normal file

File diff suppressed because one or more lines are too long

View File

@@ -3,13 +3,7 @@ import { Box, Stack, Typography, useTheme } from "@mui/material";
import { CharacterRow } from "../Characters/CharacterRow";
import { PlanetaryInteractionRow } from "../PlanetaryInteraction/PlanetaryInteractionRow";
export const AccountCard = ({
characters,
sessionReady,
}: {
characters: AccessToken[];
sessionReady: boolean;
}) => {
export const AccountCard = ({ characters }: { characters: AccessToken[] }) => {
const theme = useTheme();
return (
<Box
@@ -30,7 +24,7 @@ export const AccountCard = ({
alignItems="flex-start"
>
<CharacterRow character={c} />
{sessionReady && <PlanetaryInteractionRow character={c} />}
<PlanetaryInteractionRow character={c} />
</Stack>
))}
</Box>

View File

@@ -10,6 +10,8 @@ import { AccountCard } from "./Account/AccountCard";
import { AccessToken } from "@/types";
import { CharacterContext, SessionContext } from "../context/Context";
import ResponsiveAppBar from "./AppBar/AppBar";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useTheme } from "@emotion/react";
interface Grouped {
[key: string]: AccessToken[];
@@ -91,7 +93,7 @@ export const MainGrid = ({ sessionReady }: { sessionReady: boolean }) => {
sm={compactMode ? 6 : 12}
key={`account-${id}-${g[0].account}`}
>
<AccountCard characters={g} sessionReady={sessionReady} />
<AccountCard characters={g} />
</Grid>
))}
</Grid>

View File

@@ -0,0 +1,340 @@
import { Button, Tooltip, Typography, useTheme } from "@mui/material";
import { AccessToken, Planet, PlanetInfo, PlanetInfoUniverse } from "@/types";
import { Api } from "@/esi-api";
import {
Dispatch,
SetStateAction,
forwardRef,
useContext,
useEffect,
useState,
} from "react";
import { DateTime } from "luxon";
import {
EXTRACTOR_TYPE_IDS,
FACTORY_IDS,
PI_SCHEMATICS,
PI_TYPES_MAP,
} from "@/const";
import TableCell from "@mui/material/TableCell";
import TableRow from "@mui/material/TableRow";
import Countdown from "react-countdown";
import Image from "next/image";
import { SessionContext } from "@/app/context/Context";
import Slide from "@mui/material/Slide";
import { TransitionProps } from "@mui/material/transitions";
import Dialog from "@mui/material/Dialog";
import AppBar from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import IconButton from "@mui/material/IconButton";
import CloseIcon from "@mui/icons-material/Close";
import PinsCanvas3D from "./PinsCanvas3D";
const Transition = forwardRef(function Transition(
props: TransitionProps & {
children: React.ReactElement;
},
ref: React.Ref<unknown>
) {
return <Slide direction="up" ref={ref} {...props} />;
});
export const PlanetTableRow = ({
planet,
character,
}: {
planet: Planet;
character: AccessToken;
}) => {
const theme = useTheme();
const [planetRenderOpen, setPlanetRenderOpen] = useState(false);
const handle3DrenderOpen = () => {
setPlanetRenderOpen(true);
};
const handle3DrenderClose = () => {
setPlanetRenderOpen(false);
};
const { piPrices } = useContext(SessionContext);
const [planetInfo, setPlanetInfo] = useState<PlanetInfo | undefined>(
undefined
);
const [planetInfoUniverse, setPlanetInfoUniverse] = useState<
PlanetInfoUniverse | undefined
>(undefined);
const [extractors, setExtractors] = useState<PlanetInfo["pins"]>([]);
const [production, setProduction] = useState(
new Map<SchematicId, (typeof PI_SCHEMATICS)[number]>()
);
const [imports, setImports] = useState<
(typeof PI_SCHEMATICS)[number]["inputs"]
>([]);
const [exports, setExports] = useState<{ typeId: number; amount: number }[]>(
[]
);
type SchematicId = number;
const getPlanet = async (
character: AccessToken,
planet: Planet
): Promise<PlanetInfo> => {
const api = new Api();
const planetRes = await api.v3.getCharactersCharacterIdPlanetsPlanetId(
character.character.characterId,
planet.planet_id,
{
token: character.access_token,
}
);
const planetInfo = planetRes.data;
setExtractors(
planetInfo.pins.filter((p) =>
EXTRACTOR_TYPE_IDS.some((e) => e === p.type_id)
)
);
const localProduction = planetInfo.pins
.filter((p) => FACTORY_IDS().some((e) => e.type_id === p.type_id))
.reduce((acc, f) => {
if (f.schematic_id) {
const schematic = PI_SCHEMATICS.find(
(s) => s.schematic_id == f.schematic_id
);
if (schematic) acc.set(f.schematic_id, schematic);
}
return acc;
}, new Map<SchematicId, (typeof PI_SCHEMATICS)[number]>());
setProduction(localProduction);
const locallyProduced = Array.from(localProduction)
.flatMap((p) => p[1].outputs)
.map((p) => p.type_id);
const locallyConsumed = Array.from(localProduction)
.flatMap((p) => p[1].inputs)
.map((p) => p.type_id);
const locallyExcavated = planetInfo.pins
.filter((p) => EXTRACTOR_TYPE_IDS.some((e) => e === p.type_id))
.map((e) => e.extractor_details?.product_type_id ?? 0);
const localImports = Array.from(localProduction)
.flatMap((p) => p[1].inputs)
.filter(
(p) =>
![...locallyProduced, ...locallyExcavated].some(
(lp) => lp === p.type_id
)
);
const localExports = locallyProduced
.filter((p) => !locallyConsumed.some((lp) => lp === p))
.map((typeId) => {
const schematic = PI_SCHEMATICS.flatMap((s) => s.outputs).find(
(s) => s.type_id === typeId
);
if (!schematic) return { typeId, amount: 0 };
const factoriesProducing = planetInfo.pins
.filter((p) => FACTORY_IDS().some((e) => e.type_id === p.type_id))
.filter((f) => f.schematic_id === schematic?.schematic_id);
const amount = schematic.quantity
? factoriesProducing.length * schematic.quantity
: (0 * PI_SCHEMATICS[schematic.schematic_id].cycle_time) / 3600;
return {
typeId,
amount,
};
});
setImports(localImports);
setExports(localExports);
return planetInfo;
};
const getPlanetUniverse = async (
planet: Planet
): Promise<PlanetInfoUniverse> => {
const api = new Api();
const planetInfo = (
await api.v1.getUniversePlanetsPlanetId(planet.planet_id)
).data;
return planetInfo;
};
const timeColor = (extractorDate: string | undefined): string => {
if (!extractorDate) return "red";
const dateExtractor = DateTime.fromISO(extractorDate);
const dateNow = DateTime.now();
if (dateExtractor < dateNow) return "red";
if (dateExtractor.minus({ hours: 24 }) < dateNow) return "yellow";
return "green";
};
useEffect(() => {
getPlanet(character, planet).then(setPlanetInfo);
getPlanetUniverse(planet).then(setPlanetInfoUniverse);
}, [planet, character]);
return (
<TableRow sx={{ "&:last-child td, &:last-child th": { border: 0 } }}>
<TableCell component="th" scope="row">
<Tooltip
title={`${
planet.planet_type.charAt(0).toUpperCase() +
planet.planet_type.slice(1)
} planet.`}
>
<div style={{ display: "flex" }}>
<Image
src={`/${planet.planet_type}.png`}
alt=""
width={theme.custom.cardImageSize / 6}
height={theme.custom.cardImageSize / 6}
/>
{planetInfoUniverse?.name}
</div>
</Tooltip>
</TableCell>
<TableCell>{planet.upgrade_level}</TableCell>
<TableCell>
<div style={{ display: "flex", flexDirection: "column" }}>
{extractors.map((e, idx) => {
return (
<div
key={`${e}-${idx}-${character.character.characterId}`}
style={{ display: "flex" }}
>
<Typography
color={timeColor(e.expiry_time)}
fontSize={theme.custom.smallText}
paddingRight={1}
>
{e ? (
<Countdown
overtime={true}
date={DateTime.fromISO(e.expiry_time ?? "").toMillis()}
/>
) : (
"STOPPED"
)}
</Typography>
<Typography fontSize={theme.custom.smallText}>
{PI_TYPES_MAP[e.extractor_details?.product_type_id ?? 0].name}
</Typography>
</div>
);
})}
</div>
</TableCell>
<TableCell>
<div style={{ display: "flex", flexDirection: "column" }}>
{Array.from(production).map((schematic, idx) => {
return (
<Typography
key={`prod-${character.character.characterId}-${planet.planet_id}-${idx}`}
fontSize={theme.custom.smallText}
>
{schematic[1].name}
</Typography>
);
})}
</div>
</TableCell>
<TableCell>
<div style={{ display: "flex", flexDirection: "column" }}>
{imports.map((i) => (
<Typography
key={`import-${character.character.characterId}-${planet.planet_id}-${i.type_id}`}
fontSize={theme.custom.smallText}
>
{PI_TYPES_MAP[i.type_id].name}
</Typography>
))}
</div>
</TableCell>
<TableCell>
<div style={{ display: "flex", flexDirection: "column" }}>
{exports.map((exports) => (
<Typography
key={`export-${character.character.characterId}-${planet.planet_id}-${exports.typeId}`}
fontSize={theme.custom.smallText}
>
{PI_TYPES_MAP[exports.typeId].name}
</Typography>
))}
</div>
</TableCell>
<TableCell>
<div style={{ display: "flex", flexDirection: "column" }}>
{exports.map((exports) => (
<Typography
key={`export-uph-${character.character.characterId}-${planet.planet_id}-${exports.typeId}`}
fontSize={theme.custom.smallText}
>
{exports.amount}
</Typography>
))}
</div>
</TableCell>
<TableCell>
<div style={{ display: "flex", flexDirection: "column" }}>
{exports.map((e) => (
<Typography
key={`export-praisal-${character.character.characterId}-${planet.planet_id}-${e.typeId}`}
fontSize={theme.custom.smallText}
>
{`${(
((piPrices?.appraisal.items.find((a) => a.typeID === e.typeId)
?.prices.sell.min ?? 0) *
e.amount) /
1000000
).toFixed(2)} M`}
</Typography>
))}
</div>
</TableCell>
<TableCell>
<Button variant="contained" onClick={handle3DrenderOpen}>
3D
</Button>
</TableCell>
<Dialog
fullScreen
open={planetRenderOpen}
onClose={handle3DrenderClose}
TransitionComponent={Transition}
>
<AppBar sx={{ position: "relative" }}>
<Toolbar>
<IconButton
edge="start"
color="inherit"
onClick={handle3DrenderClose}
aria-label="close"
>
<CloseIcon />
</IconButton>
<Typography sx={{ ml: 2, flex: 1 }} variant="h6" component="div">
{planetInfoUniverse?.name}
</Typography>
<Button autoFocus color="inherit" onClick={handle3DrenderClose}>
Close
</Button>
</Toolbar>
</AppBar>
<PinsCanvas3D planetInfo={planetInfo} />
</Dialog>
</TableRow>
);
};

View File

@@ -1,9 +1,17 @@
import { Api } from "@/esi-api";
import { AccessToken, Planet } from "@/types";
import { Stack, styled } from "@mui/material";
import { Stack, styled, useTheme } from "@mui/material";
import { useEffect, useState } from "react";
import { PlanetCard } from "./PlanetCard";
import { NoPlanetCard } from "./NoPlanetCard";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import { PlanetTableRow } from "./PlanetTableRow";
const StackItem = styled(Stack)(({ theme }) => ({
...theme.typography.body2,
@@ -26,16 +34,51 @@ const getPlanets = async (character: AccessToken): Promise<Planet[]> => {
return planets;
};
export const PlanetaryInteractionRow = ({
const PlanetaryIteractionTable = ({
character,
planets,
}: {
character: AccessToken;
planets: Planet[];
}) => {
const [planets, setPlanets] = useState<Planet[]>([]);
useEffect(() => {
getPlanets(character).then(setPlanets).catch(console.log);
}, [character]);
return (
<StackItem width="100%">
<TableContainer component={Paper}>
<Table size="small" aria-label="a dense table">
<TableHead>
<TableRow>
<TableCell width="13%">Planet</TableCell>
<TableCell width="2%">CC</TableCell>
<TableCell width="20%">Extraction</TableCell>
<TableCell width="20%">Production</TableCell>
<TableCell width="20%">Imports</TableCell>
<TableCell width="20%">Exports</TableCell>
<TableCell width="5%">u/h</TableCell>
<TableCell width="5%">MISK/h</TableCell>
</TableRow>
</TableHead>
<TableBody>
{planets.map((planet) => (
<PlanetTableRow
key={`${character.character.characterId}-${planet.planet_id}`}
planet={planet}
character={character}
/>
))}
</TableBody>
</Table>
</TableContainer>
</StackItem>
);
};
const PlanetaryInteractionIconsRow = ({
character,
planets,
}: {
character: AccessToken;
planets: Planet[];
}) => {
return (
<StackItem>
<Stack spacing={2} direction="row" flexWrap="wrap">
@@ -55,3 +98,21 @@ export const PlanetaryInteractionRow = ({
</StackItem>
);
};
export const PlanetaryInteractionRow = ({
character,
}: {
character: AccessToken;
}) => {
const [planets, setPlanets] = useState<Planet[]>([]);
const theme = useTheme();
useEffect(() => {
getPlanets(character).then(setPlanets).catch(console.log);
}, [character]);
return theme.custom.compactMode ? (
<PlanetaryInteractionIconsRow planets={planets} character={character} />
) : (
<PlanetaryIteractionTable planets={planets} character={character} />
);
};

View File

@@ -1,3 +1,4 @@
import { EvePraisalResult } from "@/eve-praisal";
import { AccessToken, CharacterUpdate } from "@/types";
import { Dispatch, SetStateAction, createContext } from "react";
@@ -21,6 +22,7 @@ export const SessionContext = createContext<{
EVE_SSO_CLIENT_ID: string;
compactMode: boolean;
toggleCompactMode: () => void;
piPrices: EvePraisalResult | undefined;
}>({
sessionReady: false,
refreshSession: () => {},
@@ -29,4 +31,5 @@ export const SessionContext = createContext<{
EVE_SSO_CLIENT_ID: "",
compactMode: false,
toggleCompactMode: () => {},
piPrices: undefined,
});

View File

@@ -9,12 +9,16 @@ import { MainGrid } from "./components/MainGrid";
import { refreshToken } from "@/esi-sso";
import { CharacterContext, SessionContext } from "./context/Context";
import { useSearchParams } from "next/navigation";
import { EvePraisalResult, fetchAllPrices } from "@/eve-praisal";
const Home = () => {
const [characters, setCharacters] = useState<AccessToken[]>([]);
const [sessionReady, setSessionReady] = useState(false);
const [environment, setEnvironment] = useState<Env | undefined>(undefined);
const [compactMode, setCompactMode] = useState(false);
const [piPrices, setPiPrices] = useState<EvePraisalResult | undefined>(
undefined
);
const searchParams = useSearchParams();
const code = searchParams && searchParams.get("code");
@@ -110,6 +114,12 @@ const Home = () => {
.then(() => setSessionReady(true));
}, []);
useEffect(() => {
fetchAllPrices()
.then(setPiPrices)
.catch(() => console.log("failed getting pi prices"));
}, []);
useEffect(() => {
const ESI_CACHE_TIME_MS = 600000;
const interval = setInterval(() => {
@@ -128,6 +138,7 @@ const Home = () => {
EVE_SSO_CLIENT_ID: environment?.EVE_SSO_CLIENT_ID ?? "",
compactMode,
toggleCompactMode,
piPrices,
}}
>
<CharacterContext.Provider

File diff suppressed because it is too large Load Diff

112
src/eve-praisal.ts Normal file
View File

@@ -0,0 +1,112 @@
import { PI_TYPES_ARRAY } from "./const";
export interface Totals {
buy: number;
sell: number;
volume: number;
}
export interface All {
avg: number;
max: number;
median: number;
min: number;
percentile: number;
stddev: number;
volume: number;
order_count: number;
}
export interface Buy {
avg: number;
max: number;
median: number;
min: number;
percentile: number;
stddev: number;
volume: number;
order_count: number;
}
export interface Sell {
avg: number;
max: number;
median: number;
min: number;
percentile: number;
stddev: number;
volume: number;
order_count: number;
}
export interface Prices {
all: All;
buy: Buy;
sell: Sell;
updated: string;
strategy: string;
}
export interface Meta {}
export interface Item {
name: string;
typeID: number;
typeName: string;
typeVolume: number;
quantity: number;
prices: Prices;
meta: Meta;
}
export interface Appraisal {
created: number;
kind: string;
market_name: string;
totals: Totals;
items: Item[];
raw: string;
unparsed?: any;
private: boolean;
live: boolean;
}
export interface EvePraisalResult {
appraisal: Appraisal;
}
export interface EvePraisalRequest {
items: { amount: number; typeId: number }[];
}
const PRAISAL_URL =
"https://evepraisal.com/appraisal/structured.json?persist=no";
export const getPraisal = async (
items: { quantity: number; type_id: number }[]
): Promise<EvePraisalResult | undefined> => {
const praisalRequest = {
market_name: "jita",
items,
};
return fetch(PRAISAL_URL, {
method: "POST",
body: JSON.stringify(praisalRequest),
headers: {
"User-Agent": "EVE-PI https://github.com/calli-eve/eve-pi",
},
})
.then((res) => res.json())
.catch(() => console.log("Appraisal failed"));
};
export const fetchAllPrices = async (): Promise<EvePraisalResult> => {
const allPI = PI_TYPES_ARRAY.map((t) => {
return { quantity: 1, type_id: t.type_id };
});
return await fetch("api/praisal", {
method: "POST",
body: JSON.stringify(allPI),
}).then((res) => res.json());
};

21
src/pages/api/praisal.ts Normal file
View File

@@ -0,0 +1,21 @@
import { getPraisal } from "@/eve-praisal";
import { NextApiRequest, NextApiResponse } from "next";
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === "POST") {
const praisalRequest: { quantity: number; type_id: number }[] = JSON.parse(
req.body
);
try {
const praisal = await getPraisal(praisalRequest);
return res.json(praisal);
} catch (e) {
console.log(e);
res.status(404).end();
}
} else {
res.status(404).end();
}
};
export default handler;

View File

@@ -15,6 +15,17 @@ export interface Character {
characterId: number;
}
export interface PlanetWithInfo extends Planet {
info: PlanetInfo;
infoUniverse: PlanetInfoUniverse;
}
export interface CharacterPlanets {
name: string;
characterId: number;
account?: string;
planets: PlanetWithInfo[];
}
export interface CharacterUpdate {
account?: string;
}