forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImportDetailsPage.tsx
More file actions
489 lines (460 loc) · 15.3 KB
/
ImportDetailsPage.tsx
File metadata and controls
489 lines (460 loc) · 15.3 KB
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import { useContext, useMemo, useState } from 'react';
import { Helmet } from 'react-helmet';
import { useNavigate, useParams } from 'react-router-dom';
import { FormattedMessage, useIntl } from '@edx/frontend-platform/i18n';
import {
Stack, Container, Alert, Layout, Button,
DataTable,
} from '@openedx/paragon';
import Header from '@src/header';
import { useCourseDetails } from '@src/course-outline/data/apiHooks';
import SubHeader from '@src/generic/sub-header/SubHeader';
import {
ArrowForward, CheckCircle, Info, WarningFilled,
} from '@openedx/paragon/icons';
import Loading from '@src/generic/Loading';
import { ToastContext } from '@src/generic/toast-context';
import { Paragraph } from '@src/utils';
import { useBulkModulestoreMigrate, useModulestoreMigrationStatus } from '@src/data/apiHooks';
import { useGetContentHits } from '@src/search-manager';
import { ContainerType, getBlockType } from '@src/generic/key-utils';
import messages from './messages';
import { SummaryCard } from './stepper/SummaryCard';
import { HelpSidebar } from './HelpSidebar';
import { useLibraryContext } from '../common/context/LibraryContext';
import { useMigrationBlocksInfo } from '../data/apiHooks';
const ImportDetailsContent = () => {
const intl = useIntl();
const navigate = useNavigate();
const [enableRefeshState, setEnableRefreshState] = useState(true);
const { libraryId, libraryData } = useLibraryContext();
const { courseId, migrationTaskId } = useParams();
const { showToast } = useContext(ToastContext);
const [disableReimport, setDisableReimport] = useState(false);
// Using bulk migrate as it allows us to create collection automatically
// TODO: Modify single migration API to allow create collection
const migrate = useBulkModulestoreMigrate();
if (libraryId === undefined) {
// istanbul ignore next - This shouldn't be possible; it's just here to satisfy the type checker.
throw new Error('Error: route is missing libraryId.');
}
if (migrationTaskId === undefined) {
// istanbul ignore next - This shouldn't be possible; it's just here to satisfy the type checker.
throw new Error('Error: route is missing migrationId.');
}
const {
data: courseDetails,
isPending: isPendingCourseDetails,
} = useCourseDetails(courseId);
const {
data: migrationStatusData,
isPaused: isPendingMigrationStatusData,
} = useModulestoreMigrationStatus(migrationTaskId, enableRefeshState ? 1000 : false);
// Get the first migration, because the courses are imported one by one
const courseImportDetails = migrationStatusData?.parameters?.[0];
const {
data: migrationBlockInfo,
isPending: isPendingMigrationBlockInfo,
refetch: refetchMigrationBlockInfo,
} = useMigrationBlocksInfo(
libraryId,
undefined,
undefined,
migrationTaskId,
migrationStatusData?.state !== 'Failed',
);
const isPending = isPendingCourseDetails || isPendingMigrationStatusData || isPendingMigrationBlockInfo;
// Build migration summary using the migration blocks info
const {
migrationSummary,
unsupportedBlockIds,
} = useMemo(() => {
const counts: MigrationSummary = {
totalBlocks: 0,
sections: 0,
subsections: 0,
units: 0,
components: 0,
unsupported: 0,
};
const resultUnsupportedIds: string[] = [];
if (!migrationBlockInfo) {
return {
migrationSummary: counts,
unsupportedBlockIds: resultUnsupportedIds,
};
}
for (const block of migrationBlockInfo) {
if (!block.targetKey) {
// The migrations of this block is failed
counts.unsupported += 1;
resultUnsupportedIds.push(block.sourceKey);
} else {
counts.totalBlocks += 1;
const blockType = getBlockType(block.sourceKey);
switch (blockType) {
case ContainerType.Chapter:
counts.sections += 1;
break;
case ContainerType.Sequential:
counts.subsections += 1;
break;
case ContainerType.Vertical:
counts.units += 1;
break;
default:
counts.components += 1;
}
}
}
return {
migrationSummary: counts,
unsupportedBlockIds: resultUnsupportedIds,
};
}, [migrationBlockInfo]);
// Calculate current migration status
let migrationStatus = 'In Progress';
if (migrationStatusData?.state === 'Failed') {
// The entire task has failed
migrationStatus = 'Failed';
} else if (migrationStatusData?.state === 'Succeeded') {
// refetch migrationBlockInfo data once the import is complete
// eslint-disable-next-line @typescript-eslint/no-floating-promises
refetchMigrationBlockInfo();
// Currently, bulk migrate is being used to migrate courses because
// it has the ability to create collections.
// In bulk migration, the task may succeed, but each migration may fail.
// This checks whether the course migration has failed.
// TODO: Update this code when using simple migration
if (courseImportDetails?.isFailed) {
migrationStatus = 'Failed';
} else if (migrationSummary.unsupported !== 0) {
migrationStatus = 'Partial Succeeded';
} else {
migrationStatus = 'Succeeded';
}
}
// Fetch unsupported blocks usage_key information from meilisearch index.
const { data: unsupportedBlocksData } = useGetContentHits(
[
`usage_key IN [${unsupportedBlockIds.map(k => `"${k}"`).join(',')}]`,
],
(unsupportedBlockIds.length || 0) > 0,
['usage_key', 'block_type', 'display_name'],
unsupportedBlockIds.length,
true,
);
// Build the data for the reasons for failed imports
const unsupportedTableData = useMemo(() => {
if (!migrationBlockInfo || !unsupportedBlocksData) {
return [];
}
const reasons = migrationBlockInfo.reduce((result, block) => ({
...result,
[block.sourceKey]: block.unsupportedReason || '',
}), {} as Record<string, string>);
return unsupportedBlocksData.hits.map(block => ({
blockName: block.display_name,
blockType: block.block_type,
reason: reasons[block.usage_key],
}));
}, [migrationBlockInfo, unsupportedBlocksData]);
// In any state other than "in progress", it is no longer necessary
// to keep refreshing the task status.
if (enableRefeshState && migrationStatus !== 'In Progress') {
setEnableRefreshState(false);
}
const collectionLink = () => {
let libUrl = `/library/${libraryId}`;
if (courseImportDetails?.targetCollection?.key) {
libUrl += `/collection/${courseImportDetails.targetCollection.key}`;
}
return libUrl;
};
const handleImportCourse = async () => {
if (!courseId || !courseImportDetails || !courseDetails || !migrationStatusData) {
return;
}
setDisableReimport(true);
try {
const newMigrationTask = await migrate.mutateAsync({
sources: [courseId!],
target: libraryId,
createCollections: true,
repeatHandlingStrategy: 'fork',
compositionLevel: 'section',
});
navigate(`../import/${courseImportDetails.source}/${newMigrationTask.uuid}`);
setDisableReimport(false);
} catch {
showToast(intl.formatMessage(messages.importCourseCompleteFailedToastMessage, {
courseName: courseDetails.title,
}));
setDisableReimport(false);
}
};
if (isPending || !courseImportDetails) {
return <Loading />;
}
if (migrationStatus === 'Succeeded') {
return (
<Stack gap={3}>
<Helmet>
<title>
{libraryData?.title || ''} | {intl.formatMessage(messages.importSuccessfulAlertTitle)} | {process.env.SITE_NAME}
</title>
</Helmet>
<Alert
variant="success"
icon={CheckCircle}
stacked
actions={[
<Button
key="view-content"
variant="outline-primary"
iconAfter={ArrowForward}
onClick={() => navigate(collectionLink())}
>
<FormattedMessage {...messages.viewImportedContentButton} />
</Button>,
]}
>
<Alert.Heading>
<FormattedMessage {...messages.importSuccessfulAlertTitle} />
</Alert.Heading>
<p>
<FormattedMessage
{...messages.importSuccessfulAlertBody}
values={{
courseName: courseDetails?.title,
collectionName: courseImportDetails.targetCollection?.title,
}}
/>
</p>
</Alert>
<h4><FormattedMessage {...messages.importSummaryTitle} /></h4>
<SummaryCard
totalBlocks={migrationSummary.totalBlocks}
totalComponents={migrationSummary.components}
sections={migrationSummary.sections}
subsections={migrationSummary.subsections}
units={migrationSummary.units}
unsupportedBlocks={migrationSummary.unsupported}
isPending={isPendingMigrationBlockInfo}
/>
<p>
<FormattedMessage
{...messages.importSuccessfulBody}
values={{
courseName: courseDetails?.title,
}}
/>
</p>
</Stack>
);
} if (migrationStatus === 'Failed') {
return (
<Stack gap={3}>
<Helmet>
<title>
{libraryData?.title || ''} | {intl.formatMessage(messages.importFailedAlertTitle)} | {process.env.SITE_NAME}
</title>
</Helmet>
<Alert
variant="danger"
icon={Info}
stacked
actions={[
<Button
key="retry-btn"
variant="outline-primary"
iconAfter={ArrowForward}
onClick={handleImportCourse}
disabled={disableReimport}
>
<FormattedMessage {...messages.importFailedRetryImportButton} />
</Button>,
]}
>
<Alert.Heading>
<FormattedMessage {...messages.importFailedAlertTitle} />
</Alert.Heading>
<p>
<FormattedMessage
{...messages.importFailedAlertBody}
values={{
courseName: courseDetails?.title,
}}
/>
</p>
</Alert>
<h4><FormattedMessage {...messages.importFailedDetailsSectionTitle} /></h4>
<p>
<FormattedMessage {...messages.importFailedDetailsSectionBody} />
</p>
</Stack>
);
} if (migrationStatus === 'Partial Succeeded') {
return (
<Stack gap={3}>
<Helmet>
<title>
{libraryData?.title || ''} | {intl.formatMessage(messages.importPartialAlertTitle)} | {process.env.SITE_NAME}
</title>
</Helmet>
<Alert
variant="warning"
icon={WarningFilled}
stacked
actions={[
<Button
key="view-content"
variant="outline-primary"
iconAfter={ArrowForward}
onClick={() => navigate(collectionLink())}
>
<FormattedMessage {...messages.viewImportedContentButton} />
</Button>,
]}
>
<Alert.Heading>
<FormattedMessage {...messages.importPartialAlertTitle} />
</Alert.Heading>
<p>
<FormattedMessage
{...messages.importPartialAlertBody}
values={{
courseName: courseDetails?.title,
collectionName: courseImportDetails.targetCollection?.title,
}}
/>
</p>
</Alert>
<h4><FormattedMessage {...messages.importSummaryTitle} /></h4>
<SummaryCard
totalBlocks={migrationSummary.totalBlocks}
totalComponents={migrationSummary.components}
sections={migrationSummary.sections}
subsections={migrationSummary.subsections}
units={migrationSummary.units}
unsupportedBlocks={migrationSummary.unsupported}
isPending={isPendingMigrationBlockInfo}
/>
<div>
<FormattedMessage
{...messages.importPartialBody}
values={{
percentage: Math.floor(
(migrationSummary.totalBlocks * 100) / (migrationSummary.totalBlocks + migrationSummary.unsupported),
),
courseName: courseDetails?.title,
p: Paragraph,
}}
/>
</div>
{!isPendingMigrationBlockInfo && unsupportedTableData && (
<DataTable
isPaginated
initialState={{
pageSize: 10,
}}
itemCount={unsupportedTableData.length}
columns={[
{
Header: intl.formatMessage(messages.importPartialReasonTableBlockName),
accessor: 'blockName',
},
{
Header: intl.formatMessage(messages.importPartialReasonTableBlockType),
accessor: 'blockType',
},
{
Header: intl.formatMessage(messages.importPartialReasonTableReason),
accessor: 'reason',
},
]}
data={unsupportedTableData}
>
<DataTable.Table />
<DataTable.TableFooter />
</DataTable>
)}
</Stack>
);
}
return (
// In Progress
<Stack gap={3}>
<h4><FormattedMessage {...messages.importInProgressTitle} /></h4>
<p>
<FormattedMessage
{...messages.importInProgressBody}
values={{
courseName: courseDetails?.title,
}}
/>
</p>
<h4><FormattedMessage {...messages.importSummaryTitle} /></h4>
<SummaryCard isPending />
<div className="w-100 d-flex justify-content-end">
<Button
variant="outline-primary"
iconAfter={ArrowForward}
disabled
>
<FormattedMessage {...messages.viewImportedContentButton} />
</Button>
</div>
</Stack>
);
};
export interface MigrationSummary {
totalBlocks: number;
sections: number;
subsections: number;
units: number;
components: number;
unsupported: number;
}
export const ImportDetailsPage = () => {
const intl = useIntl();
const { libraryId, libraryData, readOnly } = useLibraryContext();
return (
<div className="d-flex">
<Helmet>
<title>{libraryData?.title || ''} | {process.env.SITE_NAME}</title>
</Helmet>
<div className="flex-grow-1">
<Header
number={libraryData?.slug}
title={libraryData?.title}
org={libraryData?.org}
contextId={libraryId}
isLibrary
readOnly={readOnly}
containerProps={{
size: undefined,
}}
/>
<Container className="mt-4 mb-5">
<div className="px-4 bg-light-200 border-bottom">
<SubHeader
title={intl.formatMessage(messages.importDetailsTitle)}
hideBorder
/>
</div>
<Layout xs={[{ span: 9 }, { span: 3 }]}>
<Layout.Element>
<div className="mt-4 px-4">
<ImportDetailsContent />
</div>
</Layout.Element>
<Layout.Element>
<HelpSidebar />
</Layout.Element>
</Layout>
</Container>
</div>
</div>
);
};