Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion apps/backend/src/datasources/UserDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,11 @@ export interface UserDataSource {
): Promise<{ totalCount: number; users: BasicUserDetails[] }>;
getPreviousCollaborators(
user_id: number,
filter?: string,
first?: number,
offset?: number,
sortField?: string,
sortDirection?: string,
searchText?: string,
userRole?: UserRole,
subtractUsers?: [number]
): Promise<{ totalCount: number; users: BasicUserDetails[] }>;
Expand Down
8 changes: 6 additions & 2 deletions apps/backend/src/datasources/mockups/UserDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -442,9 +442,13 @@ export class UserDataSourceMock implements UserDataSource {

async getPreviousCollaborators(
user_id: number,
filter?: string,
first?: number,
offset?: number
offset?: number,
sortField?: string,
sortDirection?: string,
searchText?: string,
userRole?: UserRole,
subtractUsers?: [number]
): Promise<{ totalCount: number; users: BasicUserDetails[] }> {
return {
totalCount: 2,
Expand Down
69 changes: 51 additions & 18 deletions apps/backend/src/datasources/postgres/UserDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ import {
createUserObject,
} from './records';

const fieldMap: { [key: string]: string } = {
created_at: 'created_at',
firstname: 'firstname',
preferredname: 'preferredname',
lastname: 'lastname',
institution: 'i.institution',
};

export default class PostgresUserDataSource implements UserDataSource {
async delete(id: number): Promise<User | null> {
return database('users')
Expand Down Expand Up @@ -494,26 +502,25 @@ export default class PostgresUserDataSource implements UserDataSource {
}

async getUsers({
filter,
searchText,
first,
offset,
userRole,
subtractUsers,
orderBy,
orderDirection = 'desc',
sortField = 'created_at',
sortDirection = 'desc',
}: UsersArgs): Promise<{ totalCount: number; users: BasicUserDetails[] }> {
return database
.select(['*', database.raw('count(*) OVER() AS full_count')])
.from('users')
.join('institutions as i', { 'users.institution_id': 'i.institution_id' })
.orderBy('users.user_id', orderDirection)
.modify((query) => {
if (filter) {
if (searchText) {
query.andWhere((qb) => {
qb.whereILikeEscaped('institution', '%?%', filter)
.orWhereILikeEscaped('firstname', '%?%', filter)
.orWhereILikeEscaped('preferredname', '%?%', filter)
.orWhereILikeEscaped('lastname', '%?%', filter);
qb.whereILikeEscaped('institution', '%?%', searchText)
.orWhereILikeEscaped('firstname', '%?%', searchText)
.orWhereILikeEscaped('preferredname', '%?%', searchText)
.orWhereILikeEscaped('lastname', '%?%', searchText);
});
}
if (first) {
Expand All @@ -530,8 +537,12 @@ export default class PostgresUserDataSource implements UserDataSource {
if (subtractUsers && subtractUsers.length > 0) {
query.whereNotIn('users.user_id', subtractUsers);
}
if (orderBy) {
query.orderBy(orderBy, orderDirection);
if (sortField && sortDirection) {
if (!fieldMap.hasOwnProperty(sortField)) {
throw new GraphQLError(`Bad sort field given: ${sortField}`);
}
sortField = fieldMap[sortField];
query.orderByRaw(`${sortField} ${sortDirection}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to validate the user’s input values with GraphQL in this case?
The sortDirection string goes directly into the SQL command which could be harmful.

}
})
.then(
Expand All @@ -550,14 +561,24 @@ export default class PostgresUserDataSource implements UserDataSource {

async getPreviousCollaborators(
userId: number,
filter?: string,
first?: number,
offset?: number,
sortField?: string,
sortDirection?: string,
searchText?: string,
userRole?: UserRole,
subtractUsers?: [number]
): Promise<{ totalCount: number; users: BasicUserDetails[] }> {
if (userId == -1) {
return this.getUsers({ filter, first, offset, userRole, subtractUsers });
return this.getUsers({
searchText,
first,
offset,
userRole,
subtractUsers,
sortField,
sortDirection,
});
}

const lastCollaborators = await this.getMostRecentCollaborators(userId);
Expand All @@ -574,14 +595,26 @@ export default class PostgresUserDataSource implements UserDataSource {
.join('institutions as i', { 'users.institution_id': 'i.institution_id' })
.whereIn('users.user_id', userIds)
.modify((query) => {
if (filter) {
if (searchText) {
query.andWhere((qb) => {
qb.whereILikeEscaped('institution', '%?%', filter)
.orWhereILikeEscaped('firstname', '%?%', filter)
.orWhereILikeEscaped('preferredname', '%?%', filter)
.orWhereILikeEscaped('lastname', '%?%', filter);
qb.whereILikeEscaped('institution', '%?%', searchText)
.orWhereILikeEscaped('firstname', '%?%', searchText)
.orWhereILikeEscaped('preferredname', '%?%', searchText)
.orWhereILikeEscaped('lastname', '%?%', searchText);
});
}
logger.logInfo(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is not important then I would not log the sort information.

`Sort field: ${sortField}, direction: ${sortDirection}`,
{}
);
if (sortField && sortDirection) {
if (!fieldMap.hasOwnProperty(sortField)) {
throw new GraphQLError(`Bad sort field given: ${sortField}`);
}
sortField = fieldMap[sortField];
query.orderByRaw(`${sortField} ${sortDirection}`);
}

if (first) {
query.limit(first);
}
Expand Down
12 changes: 8 additions & 4 deletions apps/backend/src/datasources/stfc/StfcUserDataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,7 @@ export class StfcUserDataSource implements UserDataSource {
offset: offset,
userRole: undefined,
subtractUsers: subtractUsers,
orderDirection: 'asc',
sortDirection: 'asc',
});

if (users[0]) {
Expand All @@ -610,18 +610,22 @@ export class StfcUserDataSource implements UserDataSource {

async getPreviousCollaborators(
userId: number,
filter?: string,
first?: number,
offset?: number,
userRole?: number,
sortField?: string,
sortDirection?: string,
searchText?: string,
userRole?: UserRole,
subtractUsers?: [number]
): Promise<{ totalCount: number; users: BasicUserDetails[] }> {
const dbUsers: BasicUserDetails[] = (
await postgresUserDataSource.getPreviousCollaborators(
userId,
filter,
first,
offset,
sortField,
sortDirection,
searchText,
undefined,
subtractUsers
)
Expand Down
8 changes: 6 additions & 2 deletions apps/backend/src/queries/UserQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,17 +140,21 @@ export default class UserQueries {
async getPreviousCollaborators(
agent: UserWithRole | null,
userId: number,
filter?: string,
first?: number,
offset?: number,
sortField?: string,
sortDirection?: string,
searchText?: string,
userRole?: UserRole,
subtractUsers?: [number]
) {
return this.dataSource.getPreviousCollaborators(
userId,
filter,
first,
offset,
sortField,
sortDirection,
searchText,
userRole,
subtractUsers
);
Expand Down
19 changes: 13 additions & 6 deletions apps/backend/src/resolvers/queries/UsersQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,14 @@ export class UsersArgs {
@Field(() => [Int], { nullable: 'itemsAndList' })
subtractUsers?: [number];

@Field(() => String, { nullable: true })
orderBy?: string;
@Field({ nullable: true })
public sortField?: string;

@Field(() => String, { nullable: true })
orderDirection?: string;
@Field({ nullable: true })
public sortDirection?: string;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here, we could use SortDirection enum (asc, desc) for validating the input, I guess.


@Field({ nullable: true })
public searchText?: string;
}

@ArgsType()
Expand All @@ -65,20 +68,24 @@ export class UsersQuery {
@Args()
{
userId,
filter,
first,
offset,
userRole,
subtractUsers,
sortField,
sortDirection,
searchText,
}: PreviousCollaboratorsArgs,
@Ctx() context: ResolverContext
) {
return context.queries.user.getPreviousCollaborators(
context.user,
userId,
filter,
first,
offset,
sortField,
sortDirection,
searchText,
userRole,
subtractUsers
);
Expand Down
45 changes: 42 additions & 3 deletions apps/frontend/src/components/experiment/ExperimentsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { useSearchParams } from 'react-router-dom';

import { Experiment, SettingsId } from 'generated/sdk';
import { useFormattedDateTime } from 'hooks/admin/useFormattedDateTime';
import { setSortDirectionOnSortField } from 'utils/helperFunctions';
import useDataApiWithFeedback from 'utils/useDataApiWithFeedback';

import ExperimentReviewContent, {
Expand Down Expand Up @@ -58,7 +59,7 @@ export default function ExperimentsTable({
const page = searchParams.get('page');
const pageSize = searchParams.get('pageSize');
const selectedExperimentId = searchParams.get('experiment');

const [isFirstRender, setIsFirstRender] = useState(true);
const refreshTableData = () => {
tableRef.current?.onQueryChange({});
};
Expand All @@ -75,10 +76,14 @@ export default function ExperimentsTable({
React.useEffect(() => {
let isMounted = true;

if (isMounted) {
if (isMounted && !isFirstRender) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refreshTableData();
}

if (isFirstRender) {
setIsFirstRender(false);
}

return () => {
isMounted = false;
};
Expand Down Expand Up @@ -193,6 +198,12 @@ export default function ExperimentsTable({
];
}

columns = setSortDirectionOnSortField(
columns,
searchParams.get('sortField'),
searchParams.get('sortDirection')
);

const experimentReviewTabs = [
EXPERIMENT_MODAL_TAB_NAMES.EXPERIMENT_INFORMATION,
EXPERIMENT_MODAL_TAB_NAMES.PROPOSAL_INFORMATION,
Expand All @@ -215,12 +226,21 @@ export default function ExperimentsTable({
options={{
searchText: search || undefined,
pageSize: pageSize ? +pageSize : 10,
initialPage: search ? 0 : page ? +page : 0,
initialPage: page ? +page : 0,
}}
onRowsPerPageChange={(pageSize) => {
setSearchParams((searchParams) => {
searchParams.set('pageSize', pageSize.toString());
searchParams.set('page', '0');

return searchParams;
});
}}
onSearchChange={(searchText) => {
setSearchParams((searchParams) => {
if (searchText) {
searchParams.set('search', searchText);
searchParams.set('page', '0');
} else {
searchParams.delete('search');
}
Expand All @@ -235,6 +255,25 @@ export default function ExperimentsTable({
return searchParams;
});
}}
onOrderCollectionChange={(orderByCollection) => {
const [orderBy] = orderByCollection;

if (!orderBy) {
setSearchParams((searchParams) => {
searchParams.delete('sortField');
searchParams.delete('sortDirection');

return searchParams;
});
} else {
setSearchParams((searchParams) => {
searchParams.set('sortField', orderBy.orderByField);
searchParams.set('sortDirection', orderBy.orderDirection);

return searchParams;
});
}
}}
/>

{selectedExperiment && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ const CreateUpdateInstrument = ({

try {
await api()
.getUsers({ filter: value, userRole: UserRole.INSTRUMENT_SCIENTIST })
.getUsers({
userRole: UserRole.INSTRUMENT_SCIENTIST,
searchText: value,
})
.then((data) => {
if (data.users?.totalCount == 0) {
setFieldError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ const CreateUpdateInternalReview = ({

try {
await api()
.getUsers({ filter: value, userRole: UserRole.INTERNAL_REVIEWER })
.getUsers({ searchText: value, userRole: UserRole.INTERNAL_REVIEWER })
.then((data) => {
if (data.users?.totalCount == 0) {
setFieldError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,8 @@ function ParticipantSelector({
];

const { users } = await api().getUsers({
filter: query,
subtractUsers: excludedUserIds,
searchText: query,
});

setOptions(users?.users || []);
Expand Down
Loading
Loading