Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SW-5940 follow up - Improve errors when uploading modules/deliverables and fix search/sort on modules #3278

Merged
merged 4 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
36 changes: 34 additions & 2 deletions src/api/types/generated-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3091,6 +3091,26 @@ export interface components {
ImageVariablePayload: {
type: "Image";
} & Omit<components["schemas"]["VariablePayload"], "type">;
ImportDeliverableProblemElement: {
problem: string;
/** Format: int32 */
row: number;
};
ImportDeliverableResponsePayload: {
message?: string;
problems: components["schemas"]["ImportDeliverableProblemElement"][];
status: components["schemas"]["SuccessOrError"];
};
ImportModuleProblemElement: {
problem: string;
/** Format: int32 */
row: number;
};
ImportModuleResponsePayload: {
message?: string;
problems: components["schemas"]["ImportModuleProblemElement"][];
status: components["schemas"]["SuccessOrError"];
};
InternalTagPayload: {
/** Format: int64 */
id: number;
Expand Down Expand Up @@ -3396,6 +3416,7 @@ export interface components {
/** Format: int64 */
moduleId: number;
moduleName: string;
projects?: components["schemas"]["ModuleEventProject"][];
/** Format: uri */
recordingUrl?: string;
/** Format: uri */
Expand All @@ -3407,6 +3428,17 @@ export interface components {
/** @enum {string} */
type: "One-on-One Session" | "Workshop" | "Live Session" | "Recorded Session";
};
ModuleEventProject: {
/** Format: int64 */
cohortId: number;
cohortName: string;
/** Format: int64 */
participantId: number;
participantName: string;
/** Format: int64 */
projectId: number;
projectName: string;
};
ModulePayload: {
additionalResources?: string;
/** Format: date */
Expand Down Expand Up @@ -5974,7 +6006,7 @@ export interface operations {
/** @description The requested operation succeeded. */
200: {
content: {
"application/json": components["schemas"]["SimpleSuccessResponsePayload"];
"application/json": components["schemas"]["ImportDeliverableResponsePayload"];
};
};
};
Expand Down Expand Up @@ -6330,7 +6362,7 @@ export interface operations {
/** @description The requested operation succeeded. */
200: {
content: {
"application/json": components["schemas"]["SimpleSuccessResponsePayload"];
"application/json": components["schemas"]["ImportModuleResponsePayload"];
};
};
};
Expand Down
30 changes: 25 additions & 5 deletions src/components/common/ImportModal.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import React, { useEffect, useRef, useState } from 'react';

import { Box, useTheme } from '@mui/material';
import { Box, Typography, useTheme } from '@mui/material';

import Link from 'src/components/common/Link';
import { useOrganization } from 'src/providers/hooks';
import { Response } from 'src/services/HttpService';
import { ImportResponsePayload } from 'src/services/ModuleService';
import strings from 'src/strings';
import { Facility } from 'src/types/Facility';
import { GetUploadStatusResponsePayload, ResolveResponse, UploadFileResponse, UploadResponse } from 'src/types/File';
import useSnackbar from 'src/utils/useSnackbar';

import DialogBox from './DialogBox/DialogBox';
import ProgressCircle from './ProgressCircle/ProgressCircle';
Expand All @@ -26,7 +27,7 @@ export type ImportSpeciesModalProps = {
uploadApi?: (file: File, orgOrFacilityId: string) => Promise<UploadFileResponse>;
templateApi?: () => Promise<any>;
statusApi?: (uploadId: number) => Promise<UploadResponse>;
simpleUploadApi?: (file: File) => Promise<Response>;
simpleUploadApi?: (file: File) => Promise<ImportResponsePayload | null>;
importCompleteLabel: string;
importingLabel: string;
duplicatedLabel: string;
Expand Down Expand Up @@ -79,6 +80,7 @@ export default function ImportSpeciesModal(props: ImportSpeciesModalProps): JSX.
const [warning, setWarning] = useState(false);
const [uploadId, setUploadId] = useState<number>();
const theme = useTheme();
const snackbar = useSnackbar();

const spacingStyles = { marginRight: theme.spacing(2) };

Expand Down Expand Up @@ -189,9 +191,27 @@ export default function ImportSpeciesModal(props: ImportSpeciesModalProps): JSX.
setLoading(true);
const response = await simpleUploadApi(file);
if (response) {
if (response.requestSucceeded === false) {
if (response.status === 'error') {
setLoading(false);
setError(<>{strings.DATA_IMPORT_FAILED}</>);
snackbar.toastError(
response.problems?.length > 0
? [
<ul key='errors'>
{response.problems.map((problem, index) => (
<li key={`import-error-item-${index}`}>
{strings.formatString(
strings.DATA_IMPORT_ROW_MESSAGE,
`${problem.row}`,
problem.problem || strings.GENERIC_ERROR
)}
</li>
))}
</ul>,
]
: [<Typography key='error-message'>{response.message}</Typography>],
strings.UPLOAD_FAILED
);
onClose(false);
} else {
setLoading(false);
setCompleted(true);
Expand Down
18 changes: 17 additions & 1 deletion src/redux/features/modules/modulesAsyncThunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import { ListDeliverablesElementWithOverdue } from 'src/types/Deliverables';
import {
ModuleCohortsAndProjectsSearchResult,
ModuleProjectSearchResult,
ModuleSearchResult,
UpdateCohortModuleRequest,
} from 'src/types/Module';
import { SearchNodePayload, SearchRequestPayload } from 'src/types/Search';
import { SearchNodePayload, SearchRequestPayload, SearchSortOrder } from 'src/types/Search';

export const requestGetModule = createAsyncThunk(
'modules/get',
Expand Down Expand Up @@ -221,3 +222,18 @@ export const requestListModuleCohortsAndProjects = createAsyncThunk(
return rejectWithValue(strings.GENERIC_ERROR);
}
);

export const requestSearchModules = createAsyncThunk(
'modules/search',
async (request: { search?: SearchNodePayload; sortOrder?: SearchSortOrder }, { rejectWithValue }) => {
const { search, sortOrder } = request;

const response: ModuleSearchResult[] | null = await ModuleService.search(search, sortOrder);

if (response) {
return response;
}

return rejectWithValue(strings.GENERIC_ERROR);
}
);
2 changes: 2 additions & 0 deletions src/redux/features/modules/modulesSelectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ export const selectUpdateManyCohortModule = (requestId: string) => (state: RootS

export const selectModuleCohortsAndProjects = (moduleId: string) => (state: RootState) =>
state.moduleCohortsAndProjects[moduleId];

export const selectSearchModules = (requestId: string) => (state: RootState) => state.searchModules[requestId];
18 changes: 17 additions & 1 deletion src/redux/features/modules/modulesSlice.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createSlice } from '@reduxjs/toolkit';

import { ListDeliverablesElement } from 'src/types/Deliverables';
import { Module, ModuleCohortsAndProjectsSearchResult } from 'src/types/Module';
import { Module, ModuleCohortsAndProjectsSearchResult, ModuleSearchResult } from 'src/types/Module';

import { StatusT, buildReducers } from '../asyncUtils';
import {
Expand All @@ -12,6 +12,7 @@ import {
requestListModuleDeliverables,
requestListModuleProjects,
requestListModules,
requestSearchModules,
requestUpdateCohortModule,
requestUpdateManyCohortModule,
} from './modulesAsyncThunks';
Expand Down Expand Up @@ -142,6 +143,20 @@ export const moduleCohortsAndProjectsSlice = createSlice({
},
});

/**
* Search modules
*/
const initialStateSearchModules: { [key: string]: StatusT<ModuleSearchResult[]> } = {};

export const searchModulesSlice = createSlice({
name: 'searchModulesSlice',
initialState: initialStateSearchModules,
reducers: {},
extraReducers: (builder) => {
buildReducers(requestSearchModules)(builder);
},
});

const moduleReducers = {
module: moduleSlice.reducer,
moduleDeliverables: ModuleDeliverablesSlice.reducer,
Expand All @@ -152,6 +167,7 @@ const moduleReducers = {
cohortModuleDeleteMany: cohortModuleDeleteManySlice.reducer,
cohortModuleUpdateMany: cohortModuleUpdateManySlice.reducer,
moduleCohortsAndProjects: moduleCohortsAndProjectsSlice.reducer,
searchModules: searchModulesSlice.reducer,
};

export default moduleReducers;
2 changes: 1 addition & 1 deletion src/scenes/AcceleratorRouter/Modules/ModuleView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export default function ModuleView(): JSX.Element {
);

return (
<Page crumbs={crumbs} title={<CommonTitleBar title={module?.name} subtitle={`${strings.PHASE_ID}:`} />}>
<Page crumbs={crumbs} title={<CommonTitleBar title={module?.name} />}>
<Box
ref={contentRef}
display='flex'
Expand Down
68 changes: 44 additions & 24 deletions src/scenes/AcceleratorRouter/Modules/index.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,61 @@
import React, { useCallback, useState } from 'react';
import { useDispatch } from 'react-redux';
import React, { useCallback, useEffect, useState } from 'react';

import { IconName, TableColumnType } from '@terraware/web-components';

import PageListView, { PageListViewProps } from 'src/components/DocumentProducer/PageListView';
import useListModules from 'src/hooks/useListModules';
import { useLocalization } from 'src/providers';
import { requestSearchModules } from 'src/redux/features/modules/modulesAsyncThunks';
import { selectSearchModules } from 'src/redux/features/modules/modulesSelectors';
import { useAppDispatch, useAppSelector } from 'src/redux/store';
import strings from 'src/strings';
import { SearchSortOrder } from 'src/types/Search';
import { ModuleSearchResult } from 'src/types/Module';
import { SearchNodePayload, SearchSortOrder } from 'src/types/Search';

import ModulesCellRenderer from './ModulesCellRenderer';
import UploadModulesModal from './UploadModulesModal';

const columns = (activeLocale: string | null): TableColumnType[] =>
activeLocale
? [
{ key: 'name', name: strings.MODULE, type: 'string' },
{ key: 'id', name: strings.MODULE_ID, type: 'string' },
{ key: 'cohortsQuantity', name: strings.COHORTS, type: 'number' },
{ key: 'deliverablesQuantity', name: strings.DELIVERABLES, type: 'number' },
]
: [];

const defaultSearchOrder: SearchSortOrder = {
field: 'name',
direction: 'Ascending',
};

const fuzzySearchColumns = ['name'];

export default function ModuleContentView() {
const { activeLocale } = useLocalization();
const { modules, listModules } = useListModules();
const [openUploadModal, setOpenUploadModal] = useState(false);
const dispatch = useDispatch();
const dispatch = useAppDispatch();
const [requestId, setRequestId] = useState('');
const modulesResponse = useAppSelector(selectSearchModules(requestId));
const [modules, setModules] = useState<ModuleSearchResult[]>([]);

const dispatchSearchRequest = useCallback(() => {
listModules({});
}, [dispatch]);
const dispatchSearchRequest = useCallback(
(locale: string | null, search: SearchNodePayload, searchSortOrder: SearchSortOrder) => {
const request = dispatch(requestSearchModules({ search, sortOrder: searchSortOrder }));
setRequestId(request.requestId);
},
[dispatch]
);

const columns = (activeLocale: string | null): TableColumnType[] =>
activeLocale
? [
{ key: 'name', name: strings.MODULE, type: 'string' },
{ key: 'id', name: strings.MODULE_ID, type: 'string' },
{ key: 'phaseId', name: strings.PHASE_ID, type: 'string' },
{ key: 'cohortsQuantity', name: strings.VERSION, type: 'number' },
{ key: 'deliverablesQuantity', name: strings.CREATED, type: 'date' },
]
: [];
useEffect(() => {
if (!modulesResponse) {
return;
}

const defaultSearchOrder: SearchSortOrder = {
field: 'name',
direction: 'Ascending',
};
if (modulesResponse?.status === 'success' && modulesResponse?.data) {
setModules(modulesResponse.data);
}
}, [modulesResponse]);

const showUploadModal = () => {
setOpenUploadModal(true);
Expand All @@ -53,8 +72,9 @@ export default function ModuleContentView() {
columns: () => columns(activeLocale),
defaultSearchOrder,
dispatchSearchRequest,
fuzzySearchColumns,
id: 'modules-list',
rows: modules || [],
rows: modules,
Renderer: ModulesCellRenderer,
},
};
Expand Down
7 changes: 5 additions & 2 deletions src/services/DeliverablesService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { SearchNodePayload, SearchSortOrder } from 'src/types/Search';
import { today } from 'src/utils/dateUtils';
import { SearchAndSortFn, SearchOrderConfig, searchAndSort as genericSearchAndSort } from 'src/utils/searchAndSort';

import { ImportResponsePayload } from './ModuleService';
import { getPromisesResponse } from './utils';

/**
Expand Down Expand Up @@ -42,6 +43,8 @@ export type UpdateSubmissionResponsePayload =
paths[typeof ENDPOINT_DELIVERABLE_SUBMISSION]['put']['responses'][200]['content']['application/json'];
export type SubmitSubmissionResponsePayload =
paths[typeof ENDPOINT_DELIVERABLE_SUBMISSION_SUBMIT]['post']['responses'][200]['content']['application/json'];
export type ImportDeliverablesResponsePayload =
paths[typeof DELIVERABLES_IMPORT_ENDPOINT]['post']['responses'][200]['content']['application/json'];

const httpDeliverables = HttpService.root(ENDPOINT_DELIVERABLES);
const httpDeliverableSubmission = HttpService.root(ENDPOINT_DELIVERABLE_SUBMISSION);
Expand Down Expand Up @@ -204,7 +207,7 @@ const incomplete = async (deliverableiId: number, projectId: number): Promise<Re
/**
* import deliverables
*/
const importDeliverables = async (file: File): Promise<Response> => {
const importDeliverables = async (file: File): Promise<ImportResponsePayload> => {
const entity = new FormData();
entity.append('file', file);
const headers = { 'content-type': 'multipart/form-data' };
Expand All @@ -214,7 +217,7 @@ const importDeliverables = async (file: File): Promise<Response> => {
headers,
});

return serverResponse;
return serverResponse.data;
};

const DeliverablesService = {
Expand Down
2 changes: 1 addition & 1 deletion src/services/HttpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ async function handleRequest<I extends ServerData, O>(
response.statusCode = serverResponse.status;
}
const data: I = serverResponse.data;
if (data?.status === 'error') {
if (data?.status === 'error' && serverResponse.status !== 200) {
addError(data, response);
} else {
response.requestSucceeded = true;
Expand Down
Loading