app/stores/UsersStore.ts
Rama main · réplica de lectura del repositorio original.
import commandScore from "command-score";
import invariant from "invariant";
import { deburr, differenceWith, orderBy } from "es-toolkit/compat";
import { action, computed, makeObservable, override, runInAction } from "mobx";
import type { UserRole } from "@shared/types";
import User from "~/models/User";
import { client } from "~/utils/ApiClient";
import type RootStore from "./RootStore";
import Store, { RPCAction } from "./base/Store";
export default class UsersStore extends Store<User> {
actions = [
RPCAction.Info,
RPCAction.List,
RPCAction.Create,
RPCAction.Update,
RPCAction.Delete,
RPCAction.Count,
];
constructor(rootStore: RootStore) {
super(rootStore, User);
makeObservable(this);
}
@computed
get active(): User[] {
return this.all.filter((user) => !user.isSuspended && !user.isInvited);
}
@computed
get suspended(): User[] {
return this.all.filter((user) => user.isSuspended);
}
@computed
get activeOrInvited(): User[] {
return this.all.filter((user) => !user.isSuspended);
}
@computed
get invited(): User[] {
return this.all.filter((user) => user.isInvited);
}
@computed
get admins(): User[] {
return this.all.filter((user) => user.isAdmin && !user.isInvited);
}
@computed
get members(): User[] {
return this.all.filter(
(user) => !user.isViewer && !user.isAdmin && !user.isInvited
);
}
@computed
get viewers(): User[] {
return this.all.filter((user) => user.isViewer && !user.isInvited);
}
@computed
get all(): User[] {
return this.orderedData.filter((user) => !user.isDeleted);
}
@override
get orderedData(): User[] {
return orderBy(
Array.from(this.data.values()),
(user) => user.name.toLocaleLowerCase(),
"asc"
);
}
@action
updateRole = async (user: User, role: UserRole) => {
await this.actionOnUser("update_role", user, role);
};
@action
suspend = async (user: User) => {
await this.actionOnUser("suspend", user);
};
@action
activate = async (user: User) => {
await this.actionOnUser("activate", user);
};
@action
invite = async (
invites: {
email: string;
name: string;
role: UserRole;
}[]
): Promise<User[]> => {
const res = await client.post(`/users.invite`, {
invites,
});
invariant(res?.data, "Data should be available");
let response: User[] = [];
runInAction(() => {
response = res.data.users.map(this.add);
});
return response;
};
@action
resendInvite = async (user: User) =>
client.post(`/users.resendInvite`, {
id: user.id,
});
/**
* Returns the loaded user with the given email address, if any.
*
* @param email the email address to look up.
* @returns the matching user, or undefined if none exists.
*/
getByEmail = (email: string): User | undefined => {
const normalizedEmail = email.trim().toLowerCase();
return this.all.find(
(user) => user.email?.trim().toLowerCase() === normalizedEmail
);
};
/**
* Returns users that are not in the given document, optionally filtered by a query.
*
* @param documentId
* @param query
* @returns A list of users that are not in the given document.
*/
notInDocument = (documentId: string, query = "") => {
const document = this.rootStore.documents.get(documentId);
const teamMembers = this.activeOrInvited;
const documentMembers = document?.members ?? [];
const users = differenceWith(
teamMembers,
documentMembers,
(teamMember, documentMember) => teamMember.id === documentMember.id
);
return queriedUsers(users, query);
};
/**
* Returns users that are not in the given collection, optionally filtered by a query.
*
* @param collectionId
* @param query
* @returns A list of users that are not in the given collection.
*/
notInCollection = (collectionId: string, query = "") => {
const groupUsers = this.rootStore.memberships.orderedData.filter(
(member) => member.collectionId === collectionId
);
const userIds = groupUsers.map((groupUser) => groupUser.userId);
const users = this.activeOrInvited.filter(
(user) => !userIds.includes(user.id)
);
return queriedUsers(users, query);
};
inCollection = (collectionId: string, query?: string) => {
const groupUsers = this.rootStore.memberships.orderedData.filter(
(member) => member.collectionId === collectionId
);
const userIds = groupUsers.map((groupUser) => groupUser.userId);
const users = this.activeOrInvited.filter((user) =>
userIds.includes(user.id)
);
return queriedUsers(users, query);
};
notInGroup = (groupId: string, query = "") => {
const groupUsers = this.rootStore.groupUsers.orderedData.filter(
(member) => member.groupId === groupId
);
const userIds = groupUsers.map((groupUser) => groupUser.userId);
const users = this.activeOrInvited.filter(
(user) => !userIds.includes(user.id)
);
return queriedUsers(users, query);
};
inGroup = (groupId: string, query?: string) => {
const groupUsers = this.rootStore.groupUsers.orderedData.filter(
(member) => member.groupId === groupId
);
const userIds = groupUsers.map((groupUser) => groupUser.userId);
const users = this.activeOrInvited.filter((user) =>
userIds.includes(user.id)
);
return queriedUsers(users, query);
};
actionOnUser = async (action: string, user: User, role?: UserRole) => {
const res = await client.post(`/users.${action}`, {
id: user.id,
role,
});
invariant(res?.data, "Data should be available");
runInAction(() => {
this.addPolicies(res.policies);
this.add(res.data);
});
};
}
export function queriedUsers(users: User[], query?: string) {
const normalizedQuery = deburr((query || "").toLocaleLowerCase());
return normalizedQuery
? users
.filter(
(user) =>
deburr(user.name.toLocaleLowerCase()).includes(normalizedQuery) ||
user.email?.includes(normalizedQuery)
)
.map((user) => ({
user,
score: commandScore(user.name, normalizedQuery),
}))
.sort((a, b) => b.score - a.score)
.map(({ user }) => user)
: users;
}