openreplay/frontend/app/mstore/userStore.ts
Delirium 622d0a7dfa
ui: omnisearch, timeseries charts redesign (#2791)
* ui: start redesign for live search/list

* ui: remove search field, show filters picker by default for assist

* ui: filter modal wip

* ui: filter modal wip

* ui: finish with omnisearch thing

* ui: start new dashboard redesign

* refining new card section

* ui: some "new dashboard" view improvs, fix icons fill inheritance, add ai button colors

* ui: split up search component (1.22+ tbd?), restrict filter type to own modals

* ui: mimic ant card

* ui: some changes for card creation flow, add series table to CustomMetricLineChart.tsx

* ui: more chart types, add table with filtering out series, start "compare to" thing

* ui: comparison designs

* ui: better granularity support, comparison view for bar chart

* ui: add comparison to more charts, add "metric" chart (BigNumChart.tsx)

* ui: cleanup logs

* ui: fix defualt import, fix sessheader crash, fix condition set ui

* ui: some refactoring and type coverage...

* ui: more refactoring; silence warnings for list renderers

* ui: moveing and renaming filters

* ui: add metricOf selector

* ui: check for metric type

* ui: fix crashes, add widget library table

* ui: change new series btn

* ui: restrict filterselection

* ui: fix timeseries table format

* ui: autoclose autocomplete modal

* ui: some fixes to issue filters default value, display and placeholder consistency

* ui: some dashboard issues with card selection modal and empty states

* ui: comparing for funnels, alternate column view, some refactoring to prepare for customizations...

* Style improvements in omnisearch headers

* Revert "Style improvements in omnisearch headers"

This reverts commit 89e51b0531.

* ui: show health status fetch error

* ui: table, bignum and comp for funnel, add csv export

* Omni-search improvements. (#2823)

Co-authored-by: Sudheer Salavadi <connect.uxmaster@gmail.com>

* ui: fix bad merge (git hallo?)

* ui: fix filter mapper

* rm husky

* ui: add card floater

* ui: add card floater

* ui: refactor local autocomplete input

* ui: filterout empty options

* UI improvements in New Cards (#2864)

* ui: some minor dashb improvements

* ui: metric type selector for head

* ui: change card type selector, add automapping

* ui: check chart/widget components for crashes

* ui: fix crash with table metrics

* ui: fix crashes related to metric type changes

* ui: filter category for clickmap filt

* ui: fix dash options menu, fix cr/up button

* ui: fix dash list menu propagation

* ui: hide addevent in heatmaps

* ui: fix time mapping for charts

* ui: fix exclusion component for path

* ui: fix series amount for path analysis, rm grid/list selector

* ui: fix icons in list view

* ui: fix for dlt button in widgets

* Various improvements Cards, OmniSearch and Cards  Listing (#2881)

* ui: some improvements for cards list view, funnels and general filter display

* ui: longer node width for journey

* Product Analytics UI Improvements. (#2896)

* Various improvements Cards, OmniSearch and Cards  Listing

* Improved cards listing page

* Various improvements in product analytics

* Charts UI improvements

---------

Co-authored-by: nick-delirium <nikita@openreplay.com>

* Live se red s2 (#2902)

* Various improvements Cards, OmniSearch and Cards  Listing

* Improved cards listing page

* Various improvements in product analytics

* Charts UI improvements

* ui crash

---------

Co-authored-by: Sudheer Salavadi <connect.uxmaster@gmail.com>

* ui: fix lucide version

* ui: fix custom comparison period

* ui: fix custom comparison period

* ui: handle minor paths on frontend for path/sankey

* ui: assign icon for event types in sankey nodes

* ui: some strings changed

* ui: hide btn control for table view

* Various improvements in graphs, and analytics pages. (#2908)

* Various improvements Cards, OmniSearch and Cards  Listing

* Improved cards listing page

* Various improvements in product analytics

* Charts UI improvements

* ui crash

* Chart improvements and layout toggling

* Various improvements

* Tooltips

---------

Co-authored-by: nick-delirium <nikita@openreplay.com>

* ui: fix weekday mapper for x axis on >7d range

* ui: lower default density to 35, fix table card display

* ui: filterMinorPaths -> return input data if nodes arr. is empty

* ui: use default filter for sessions, move around saved search actions, remove tags modal

* ui: fix card creator visibility in grid, fix table exporter visiblility in grid

* ui: fix some proptype warnings

* ui: change new series default expand state

* ui: save comp range in widget details

* ui: move timeseries to apache echarts

* ui: use unique id for window values

* ui: add timestamp for comp tooltip row

* ui: rename var for readability

* ui: fix comparison for 24hr

* Streamlined icons and improved echarts trends (#2920)

* Various improvements Cards, OmniSearch and Cards  Listing

* Improved cards listing page

* Various improvements in product analytics

* Charts UI improvements

* ui crash

* Chart improvements and layout toggling

* Various improvements

* Tooltips

* Improved icons in cards listing page

* Update WidgetFormNew.tsx

* Sankey improvements

* Icon and text updates

Text alignment and color changes in x-ray
Icon Mapping with appropriate names and shapes

* Colors and Trend Chart Interaction updates

* ui

---------

Co-authored-by: nick-delirium <nikita@openreplay.com>

* ui: series update observe

* ui: resize chart on window

* ui: move barchart to echarts

* ui: fixing bars under comparison

* ui: fixing horizontal bar tooltip

* ui: rm unused

* ui: keep state in storage

* ui: small fixes for granularity and comparisons

* ui: fix savesearch button, fix comparison period tracking

* ui: fix funnel type selection

* ui: fixing saved search button

* ui: enable error logging, remove immutable reference

* ui: update savedsearch drop

* ui: disable button if no saved

* ui: small ui fixes

* ui: add drill to summary charts, add more options to card category picker

* ui: filter compSeries with table

* ui: swap tag_el operator and value

* ui: fix top countries

* ui: further changes for search/cards

* ui: move focus to session list on line click

* ui: fix issue filter mapper

* ui: fix alert pre-init function, fix metric list options, fix legend placement

* ui: fixes for card library

* ui: work on new sankey chart

* ui: fix metadata prefetch

* ui: moving snakey to echarts

* ui: fix funnel comparison focus

* ui: stale loader

---------

Co-authored-by: Sudheer Salavadi <connect.uxmaster@gmail.com>
2025-01-24 09:58:35 +01:00

676 lines
16 KiB
TypeScript

import Account from 'Types/account';
import Client from 'Types/client';
import copy from 'copy-to-clipboard';
import { makeAutoObservable, runInAction } from 'mobx';
import { makePersistable } from 'mobx-persist-store';
import { toast } from 'react-toastify';
import { userService } from 'App/services';
import { deleteCookie } from 'App/utils';
import User from 'App/mstore/types/user';
class UserStore {
list: User[] = [];
instance: User | null = null;
page: number = 1;
pageSize: number = 10;
searchQuery: string = '';
modifiedCount: number = 0;
loading: boolean = false;
saving: boolean = false;
limits: any = {};
initialDataFetched: boolean = false;
account = new Account();
siteId: string | null = null;
passwordRequestError: boolean = false;
passwordErrors: string[] = [];
tenants: any[] = [];
onboarding: boolean = false;
sites: any[] = [];
jwt: string | null = null;
spotJwt: string | null = null;
errors: any[] = [];
loginRequest = {
loading: false,
errors: [] as string[]
};
fetchInfoRequest = {
loading: false,
errors: [] as string[]
};
signUpRequest = {
loading: false,
errors: [] as string[]
};
updatePasswordRequest = {
loading: false,
errors: [] as string[]
};
scopeState: number | null = null;
client = new Client();
authStore: AuthStore;
constructor(authStore: AuthStore) {
makeAutoObservable(this);
this.authStore = authStore;
void makePersistable(
this,
{
name: 'UserStore',
properties: [
'siteId',
'tenants',
'jwt',
'spotJwt',
'scopeState',
'onboarding',
{
key: 'account',
serialize: (acc) => {
return acc.id ? JSON.stringify(acc.toData()) : JSON.stringify({});
},
deserialize: (json) => {
return new Account(JSON.parse(json));
}
}
],
storage: window.localStorage
},
{
delay: 200
}
);
}
get isEnterprise() {
return (
this.account?.edition === 'ee' ||
this.authStore.authDetails?.edition === 'ee'
);
}
get isLoggedIn() {
return Boolean(this.jwt);
}
fetchLimits = (): Promise<any> => {
return new Promise((resolve, reject) => {
userService
.getLimits()
.then((response: any) => {
runInAction(() => {
this.setLimits(response);
});
resolve(response);
})
.catch((error: any) => {
reject(error);
});
});
};
setLimits = (limits: any) => {
this.limits = limits;
};
initUser = (user?: User): Promise<void> => {
return new Promise((resolve) => {
if (user) {
this.instance = new User().fromJson(user.toJson());
} else {
this.instance = new User();
}
resolve();
});
};
updateKey = (key: keyof this, value: any) => {
// @ts-ignore
this[key] = value;
if (key === 'searchQuery') {
this.page = 1;
}
};
updateUser = (user: User) => {
const index = this.list.findIndex((u) => u.userId === user.userId);
if (index > -1) {
this.list[index] = user;
}
};
fetchUser = (userId: string): Promise<any> => {
this.loading = true;
return new Promise((resolve, reject) => {
userService
.one(userId)
.then((data) => {
runInAction(() => {
this.instance = new User().fromJson(data);
});
resolve(data);
})
.catch((error) => {
runInAction(() => {
this.loading = false;
});
reject(error);
})
.finally(() => {
runInAction(() => {
this.loading = false;
});
});
});
};
fetchUsers = (): Promise<any> => {
this.loading = true;
return new Promise((resolve, reject) => {
userService
.all()
.then((response) => {
runInAction(() => {
this.list = response.map((user: any) => new User().fromJson(user));
});
resolve(response);
})
.catch((error) => {
runInAction(() => {
this.loading = false;
});
reject(error);
})
.finally(() => {
runInAction(() => {
this.loading = false;
});
});
});
};
saveUser = (user: User): Promise<any> => {
this.saving = true;
const wasCreating = !user.userId;
return new Promise((resolve, reject) => {
userService
.save(user)
.then((response) => {
runInAction(() => {
const newUser = new User().fromJson(response);
if (wasCreating) {
this.modifiedCount -= 1;
this.list.push(newUser);
toast.success('User created successfully');
} else {
this.updateUser(newUser);
toast.success('User updated successfully');
}
});
resolve(response);
})
.catch(async (e) => {
const err = await e.response?.json();
runInAction(() => {
this.saving = false;
});
const errStr = err.errors[0]
? err.errors[0].includes('already exists')
? `This email is already linked to an account or team on OpenReplay and can't be used again.`
: err.errors[0]
: 'Error saving user';
toast.error(errStr);
reject(e);
})
.finally(() => {
runInAction(() => {
this.saving = false;
});
});
});
};
deleteUser = (userId: string): Promise<any> => {
this.saving = true;
return new Promise((resolve, reject) => {
userService
.delete(userId)
.then((response) => {
runInAction(() => {
this.modifiedCount += 1;
this.list = this.list.filter((user) => user.userId !== userId);
});
resolve(response);
})
.catch((error) => {
runInAction(() => {
this.saving = false;
});
toast.error('Error deleting user');
reject(error);
})
.finally(() => {
runInAction(() => {
this.saving = false;
});
});
});
};
copyInviteCode = (userId: string): void => {
const content = this.list.find((u) => u.userId === userId)?.invitationLink;
if (content) {
copy(content);
toast.success('Invite code copied successfully');
} else {
toast.error('Invite code not found');
}
};
generateInviteCode = (userId: string): Promise<any> => {
this.saving = true;
const promise = new Promise((resolve, reject) => {
userService
.generateInviteCode(userId)
.then((response) => {
runInAction(() => {
const index = this.list.findIndex((u) => u.userId === userId);
if (index > -1) {
this.list[index].updateKey('isExpiredInvite', false);
this.list[index].updateKey(
'invitationLink',
response.invitationLink
);
}
copy(response.invitationLink);
});
resolve(response);
})
.catch((error) => {
runInAction(() => {
this.saving = false;
});
reject(error);
})
.finally(() => {
runInAction(() => {
this.saving = false;
});
});
});
toast.promise(promise, {
pending: 'Generating an invite code...',
success: 'Invite code generated successfully'
});
return promise;
};
syntheticLogin = ({ data }: any) => {
this.account = new Account(data.user);
this.spotJwt = data.spotJwt;
this.scopeState = data.scopeState;
this.loginRequest = { loading: false, errors: [] };
};
syntheticLoginError = (errors: any) => {
deleteCookie('jwt', '/', 'openreplay.com');
this.loginRequest = {
loading: false,
errors: errors || []
};
};
login = async (params: any) => {
this.loginRequest = { loading: true, errors: [] };
try {
const data = await userService.login(params);
runInAction(() => {
this.account = new Account(data.user);
this.jwt = data.jwt;
this.spotJwt = data.spotJwt;
this.scopeState = data.scopeState;
this.loginRequest = { loading: false, errors: [] };
});
} catch (error: any) {
runInAction(() => {
console.log('Login failed', error);
deleteCookie('jwt', '/', 'openreplay.com');
this.loginRequest = {
loading: false,
errors: error.errors || []
};
});
}
};
signup = async (params: any) => {
runInAction(() => {
this.signUpRequest = { loading: true, errors: [] };
});
try {
const data = await userService.signup(params);
runInAction(() => {
this.account = new Account(data.user);
this.scopeState = data.scopeState;
this.spotJwt = data.spotJwt;
this.jwt = data.jwt;
this.signUpRequest = { loading: false, errors: [] };
});
} catch (error) {
runInAction(() => {
this.signUpRequest = {
loading: false,
errors: error.response?.errors || []
};
});
toast.error('Error signing up; please check your data and try again');
} finally {
runInAction(() => {
this.signUpRequest.loading = false;
});
}
};
resetPassword = async (params: any) => {
runInAction(() => {
this.loading = true;
});
try {
const data = await userService.resetPassword(params);
runInAction(() => {
this.account = new Account(data.user);
this.jwt = data.jwt;
this.spotJwt = data.spotJwt;
});
} catch (error) {
toast.error('Error resetting your password; please try again');
return error.response;
} finally {
runInAction(() => {
this.loading = false;
});
}
};
requestResetPassword = async (params: any) => {
runInAction(() => {
this.loading = true;
});
try {
const response = await userService.requestResetPassword(params);
if (response.errors) {
toast.error(response.errors[0] || 'Error resetting your password, please try again');
return response;
}
} catch (error) {
toast.error('Unexpected error resetting your password; please try again');
} finally {
runInAction(() => {
this.loading = false;
});
}
};
updatePassword = async (params: any) => {
runInAction(() => {
this.updatePasswordRequest = { loading: true, errors: [] };
});
try {
const data = await userService.updatePassword(params) as { jwt: string, spotJwt: string, data: any };
runInAction(() => {
this.jwt = data.jwt;
this.spotJwt = data.spotJwt;
this.scopeState = data.data.scopeState;
this.updatePasswordRequest = { loading: false, errors: [] };
});
toast.success(`Successfully changed password`);
return data;
} catch (e: any) {
toast.error(e.message || 'Failed to updated password.');
throw e;
} finally {
runInAction(() => {
this.updatePasswordRequest = {
loading: false,
errors: []
};
});
}
};
fetchUserInfo = async () => {
runInAction(() => {
this.fetchInfoRequest = { loading: true, errors: [] };
});
try {
const data = await userService.fetchUserInfo();
runInAction(() => {
this.account = new Account(data);
this.scopeState = data.scopeState;
this.passwordErrors = [];
});
} catch (error) {
runInAction(() => {
deleteCookie('jwt', '/', 'openreplay.com');
this.resetStore();
});
} finally {
runInAction(() => {
this.fetchInfoRequest = { loading: false, errors: [] };
});
}
};
logout = async () => {
try {
await userService.logout();
runInAction(() => {
deleteCookie('jwt', '/', 'openreplay.com');
this.resetStore();
});
} catch (error) {
// TODO error handling
}
};
updateClient = async (params: any) => {
runInAction(() => {
this.loading = true;
});
try {
await userService.updateClient(params);
runInAction(() => {
Object.keys(params).forEach((key) => {
this.client[key] = params[key];
this.account[key] = params[key];
});
});
} catch (error) {
// TODO error handling
} finally {
runInAction(() => {
this.loading = false;
});
}
};
updateJwt = ({ jwt, spotJwt }: { jwt?: string; spotJwt?: string }) => {
this.jwt = jwt ?? null;
this.spotJwt = spotJwt ?? null;
};
getJwt = () => {
return this.jwt;
};
updateAccount = async (params: any) => {
runInAction(() => {
this.loading = true;
});
try {
const data = await userService.updateAccount(params);
runInAction(() => {
this.account = new Account(data);
this.scopeState = data.scopeState;
this.passwordErrors = [];
});
} catch (error) {
// TODO error handling
} finally {
runInAction(() => {
this.loading = false;
});
}
};
resendEmailVerification = async (email: string) => {
try {
await userService.resendEmailVerification(email);
} catch (error) {
// TODO error handling
}
};
pushNewSite = (newSite: any) => {
this.sites.push(newSite);
};
setOnboarding = (state: boolean = false) => {
this.onboarding = state;
};
resetErrors = () => {
this.passwordErrors = [];
this.loginRequest.errors = [];
this.errors = [];
};
updateModule = (moduleKey: string) => {
const modules = this.account.settings?.modules || [];
if (modules.includes(moduleKey)) {
this.account.settings.modules = modules.filter(
(module: string) => module !== moduleKey
);
} else {
this.account.settings.modules = [...modules, moduleKey];
}
};
upgradeScope = async () => {
try {
await userService.changeScope(2);
runInAction(() => {
this.scopeState = 2;
});
} catch (error) {
// TODO error handling
}
};
downgradeScope = async () => {
try {
await userService.changeScope(1);
runInAction(() => {
this.scopeState = 1;
});
} catch (error) {
// TODO error handling
}
};
resetStore = async () => {
this.account = new Account();
this.siteId = null;
this.passwordRequestError = false;
this.passwordErrors = [];
this.tenants = [];
this.onboarding = false;
this.sites = [];
this.jwt = null;
this.spotJwt = null;
this.errors = [];
this.loginRequest = {
loading: false,
errors: []
};
this.scopeState = null;
this.client = new Client();
this.list = [];
this.instance = null;
this.page = 1;
this.pageSize = 10;
this.searchQuery = '';
this.modifiedCount = 0;
this.loading = false;
this.saving = false;
this.limits = {};
this.initialDataFetched = false;
};
}
type AuthDetails = {
tenants: boolean;
sso: string | null;
ssoProvider: string | null;
enforceSSO: boolean | null;
edition?: 'foss' | 'ee' | 'msaas';
};
class AuthStore {
authDetails: AuthDetails = {
tenants: false,
sso: null,
ssoProvider: null,
enforceSSO: null,
edition: 'foss'
};
constructor() {
makeAutoObservable(this);
void makePersistable(this, {
name: 'AuthStore',
properties: [
'authDetails',
{
key: 'authDetails',
serialize: (ad) => {
delete ad['edition']
return Object.keys(ad).length > 0 ? JSON.stringify(ad) : JSON.stringify({});
},
deserialize: (json) => {
const ad = JSON.parse(json)
delete ad['edition']
return ad;
}
}
],
expireIn: 60000 * 60,
removeOnExpiration: true,
storage: window.localStorage
});
}
fetchTenants = async () => {
try {
const response = await userService.fetchTenants();
runInAction(() => {
this.authDetails = response;
});
} catch (error) {
// TODO error handling
}
};
}
export const authStore = new AuthStore();
const userStore = new UserStore(authStore);
export default userStore;