File size: 11,462 Bytes
e3278e4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 |
"use client";
import React, { useState, useEffect } from "react";
import {
userInfoCall,
modelAvailableCall,
getTotalSpendCall,
getProxyUISettings,
teamListCall,
} from "./networking";
import { Grid, Col, Card, Text, Title } from "@tremor/react";
import CreateKey from "./create_key_button";
import ViewKeyTable from "./view_key_table";
import ViewUserSpend from "./view_user_spend";
import ViewUserTeam from "./view_user_team";
import DashboardTeam from "./dashboard_default_team";
import Onboarding from "../app/onboarding/page";
import { useSearchParams, useRouter } from "next/navigation";
import { jwtDecode } from "jwt-decode";
import { Typography } from "antd";
const isLocal = process.env.NODE_ENV === "development";
if (isLocal != true) {
console.log = function() {};
}
console.log("isLocal:", isLocal);
const proxyBaseUrl = isLocal ? "http://localhost:4000" : null;
export interface ProxySettings {
PROXY_BASE_URL: string | null;
PROXY_LOGOUT_URL: string | null;
DEFAULT_TEAM_DISABLED: boolean;
SSO_ENABLED: boolean;
DISABLE_EXPENSIVE_DB_QUERIES: boolean;
NUM_SPEND_LOGS_ROWS: number;
}
export type UserInfo = {
models: string[];
max_budget?: number | null;
spend: number;
}
function getCookie(name: string) {
console.log("COOKIES", document.cookie)
const cookieValue = document.cookie
.split('; ')
.find(row => row.startsWith(name + '='));
return cookieValue ? cookieValue.split('=')[1] : null;
}
interface UserDashboardProps {
userID: string | null;
userRole: string | null;
userEmail: string | null;
teams: any[] | null;
keys: any[] | null;
setUserRole: React.Dispatch<React.SetStateAction<string>>;
setUserEmail: React.Dispatch<React.SetStateAction<string | null>>;
setTeams: React.Dispatch<React.SetStateAction<Object[] | null>>;
setKeys: React.Dispatch<React.SetStateAction<Object[] | null>>;
premiumUser: boolean;
}
type TeamInterface = {
models: any[];
team_id: null;
team_alias: String;
};
const UserDashboard: React.FC<UserDashboardProps> = ({
userID,
userRole,
teams,
keys,
setUserRole,
userEmail,
setUserEmail,
setTeams,
setKeys,
premiumUser,
}) => {
const [userSpendData, setUserSpendData] = useState<UserInfo | null>(
null
);
// Assuming useSearchParams() hook exists and works in your setup
const searchParams = useSearchParams()!;
const viewSpend = searchParams.get("viewSpend");
const router = useRouter();
const token = getCookie('token');
const invitation_id = searchParams.get("invitation_id");
const [accessToken, setAccessToken] = useState<string | null>(null);
const [teamSpend, setTeamSpend] = useState<number | null>(null);
const [userModels, setUserModels] = useState<string[]>([]);
const [proxySettings, setProxySettings] = useState<ProxySettings | null>(null);
const defaultTeam: TeamInterface = {
models: [],
team_alias: "Default Team",
team_id: null,
};
const [selectedTeam, setSelectedTeam] = useState<any | null>(
teams ? teams[0] : defaultTeam
);
// check if window is not undefined
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", function () {
// Clear session storage
sessionStorage.clear();
});
}
function formatUserRole(userRole: string) {
if (!userRole) {
return "Undefined Role";
}
console.log(`Received user role: ${userRole}`);
switch (userRole.toLowerCase()) {
case "app_owner":
return "App Owner";
case "demo_app_owner":
return "App Owner";
case "app_admin":
return "Admin";
case "proxy_admin":
return "Admin";
case "proxy_admin_viewer":
return "Admin Viewer";
case "app_user":
return "App User";
case "internal_user":
return "Internal User";
case "internal_user_viewer":
return "Internal Viewer";
default:
return "Unknown Role";
}
}
// console.log(`selectedTeam: ${Object.entries(selectedTeam)}`);
// Moved useEffect inside the component and used a condition to run fetch only if the params are available
useEffect(() => {
if (token) {
const decoded = jwtDecode(token) as { [key: string]: any };
if (decoded) {
// cast decoded to dictionary
console.log("Decoded token:", decoded);
console.log("Decoded key:", decoded.key);
// set accessToken
setAccessToken(decoded.key);
// check if userRole is defined
if (decoded.user_role) {
const formattedUserRole = formatUserRole(decoded.user_role);
console.log("Decoded user_role:", formattedUserRole);
setUserRole(formattedUserRole);
} else {
console.log("User role not defined");
}
if (decoded.user_email) {
setUserEmail(decoded.user_email);
} else {
console.log(`User Email is not set ${decoded}`);
}
}
}
if (userID && accessToken && userRole && !keys && !userSpendData) {
const cachedUserModels = sessionStorage.getItem("userModels" + userID);
if (cachedUserModels) {
setUserModels(JSON.parse(cachedUserModels));
} else {
const fetchTeams = async () => {
let givenTeams;
if (userRole != "Admin" && userRole != "Admin Viewer") {
givenTeams = await teamListCall(accessToken, userID)
} else {
givenTeams = await teamListCall(accessToken)
}
console.log(`givenTeams: ${givenTeams}`)
setTeams(givenTeams)
}
const fetchData = async () => {
try {
const proxy_settings: ProxySettings = await getProxyUISettings(accessToken);
setProxySettings(proxy_settings);
const response = await userInfoCall(
accessToken,
userID,
userRole,
false,
null,
null
);
console.log(
`received teams in user dashboard: ${Object.keys(
response
)}; team values: ${Object.entries(response.teams)}`
);
setUserSpendData(response["user_info"]);
console.log(`userSpendData: ${JSON.stringify(userSpendData)}`)
setKeys(response["keys"]); // Assuming this is the correct path to your data
const teamsArray = [...response["teams"]];
if (teamsArray.length > 0) {
console.log(`response['teams']: ${JSON.stringify(teamsArray)}`);
setSelectedTeam(teamsArray[0]);
} else {
setSelectedTeam(defaultTeam);
}
sessionStorage.setItem(
"userData" + userID,
JSON.stringify(response["keys"])
);
sessionStorage.setItem(
"userSpendData" + userID,
JSON.stringify(response["user_info"])
);
const model_available = await modelAvailableCall(
accessToken,
userID,
userRole
);
// loop through model_info["data"] and create an array of element.model_name
let available_model_names = model_available["data"].map(
(element: { id: string }) => element.id
);
console.log("available_model_names:", available_model_names);
setUserModels(available_model_names);
console.log("userModels:", userModels);
sessionStorage.setItem(
"userModels" + userID,
JSON.stringify(available_model_names)
);
} catch (error) {
console.error("There was an error fetching the data", error);
// Optionally, update your UI to reflect the error state here as well
}
};
fetchData();
fetchTeams();
}
}
}, [userID, token, accessToken, keys, userRole]);
useEffect(() => {
// This code will run every time selectedTeam changes
if (
keys !== null &&
selectedTeam !== null &&
selectedTeam !== undefined &&
selectedTeam.team_id !== null
) {
let sum = 0;
console.log(`keys: ${JSON.stringify(keys)}`)
for (const key of keys) {
if (
selectedTeam.hasOwnProperty("team_id") &&
key.team_id !== null &&
key.team_id === selectedTeam.team_id
) {
sum += key.spend;
}
}
console.log(`sum: ${sum}`)
setTeamSpend(sum);
} else if (keys !== null) {
// sum the keys which don't have team-id set (default team)
let sum = 0;
for (const key of keys) {
sum += key.spend;
}
setTeamSpend(sum);
}
}, [selectedTeam]);
if (invitation_id != null) {
return (
<Onboarding></Onboarding>
)
}
if (userID == null || token == null) {
// user is not logged in as yet
const url = proxyBaseUrl
? `${proxyBaseUrl}/sso/key/generate`
: `/sso/key/generate`;
// clear cookie called "token" since user will be logging in again
document.cookie = "token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
console.log("Full URL:", url);
window.location.href = url;
return null;
} else if (accessToken == null) {
return null;
}
if (userRole == null) {
setUserRole("App Owner");
}
if (userRole && userRole == "Admin Viewer") {
const { Title, Paragraph } = Typography;
return (
<div>
<Title level={1}>Access Denied</Title>
<Paragraph>Ask your proxy admin for access to create keys</Paragraph>
</div>
);
}
console.log("inside user dashboard, selected team", selectedTeam);
return (
<div className="w-full mx-4">
<Grid numItems={1} className="gap-2 p-8 h-[75vh] w-full mt-2">
<Col numColSpan={1}>
<ViewUserTeam
userID={userID}
userRole={userRole}
selectedTeam={selectedTeam ? selectedTeam : null}
accessToken={accessToken}
/>
<ViewUserSpend
userID={userID}
userRole={userRole}
userMaxBudget={userSpendData?.max_budget || null}
accessToken={accessToken}
userSpend={teamSpend}
selectedTeam={selectedTeam ? selectedTeam : null}
/>
<ViewKeyTable
userID={userID}
userRole={userRole}
accessToken={accessToken}
selectedTeam={selectedTeam ? selectedTeam : null}
data={keys}
setData={setKeys}
premiumUser={premiumUser}
teams={teams}
/>
<CreateKey
key={selectedTeam ? selectedTeam.team_id : null}
userID={userID}
team={selectedTeam ? selectedTeam : null}
userRole={userRole}
accessToken={accessToken}
data={keys}
setData={setKeys}
/>
<DashboardTeam
teams={teams}
setSelectedTeam={setSelectedTeam}
userRole={userRole}
proxySettings={proxySettings}
setProxySettings={setProxySettings}
userInfo={userSpendData}
accessToken={accessToken}
setKeys={setKeys}
/>
</Col>
</Grid>
</div>
);
};
export default UserDashboard;
|