Compare commits

..

No commits in common. "ad2b2993df87df14145a23f69a8e9fc4d71e3dc6" and "a4ea0dfc417552ed78e9e2091b65ef6a2c000ab7" have entirely different histories.

6 changed files with 96 additions and 137 deletions

View File

@ -349,26 +349,24 @@ def last_submissions(
def mvp( def mvp(
request: Annotated[TeamScopedRequest, Security(verify_team_scope)], mixed=False request: Annotated[TeamScopedRequest, Security(verify_team_scope)],
): ):
ranks = dict()
if request.team_id == 42: if request.team_id == 42:
ranks = {}
random.seed(42) random.seed(42)
players = [request.user] + demo_players players = [request.user] + demo_players
for p in players: for p in players:
random.shuffle(players) random.shuffle(players)
for i, p in enumerate(players): for i, p in enumerate(players):
ranks[p.id] = ranks.get(p.id, []) + [i + 1] ranks[p.display_name] = ranks.get(p.display_name, []) + [i + 1]
return [ return [
[ {
{ "name": p,
"p_id": p_id, "rank": f"{np.mean(v):.02f}",
"rank": f"{np.mean(v):.02f}", "std": f"{np.std(v):.02f}",
"std": f"{np.std(v):.02f}", "n": len(v),
"n": len(v), }
} for p, v in ranks.items()
for i, (p_id, v) in enumerate(ranks.items())
]
] ]
with Session(engine) as session: with Session(engine) as session:
@ -380,7 +378,7 @@ def mvp(
).all() ).all()
if not players: if not players:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND) raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
player_map = {p.id: p for p in players} player_map = {p.id: p.display_name for p in players}
subquery = ( subquery = (
select(R.user, func.max(R.time).label("latest")) select(R.user, func.max(R.time).label("latest"))
.where(R.team == request.team_id) .where(R.team == request.team_id)
@ -390,45 +388,25 @@ def mvp(
statement2 = select(R).join( statement2 = select(R).join(
subquery, (R.user == subquery.c.user) & (R.time == subquery.c.latest) subquery, (R.user == subquery.c.user) & (R.time == subquery.c.latest)
) )
if mixed: for r in session.exec(statement2):
all_ranks = [] for i, p_id in enumerate(r.mvps):
for gender in ["fmp", "mmp"]: if p_id not in player_map:
ranks = {} continue
for r in session.exec(statement2): p = player_map[p_id]
mvps = [ ranks[p] = ranks.get(p, []) + [i + 1]
p_id
for p_id in r.mvps
if p_id in player_map and player_map[p_id].gender == gender
]
for i, p_id in enumerate(mvps):
p = player_map[p_id]
ranks[p_id] = ranks.get(p_id, []) + [i + 1]
all_ranks.append(ranks)
else:
ranks = {}
for r in session.exec(statement2):
for i, p_id in enumerate(r.mvps):
if p_id not in player_map:
continue
p = player_map[p_id]
ranks[p_id] = ranks.get(p_id, []) + [i + 1]
all_ranks = [ranks]
if not all_ranks: if not ranks:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="no entries found" status_code=status.HTTP_404_NOT_FOUND, detail="no entries found"
) )
return [ return [
[ {
{ "name": p,
"p_id": p_id, "rank": f"{np.mean(v):.02f}",
"rank": f"{np.mean(v):.02f}", "std": f"{np.std(v):.02f}",
"std": f"{np.std(v):.02f}", "n": len(v),
"n": len(v), }
} for p, v in ranks.items()
for p_id, v in ranks.items()
]
for ranks in all_ranks
] ]

View File

@ -16,7 +16,7 @@ names = [
demo_players = [ demo_players = [
Player.model_validate( Player.model_validate(
{ {
"id": i + 4200, "id": i,
"display_name": name, "display_name": name,
"username": name.lower().replace(" ", "").replace(".", ""), "username": name.lower().replace(" ", "").replace(".", ""),
"gender": gender, "gender": gender,

View File

@ -6,13 +6,12 @@ import { useSession } from "./Session";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
const MVPChart = () => { const MVPChart = () => {
let initialData = {} as PlayerRanking[][]; let initialData = {} as PlayerRanking[];
const [data, setData] = useState(initialData); const [data, setData] = useState(initialData);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState(""); const [error, setError] = useState("");
const [showStd, setShowStd] = useState(false); const [showStd, setShowStd] = useState(false);
const { user, teams } = useSession(); const { user, teams } = useSession();
const [mixed, setMixed] = useState(false);
const navigate = useNavigate(); const navigate = useNavigate();
useEffect(() => { useEffect(() => {
user?.scopes.includes(`team:${teams?.activeTeam}`) || user?.scopes.includes(`team:${teams?.activeTeam}`) ||
@ -20,30 +19,21 @@ const MVPChart = () => {
navigate("/", { replace: true }); navigate("/", { replace: true });
}, [user]); }, [user]);
useEffect(() => {
if (teams) {
const activeTeam = teams.teams.find(
(team) => team.id == teams.activeTeam
);
activeTeam && setMixed(activeTeam.mixed);
}
}, [teams]);
async function loadData() { async function loadData() {
setLoading(true); setLoading(true);
if (teams) { if (teams) {
await apiAuth(`analysis/mvp/${teams?.activeTeam}?mixed=${mixed}`, null) await apiAuth(`analysis/mvp/${teams?.activeTeam}`, null)
.then((data) => { .then((data) => {
if (data.detail) { if (data.detail) {
setError(data.detail); setError(data.detail);
return initialData; return initialData;
} else { } else {
setError(""); setError("");
return data as Promise<PlayerRanking[][]>; return data as Promise<PlayerRanking[]>;
} }
}) })
.then((data) => { .then((data) => {
setData(data.map((_data) => _data.sort((a, b) => a.rank - b.rank))); setData(data.sort((a, b) => a.rank - b.rank));
}) })
.catch(() => setError("no access")); .catch(() => setError("no access"));
setLoading(false); setLoading(false);
@ -56,8 +46,7 @@ const MVPChart = () => {
if (loading) return <span className="loader" />; if (loading) return <span className="loader" />;
else if (error) return <span>{error}</span>; else if (error) return <span>{error}</span>;
else else return <RaceChart std={showStd} players={data} />;
return data.map((_data) => <RaceChart std={showStd} playerRanks={_data} />);
}; };
export default MVPChart; export default MVPChart;

View File

@ -1,9 +1,8 @@
import { FC, useEffect, useState } from "react"; import { FC, useEffect, useState } from "react";
import { PlayerRanking } from "./types"; import { PlayerRanking } from "./types";
import { useSession } from "./Session";
interface RaceChartProps { interface RaceChartProps {
playerRanks: PlayerRanking[]; players: PlayerRanking[];
std: boolean; std: boolean;
} }
@ -14,14 +13,15 @@ const determineNiceWidth = (width: number) => {
else return width * 0.96; else return width * 0.96;
}; };
const RaceChart: FC<RaceChartProps> = ({ playerRanks, std }) => { const RaceChart: FC<RaceChartProps> = ({ players, std }) => {
const [width, setWidth] = useState(determineNiceWidth(window.innerWidth)); const [width, setWidth] = useState(determineNiceWidth(window.innerWidth));
const height = (playerRanks.length + 1) * 40; //const [height, setHeight] = useState(window.innerHeight);
const { players } = useSession(); const height = (players.length + 1) * 40;
useEffect(() => { useEffect(() => {
const handleResize = () => { const handleResize = () => {
setWidth(determineNiceWidth(window.innerWidth)); setWidth(determineNiceWidth(window.innerWidth));
//setHeight(window.innerHeight);
}; };
window.addEventListener("resize", handleResize); window.addEventListener("resize", handleResize);
return () => { return () => {
@ -30,18 +30,18 @@ const RaceChart: FC<RaceChartProps> = ({ playerRanks, std }) => {
}, []); }, []);
const padding = 24; const padding = 24;
const gap = 8; const gap = 8;
const maxValue = Math.max(...playerRanks.map((player) => player.rank)) + 1; const maxValue = Math.max(...players.map((player) => player.rank)) + 1;
const barHeight = (height - 2 * padding) / playerRanks.length; const barHeight = (height - 2 * padding) / players.length;
const fontSize = Math.min(barHeight - 1.5 * gap, width / 22); const fontSize = Math.min(barHeight - 1.5 * gap, width / 22);
return ( return (
<svg width={width} height={height} id="RaceChartSVG"> <svg width={width} height={height} id="RaceChartSVG">
{playerRanks.map((playerRank, index) => ( {players.map((player, index) => (
<rect <rect
key={String(index)} key={String(index)}
x={4} x={4}
y={index * barHeight + padding} y={index * barHeight + padding}
width={(1 - playerRank.rank / maxValue) * width} width={(1 - player.rank / maxValue) * width}
height={barHeight - gap} // subtract 2 for some spacing between bars height={barHeight - gap} // subtract 2 for some spacing between bars
fill="#36c" fill="#36c"
stroke="aliceblue" stroke="aliceblue"
@ -50,53 +50,49 @@ const RaceChart: FC<RaceChartProps> = ({ playerRanks, std }) => {
/> />
))} ))}
{playerRanks.map((playerRank, index) => { {players.map((player, index) => (
const player = players!.find((p) => p.id === playerRank.p_id); <g key={"group" + index}>
return ( <text
<g key={"group" + index}> key={index + "_name"}
<text x={8}
key={index + "_name"} y={index * barHeight + barHeight / 2 + padding + gap / 2}
x={8} width={(1 - player.rank / maxValue) * width}
y={index * barHeight + barHeight / 2 + padding + gap / 2} height={barHeight - 8} // subtract 2 for some spacing between bars
width={(1 - playerRank.rank / maxValue) * width} fontSize={fontSize}
height={barHeight - 8} // subtract 2 for some spacing between bars fill="aliceblue"
fontSize={fontSize} stroke="#36c"
fill="aliceblue" strokeWidth={4}
stroke="#36c" fontWeight={"bold"}
strokeWidth={4} paintOrder={"stroke fill"}
fontWeight={"bold"} fontFamily="monospace"
paintOrder={"stroke fill"} style={{ whiteSpace: "pre" }}
fontFamily="monospace" >
style={{ whiteSpace: "pre" }} {`${String(index + 1).padStart(2)}. ${player.name}`}
> </text>
{`${String(index + 1).padStart(2)}. ${player?.display_name}`} <text
</text> key={index + "_value"}
<text x={
key={index + "_value"} 8 +
x={ (4 + Math.max(...players.map((p, _) => p.name.length))) *
8 + fontSize *
(4 + 0.66
Math.max(...players!.map((p, _) => p.display_name.length))) * }
fontSize * y={index * barHeight + barHeight / 2 + padding + gap / 2}
0.66 width={(1 - player.rank / maxValue) * width}
} height={barHeight - 8} // subtract 2 for some spacing between bars
y={index * barHeight + barHeight / 2 + padding + gap / 2} fontSize={0.8 * fontSize}
width={(1 - playerRank.rank / maxValue) * width} fill="aliceblue"
height={barHeight - 8} // subtract 2 for some spacing between bars stroke="#36c"
fontSize={0.8 * fontSize} fontWeight={"bold"}
fill="aliceblue" fontFamily="monospace"
stroke="#36c" strokeWidth={4}
fontWeight={"bold"} paintOrder={"stroke fill"}
fontFamily="monospace" style={{ whiteSpace: "pre" }}
strokeWidth={4} >
paintOrder={"stroke fill"} {`${String(player.rank).padStart(5)} ± ${player.std} N = ${player.n}`}
style={{ whiteSpace: "pre" }} </text>
> </g>
{`${String(playerRank.rank).padStart(5)} ± ${playerRank.std} N = ${playerRank.n}`} ))}
</text>
</g>
);
})}
</svg> </svg>
); );
}; };

View File

@ -345,11 +345,6 @@ function MVPDnD({ user, teams, players }: PlayerInfoProps) {
handleGet(); handleGet();
}, [players]); }, [players]);
useEffect(() => {
handleGet();
// setMixedList(rankedPlayers);
}, [mixed]);
const [dialog, setDialog] = useState("dialog"); const [dialog, setDialog] = useState("dialog");
const dialogRef = useRef<HTMLDialogElement>(null); const dialogRef = useRef<HTMLDialogElement>(null);
@ -362,15 +357,6 @@ function MVPDnD({ user, teams, players }: PlayerInfoProps) {
response ? setDialog(response) : setDialog("try sending again"); response ? setDialog(response) : setDialog("try sending again");
} }
const setMixedList = (newList: User[]) =>
mixed
? setRankedPlayers(
newList.sort((a, b) =>
a.gender && b.gender ? a.gender.localeCompare(b.gender) : -1
)
)
: setRankedPlayers(newList);
async function handleGet() { async function handleGet() {
setLoading(true); setLoading(true);
const data = await apiAuth(`mvps/${teams.activeTeam}`, null, "GET"); const data = await apiAuth(`mvps/${teams.activeTeam}`, null, "GET");
@ -380,7 +366,7 @@ function MVPDnD({ user, teams, players }: PlayerInfoProps) {
setRankedPlayers([]); setRankedPlayers([]);
} else { } else {
const mvps = data as MVPRanking; const mvps = data as MVPRanking;
setMixedList(filterSort(players, mvps.mvps)); setRankedPlayers(filterSort(players, mvps.mvps));
setAvailablePlayers( setAvailablePlayers(
players.filter((user) => !mvps.mvps.includes(user.id)) players.filter((user) => !mvps.mvps.includes(user.id))
); );
@ -426,7 +412,17 @@ function MVPDnD({ user, teams, players }: PlayerInfoProps) {
)} )}
<PlayerList <PlayerList
list={rankedPlayers} list={rankedPlayers}
setList={setMixedList} setList={(newList) =>
mixed
? setRankedPlayers(
newList.sort((a, b) =>
a.gender && b.gender
? a.gender.localeCompare(b.gender)
: -1
)
)
: setRankedPlayers(newList)
}
group={{ group={{
name: "mvp-shared", name: "mvp-shared",
}} }}

View File

@ -13,7 +13,7 @@ export default interface NetworkData {
} }
export interface PlayerRanking { export interface PlayerRanking {
p_id: number; name: string;
rank: number; rank: number;
std: number; std: number;
n: number; n: number;