-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathimporters_stepper.js
More file actions
2611 lines (2275 loc) · 88.2 KB
/
Copy pathimporters_stepper.js
File metadata and controls
2611 lines (2275 loc) · 88.2 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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Bulk Import Stepper - Multi-step wizard for CSV/ZIP imports
// Handles file uploads, validation, settings, and review steps
//
// DEPENDENCIES:
// - jQuery (global)
// - BulkraxUtils (from bulkrax_utils.js - must load first)
//
// TABLE OF CONTENTS:
// - Utility Functions
// - Constants & Configuration
// - State Management
// - Initialization
// - Event Binding
// - File Validation & Utilities
// - File Upload Handlers
// - Demo Scenarios
// - Upload State Management
// - Validation
// - Validation Results Rendering
// - Import Summary & Hierarchy
// - Settings & Navigation
// - Form Submission & Success State
// - Notification Functions
; (function ($, Utils) {
'use strict'
// Import utilities from BulkraxUtils
var escapeHtml = Utils.escapeHtml
var formatFileSize = Utils.formatFileSize
var normalizeBoolean = Utils.normalizeBoolean
var t = Utils.t
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
// Delays function execution until after 'wait' milliseconds have passed
// since the last time it was invoked
function debounce(func, wait) {
var timeout
return function debounced() {
var context = this
var args = arguments
clearTimeout(timeout)
timeout = setTimeout(function () {
func.apply(context, args)
}, wait)
}
}
// ============================================================================
// CONSTANTS & CONFIGURATION
// ============================================================================
var CONSTANTS = {
// File upload limits
MAX_FILES: 2,
// Import size thresholds
IMPORT_SIZE_OPTIMAL: 100,
IMPORT_SIZE_MODERATE: 500,
IMPORT_SIZE_LARGE: 1000,
// File types
ALLOWED_EXTENSIONS: ['.csv', '.zip'],
// Upload states
UPLOAD_STATES: {
EMPTY: 'empty',
CSV_ONLY: 'csv_only',
ZIP_FILES_ONLY: 'zip_files_only',
ZIP_WITH_CSV: 'zip_with_csv',
CSV_AND_ZIP: 'csv_and_zip'
},
// Animation timings
ANIMATION_SPEED: 200,
SCROLL_SPEED: 300,
VALIDATION_DELAY: 2000,
NOTIFICATION_FADE_SPEED: 300,
DEBOUNCE_DELAY: 300,
// AJAX timeouts (in milliseconds)
AJAX_TIMEOUT_SHORT: 10000, // 10 seconds for simple requests
AJAX_TIMEOUT_LONG: 120000, // 2 minutes for validation
// Chunked upload settings (matches Hyrax v1 uploader)
CHUNK_SIZE: 10000000, // 10 MB per chunk
UPLOAD_URL: '/uploads/',
// Hierarchy rendering limits
MAX_TREE_DEPTH: 50, // Prevent stack overflow on deeply nested hierarchies
// Validation issue list cap — accordion shows up to this many items; full list is in the downloaded CSV
MAX_ISSUE_ITEMS: 10,
// API endpoints
ENDPOINTS: {
DEMO_SCENARIOS: '/importers/guided_import/demo_scenarios',
VALIDATE: '/importers/guided_import/validate',
DOWNLOAD_VALIDATION_ERRORS: '/importers/guided_import/download_validation_errors'
}
}
// ============================================================================
// STATE MANAGEMENT
// ============================================================================
var StepperState = {
currentStep: 1,
uploadedFiles: [],
uploadState: CONSTANTS.UPLOAD_STATES.EMPTY,
uploadMode: 'upload', // 'upload' or 'file_path'
validated: false,
validationData: null,
warningsAcked: false,
skipValidation: false, // Flag to skip validation step
isAddingFiles: false, // Flag to track if we're adding files vs replacing
demoScenario: null, // Track which demo scenario is loaded
demoScenariosData: null, // Cached demo scenarios JSON from server
uploadsInProgress: 0,
adminSetId: '',
adminSetName: '',
settings: {
name: '',
visibility: 'open',
rightsStatement: '',
limit: ''
}
}
// Guard flag to prevent rebinding events on every page load (Turbolinks)
var eventsInitialized = false
// ============================================================================
// INITIALIZATION
// ============================================================================
// Initialize on page load
function initBulkImportStepper() {
if ($('#bulk-import-stepper-form').length === 0) {
return
}
eventsInitialized = false
bindEvents()
initAdminSetState()
updateDownloadTemplateLink()
updateStepperUI()
initVisibilityCards()
setDefaultImportName()
}
// ============================================================================
// EVENT BINDING
// ============================================================================
// Bind all event handlers
function bindEvents() {
// Only bind events once, even if initBulkImportStepper runs multiple times
if (eventsInitialized) {
return // Events already bound, skip rebinding
}
// File upload - main dropzone
// <label for="file-input"> is needed for accessibility but also opens the file selector when clicked
// this will prevent that behavior while maintaining accessibility
$('.upload-dropzone').on('click', function (e) {
if (e.target.id === 'file-input') return
e.preventDefault()
openMainFilePicker()
})
// role="button" in WCAG 2.1 AA requires keyboard interaction for enter and space key
// this allows user to open the file picker with the space key when the dropzone is focused
$('.upload-dropzone').on('keydown', function (e) {
if (e.key === ' ') {
e.preventDefault()
openMainFilePicker()
}
})
// Delegated event handlers for dynamic content
// These only need to be bound once since they listen on stable parent containers
bindDelegatedEvents()
// File upload - add another dropzone
// <label for="file-input-additional"> is needed for accessibility but also opens the file selector when clicked
// this will prevent that behavior while maintaining accessibility
$('.upload-dropzone-small').on('click', function (e) {
e.preventDefault()
openAdditionalFilePicker()
})
// role="button" in WCAG 2.1 AA requires keyboard interaction for enter and space key
// this allows user to open the file picker with the space key when the dropzone is focused
$('.upload-dropzone-small').on('keydown', function (e) {
if (e.key === ' ') {
e.preventDefault()
openAdditionalFilePicker()
}
})
$('#file-input').on('change', function () {
handleFileSelect(StepperState.isAddingFiles)
StepperState.isAddingFiles = false // Reset flag after handling
})
// Drag and drop - main dropzone
$('.upload-dropzone').on('dragover', function (e) {
e.preventDefault()
$(this).addClass('dragover')
})
$('.upload-dropzone').on('dragleave', function (e) {
e.preventDefault()
$(this).removeClass('dragover')
})
$('.upload-dropzone').on('drop', function (e) {
e.preventDefault()
$(this).removeClass('dragover')
var droppedFiles = e.originalEvent.dataTransfer.files
if (droppedFiles.length > 0) {
// Prepare files array (up to MAX_FILES total)
var maxFiles = Math.min(droppedFiles.length, CONSTANTS.MAX_FILES)
var filesToAdd = []
for (var i = 0; i < maxFiles; i++) {
filesToAdd.push(droppedFiles[i])
}
// Try to set files on input element (with browser compatibility fallback)
setInputFiles($('#file-input')[0], filesToAdd)
handleFileSelect(false) // Drag and drop replaces files
// Show warning if more than MAX_FILES were dropped
if (droppedFiles.length > CONSTANTS.MAX_FILES) {
showNotification(
t('only_first_files', { count: CONSTANTS.MAX_FILES, max: CONSTANTS.MAX_FILES })
)
}
}
})
// Drag and drop - small "add another" dropzone
$('.upload-dropzone-small').on('dragover', function (e) {
e.preventDefault()
$(this).addClass('dragover')
})
$('.upload-dropzone-small').on('dragleave', function (e) {
e.preventDefault()
$(this).removeClass('dragover')
})
$('.upload-dropzone-small').on('drop', function (e) {
e.preventDefault()
$(this).removeClass('dragover')
var droppedFiles = e.originalEvent.dataTransfer.files
if (droppedFiles.length > 0) {
// Add only 1 file since we're adding to existing
var filesToAdd = [droppedFiles[0]]
// Try to set files on input element (with browser compatibility fallback)
setInputFiles($('#file-input')[0], filesToAdd)
handleFileSelect(true)
StepperState.isAddingFiles = false // reset after handling
// Show warning if more than 1 file was dropped
if (droppedFiles.length > 1) {
showNotification(
t('only_one_additional')
)
}
}
})
// Upload mode tabs
$('.upload-mode-tab').on('click', function () {
var mode = $(this).data('upload-mode')
switchUploadMode(mode)
})
// File path input
$('#import-file-path').on('input', debounce(function () {
resetValidationState()
updateValidateButtonState()
}, CONSTANTS.DEBOUNCE_DELAY))
// Demo scenarios (for testing)
if ($('#stepper-state').data('demo-scenarios-enabled')) {
$('.step-circle').on('dblclick', function () {
var $panel = $('.demo-scenarios')
$panel.toggle()
if ($panel.is(':visible')) {
// Prefetch scenarios data
loadDemoScenariosData().catch(function () {
// Error already handled in loadDemoScenariosData
})
}
})
$('.scenario-btn').on('click', function () {
var scenario = $(this).data('scenario')
loadDemoScenario(scenario)
$('.demo-scenarios').hide()
})
}
// Start over
$('.start-over-nav-btn').on('click', function () {
startOver()
})
// Validate button (one per tab; only the active one is visible)
$('#validate-upload-btn, #validate-path-btn').on('click', function () {
validateFiles()
})
// Warnings acknowledgment
$('#warnings-acked').on('change', function () {
StepperState.warningsAcked = $(this).is(':checked')
updateStepNavigation()
})
// Step navigation - next step
$('.step-next-btn').on('click', function () {
var nextStep = parseInt($(this).data('next-step'))
goToStep(nextStep)
})
// Step navigation - previous step
$('.step-prev-btn').on('click', function () {
var prevStep = parseInt($(this).data('prev-step'))
goToStep(prevStep)
})
// Form submission
$('#bulk-import-stepper-form').on('submit', function (e) {
e.preventDefault()
handleImportSubmit()
})
// Start another import
$('#start-another-import').on('click', function () {
location.reload()
})
// Settings form changes
$('#importer_name').on('input', debounce(function () {
StepperState.settings.name = $(this).val()
updateStepNavigation()
}, CONSTANTS.DEBOUNCE_DELAY))
// Admin set selection change
$('#importer-admin-set').on('change', function () {
StepperState.adminSetId = $(this).val()
StepperState.settings.adminSetName = $(this).find('option:selected').text()
resetValidationState()
updateStepNavigation()
updateDownloadTemplateLink()
// Update validate button state since admin set is required for validation
if (StepperState.uploadMode === 'file_path' || StepperState.uploadedFiles.length > 0) {
updateValidateButtonState()
}
})
// Rights statement selection change
$('select[name="importer[parser_fields][rights_statement]"]').on('change', function () {
StepperState.settings.rightsStatement = $(this).find('option:selected').text().trim()
// Clear if "None" was selected
if (!$(this).val()) {
StepperState.settings.rightsStatement = ''
}
updateStepNavigation()
})
$('#bulkrax_importer_limit').on('input', debounce(function () {
StepperState.settings.limit = $(this).val()
}, CONSTANTS.DEBOUNCE_DELAY))
// Remove file button (delegated to parent since rows are dynamic)
$('.uploaded-files-container').on('click', '.file-remove-btn', function () {
var $row = $(this).closest('.file-row')
var fileId = $row.data('file-id')
var fileEntry = StepperState.uploadedFiles.find(function (f) { return f.id === fileId })
if (fileEntry) {
if (fileEntry.uploadXhr) {
fileEntry.uploadAbortedByUser = true
fileEntry.uploadXhr.abort()
StepperState.uploadsInProgress--
}
if (fileEntry.uploadId) {
$.ajax({ url: CONSTANTS.UPLOAD_URL + fileEntry.uploadId, method: 'DELETE', timeout: CONSTANTS.AJAX_TIMEOUT_SHORT })
}
}
// Remove from uploadedFiles array
StepperState.uploadedFiles = StepperState.uploadedFiles.filter(
function (file) { return file.id !== fileId }
)
// Remove the row
$row.remove()
$('#file-input').val('')
// Reset validation since files changed
resetValidationState()
if (StepperState.uploadedFiles.length === 0) {
StepperState.skipValidation = false
$('#skip-validation-checkbox').prop('checked', false)
}
// Update upload state and re-render
updateUploadState()
renderUploadedFiles()
updateStepNavigation()
})
// Skip validation checkbox
$('#skip-validation-checkbox').on('change', function () {
StepperState.skipValidation = $(this).is(':checked')
updateStepNavigation()
})
// Mark events as initialized to prevent rebinding on subsequent page loads
eventsInitialized = true
}
// Bind delegated event handlers for dynamically rendered content
// These handlers are attached to stable parent containers and use event delegation
// to handle clicks on child elements. This is more efficient than rebinding handlers
// every time content is re-rendered.
function bindDelegatedEvents() {
// Accordion toggle events - delegated to validation results container
$('.validation-results').on('click.accordion', '.accordion-header', function () {
var $item = $(this).closest('.accordion-item')
var $content = $item.find('.accordion-content')
var $chevron = $item.find('.accordion-chevron')
if ($item.hasClass('accordion-open')) {
$content.slideUp(CONSTANTS.ANIMATION_SPEED)
$chevron.removeClass('fa-chevron-down').addClass('fa-chevron-right')
$item.removeClass('accordion-open')
} else {
$content.slideDown(CONSTANTS.ANIMATION_SPEED)
$chevron.removeClass('fa-chevron-right').addClass('fa-chevron-down')
$item.addClass('accordion-open')
}
})
// Tree toggle events - delegated to import summary container
function toggleTreeItem($item) {
var $children = $item.next('.tree-children')
var $chevron = $item.find('.tree-chevron')
if ($children.length > 0) {
var isExpanded = $children.is(':visible')
if (isExpanded) {
$children.slideUp(CONSTANTS.ANIMATION_SPEED)
$chevron.removeClass('fa-chevron-down').addClass('fa-chevron-right')
} else {
$children.slideDown(CONSTANTS.ANIMATION_SPEED)
$chevron.removeClass('fa-chevron-right').addClass('fa-chevron-down')
}
$item.attr('aria-expanded', String(!isExpanded))
}
}
$('.import-summary').on('click.tree', '.tree-item', function (e) {
e.stopPropagation()
toggleTreeItem($(this))
})
// Keyboard support for tree items (Enter/Space to toggle)
$('.import-summary').on('keydown.tree', '.tree-item[tabindex]', function (e) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
e.stopPropagation()
toggleTreeItem($(this))
}
})
}
// ============================================================================
// FILE VALIDATION & UTILITIES
// ============================================================================
// Check if DataTransfer constructor is available
function isDataTransferSupported() {
try {
return typeof DataTransfer !== 'undefined' && typeof DataTransfer === 'function'
} catch (e) {
return false
}
}
// Helper to set files on input element with browser compatibility
function setInputFiles(inputElement, files) {
if (isDataTransferSupported()) {
var dataTransfer = new DataTransfer()
for (var i = 0; i < files.length; i++) {
dataTransfer.items.add(files[i])
}
inputElement.files = dataTransfer.files
return true
} else {
// Fallback for older browsers: can't set files property
// Return false to indicate files weren't set on input
console.warn('DataTransfer not supported - files will be processed from memory')
return false
}
}
// Get file extension (lowercase)
function getFileExtension(filename) {
var lastDot = filename.lastIndexOf('.')
if (lastDot === -1) return ''
return filename.substring(lastDot).toLowerCase()
}
// Validate file extension
function isValidFileType(filename) {
var ext = getFileExtension(filename)
return CONSTANTS.ALLOWED_EXTENSIONS.indexOf(ext) !== -1
}
// Show inline error messages
function showFileUploadError(messages) {
var errorContainer = $('#file-upload-errors')
if (messages && messages.length > 0) {
var parts = [
'<div class="alert alert-danger alert-dismissible" role="alert">',
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">',
'<span aria-hidden="true">×</span>',
'</button>',
'<strong><span class="fa fa-exclamation-circle"></span> ' + t('file_upload_error') + '</strong>',
'<ul class="mb-0 mt-2">'
]
messages.forEach(function (msg) {
// Escape the message but allow intentional <br> tags for newlines
var escapedMsg = escapeHtml(msg).replace(/\n/g, '<br>')
parts.push('<li>' + escapedMsg + '</li>')
})
parts.push('</ul>', '</div>')
errorContainer.html(parts.join('')).show()
} else {
errorContainer.hide().html('')
}
}
// Clear file upload errors
function clearFileUploadError() {
$('#file-upload-errors').hide().html('')
}
// ============================================================================
// FILE UPLOAD HANDLERS
// ============================================================================
// Get tenant/account max file size (bytes) from the page, same source as v1 uploader
function getMaxFileSize() {
var val = $('.bulk-import-stepper-container').data('max-file-size')
if (val == null || val === '') return null
return parseInt(val, 10) || null
}
// Ensures the file picker opens in the correct mode (replace vs add)
// Ensures an invalid file is not added
function openMainFilePicker() {
StepperState.isAddingFiles = false
$('#file-input').val('')
$('#file-input').trigger('click')
}
// Open the file picker in "add" mode (appends to existing files)
function openAdditionalFilePicker() {
StepperState.isAddingFiles = true
$('#file-input').val('')
$('#file-input').trigger('click')
}
// Handle file selection
function handleFileSelect(isAddingMore) {
var files = $('#file-input')[0].files
if (files.length === 0) return
var maxFileSizeBytes = getMaxFileSize()
// If not adding more, abort any in-progress uploads and clean up server-side records
// before replacing the file list so we don't orphan uploads or desync uploadsInProgress.
if (!isAddingMore) {
StepperState.uploadedFiles.forEach(function (f) {
if (f.uploadXhr) {
f.uploadAbortedByUser = true
f.uploadXhr.abort()
}
if (f.uploadId) {
$.ajax({ url: CONSTANTS.UPLOAD_URL + f.uploadId, method: 'DELETE', timeout: CONSTANTS.AJAX_TIMEOUT_SHORT })
}
})
StepperState.uploadsInProgress = 0
StepperState.uploadedFiles = []
}
// Count existing file types
var existingCounts = StepperState.uploadedFiles.reduce(function (counts, f) {
if (f.fileType === 'csv' && !f.fromZip) counts.csv++
if (f.fileType === 'zip') counts.zip++
return counts
}, { csv: 0, zip: 0 })
var existingCsvCount = existingCounts.csv
var existingZipCount = existingCounts.zip
var addedFiles = []
var rejectedFiles = []
var newEntries = []
// Process selected files with validation
for (
var i = 0;
i < files.length && StepperState.uploadedFiles.length < CONSTANTS.MAX_FILES;
i++
) {
var file = files[i]
var fileName = file.name
var fileSize = formatFileSize(file.size)
// Validate file extension first
if (!isValidFileType(fileName)) {
rejectedFiles.push({
name: fileName,
reason: 'invalid_type',
extension: getFileExtension(fileName)
})
continue
}
// Reject empty/zero-byte files to avoid server-side errors
if (file.size === 0) {
rejectedFiles.push({ name: fileName, reason: 'file_empty' })
continue
}
// Respect tenant/account file size limit (same as v1 and Hyrax uploader)
if (maxFileSizeBytes != null && file.size > maxFileSizeBytes) {
rejectedFiles.push({
name: fileName,
reason: 'file_too_large',
size: file.size,
limit: maxFileSizeBytes
})
continue
}
var fileType = fileName.endsWith('.csv') ? 'csv' : 'zip'
// Check for duplicates
var isDuplicate = StepperState.uploadedFiles.some(function (f) {
return f.name === fileName
})
if (isDuplicate) {
rejectedFiles.push({ name: fileName, reason: 'duplicate' })
continue
}
// Validate file type constraints (max 1 CSV, max 1 ZIP)
if (fileType === 'csv' && existingCsvCount >= 1) {
rejectedFiles.push({ name: fileName, reason: 'duplicate CSV' })
continue
}
if (fileType === 'zip' && existingZipCount >= 1) {
rejectedFiles.push({ name: fileName, reason: 'duplicate ZIP' })
continue
}
// Add the file with upload tracking properties
var fileEntry = {
id: Date.now() + i,
name: fileName,
size: fileSize,
fileType: fileType,
fromZip: false,
file: file,
uploadId: null,
uploadProgress: 0,
uploadComplete: false,
uploadXhr: null
}
StepperState.uploadedFiles.push(fileEntry)
newEntries.push(fileEntry)
addedFiles.push(fileName)
// Update counts
if (fileType === 'csv') existingCsvCount++
if (fileType === 'zip') existingZipCount++
}
// Show appropriate warnings
if (rejectedFiles.length > 0) {
var messages = []
var categorized = rejectedFiles.reduce(function (acc, f) {
if (f.reason === 'invalid_type') acc.invalidTypes.push(f)
else if (f.reason === 'file_empty') acc.fileEmpty.push(f)
else if (f.reason === 'file_too_large') acc.fileTooLarge.push(f)
else if (f.reason === 'duplicate CSV') acc.duplicateCsv.push(f)
else if (f.reason === 'duplicate ZIP') acc.duplicateZip.push(f)
else if (f.reason === 'duplicate') acc.duplicates.push(f)
return acc
}, { invalidTypes: [], fileEmpty: [], fileTooLarge: [], duplicateCsv: [], duplicateZip: [], duplicates: [] })
// Handle invalid file types FIRST
if (categorized.invalidTypes.length > 0) {
messages.push(
t('invalid_format') + '\n' +
t('rejected_files') + '\n• ' +
categorized.invalidTypes.map(function (f) {
return f.name + ' (' + (f.extension || t('no_extension')) + ')'
}).join('\n• ')
)
}
if (categorized.fileEmpty.length > 0) {
messages.push(
'Empty files (0 bytes) are not allowed.\n' +
'The following files were rejected:\n• ' +
categorized.fileEmpty.map(function (f) { return f.name }).join('\n• ')
)
}
if (categorized.fileTooLarge.length > 0) {
var limitMb = categorized.fileTooLarge[0].limit / (1024 * 1024)
messages.push(
'File size exceeds the maximum allowed (' + Math.round(limitMb) + ' MB per file).\n' +
'The following files were rejected:\n• ' +
categorized.fileTooLarge.map(function (f) {
return f.name + ' (' + formatFileSize(f.size) + ')'
}).join('\n• ')
)
}
if (categorized.duplicateCsv.length > 0) {
messages.push(
t('csv_limit') + '\n• ' +
categorized.duplicateCsv
.map(function (f) {
return f.name
})
.join('\n• ')
)
}
if (categorized.duplicateZip.length > 0) {
messages.push(
t('zip_limit') + '\n• ' +
categorized.duplicateZip
.map(function (f) {
return f.name
})
.join('\n• ')
)
}
if (categorized.duplicates.length > 0) {
messages.push(
t('already_uploaded') + '\n• ' +
categorized.duplicates
.map(function (f) {
return f.name
})
.join('\n• ')
)
}
if (
StepperState.uploadedFiles.length >= CONSTANTS.MAX_FILES &&
files.length > addedFiles.length + rejectedFiles.length
) {
messages.push(t('max_files', { count: CONSTANTS.MAX_FILES }))
}
showFileUploadError(messages)
} else if (files.length > addedFiles.length) {
showFileUploadError([
t('max_files_added', { count: CONSTANTS.MAX_FILES, added: addedFiles.length })
])
} else {
clearFileUploadError()
}
// Reset validation since files changed
if (addedFiles.length > 0) {
resetValidationState()
}
updateUploadState()
renderUploadedFiles()
// Start chunked uploads for newly added files
newEntries.forEach(function (entry) {
if (entry.file) {
uploadFileChunked(entry)
}
})
}
// ============================================================================
// DEMO SCENARIOS
// ============================================================================
var demoScenariosRequest = null
// Fetch and cache demo scenarios JSON from server
function loadDemoScenariosData() {
// Return cached data as resolved promise
if (StepperState.demoScenariosData) {
return Promise.resolve(StepperState.demoScenariosData)
}
// Return existing promise if request is already in-flight
if (demoScenariosRequest) {
return demoScenariosRequest
}
demoScenariosRequest = $.ajax({
url: CONSTANTS.ENDPOINTS.DEMO_SCENARIOS,
method: 'GET',
dataType: 'json',
timeout: CONSTANTS.AJAX_TIMEOUT_SHORT
})
.then(function (data) {
StepperState.demoScenariosData = data
demoScenariosRequest = null // Clear in-flight tracker
return data
})
.catch(function (xhr) {
demoScenariosRequest = null // Clear in-flight tracker on error
var status = xhr.statusText || 'error'
var errorMsg = t('demo_load_failed')
if (status === 'timeout') {
errorMsg = t('demo_timeout')
} else if (xhr.status === 0) {
errorMsg = t('demo_network_error')
} else if (xhr.status >= 500) {
errorMsg = t('demo_server_error')
}
console.warn(errorMsg, {
status: status,
error: xhr.statusText,
statusCode: xhr.status
})
showNotification(errorMsg, 'error')
// Re-throw to allow caller to handle
throw new Error(errorMsg)
})
return demoScenariosRequest
}
// Load demo scenario from cached JSON
function loadDemoScenario(scenario) {
resetUploadState()
loadDemoScenariosData()
.then(function (data) {
if (!data || !data.scenarios || !data.scenarios[scenario]) {
console.warn('Demo scenario not found:', scenario)
return
}
StepperState.uploadedFiles = data.scenarios[scenario].files
StepperState.demoScenario = scenario
updateUploadState()
renderUploadedFiles()
})
.catch(function (error) {
// Error already handled and displayed in loadDemoScenariosData
console.error('Failed to load demo scenario:', error)
})
}
// ============================================================================
// CHUNKED FILE UPLOAD (to Hyrax /uploads/ endpoint)
// ============================================================================
function uploadFileChunked(fileEntry) {
var file = fileEntry.file
if (!file) return
StepperState.uploadsInProgress++
fileEntry.uploadProgress = 0
fileEntry.uploadComplete = false
fileEntry.uploadId = null
fileEntry.uploadAbortedByUser = false
updateValidateButtonState()
renderUploadedFiles()
var chunkSize = CONSTANTS.CHUNK_SIZE
var totalSize = file.size
var offset = 0
function sendNextChunk() {
if (offset >= totalSize) {
fileEntry.uploadComplete = true
fileEntry.uploadProgress = 100
StepperState.uploadsInProgress--
updateValidateButtonState()
renderUploadedFiles()
return Promise.resolve()
}
var end = Math.min(offset + chunkSize, totalSize)
var isFirstChunk = (offset === 0)
var chunk = file.slice(offset, end)
var formData = new FormData()
formData.append('files[]', chunk, file.name)
var headers = {}
if (!isFirstChunk) {
formData.append('id', fileEntry.uploadId)
headers['Content-Range'] = 'bytes ' + offset + '-' + (end - 1) + '/' + totalSize
}
var currentOffset = offset
return new Promise(function (resolve, reject) {
var ajaxOptions = {
url: CONSTANTS.UPLOAD_URL,
method: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
timeout: 0,
xhr: function () {
var xhr = new XMLHttpRequest()
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
var chunkLoaded = currentOffset + e.loaded
var percent = Math.round((chunkLoaded / totalSize) * 100)
fileEntry.uploadProgress = Math.min(percent, 99)
renderUploadProgress(fileEntry)
}
})
return xhr
}
}
if (Object.keys(headers).length > 0) {
ajaxOptions.headers = headers
}
var jqXhr = $.ajax(ajaxOptions)
fileEntry.uploadXhr = jqXhr
jqXhr
.then(function (result) {
if (isFirstChunk && result.files && result.files[0]) {
fileEntry.uploadId = result.files[0].id
}
offset = end
fileEntry.uploadXhr = null
resolve()
})
.catch(function (xhr) {
fileEntry.uploadXhr = null
reject(new Error(xhr.statusText || 'Upload failed'))
})
}).then(sendNextChunk)
}
sendNextChunk().catch(function (error) {
if (!fileEntry.uploadAbortedByUser) {
StepperState.uploadsInProgress--
}
fileEntry.uploadAbortedByUser = false
if (fileEntry.uploadId) {
$.ajax({ url: CONSTANTS.UPLOAD_URL + fileEntry.uploadId, method: 'DELETE', timeout: CONSTANTS.AJAX_TIMEOUT_SHORT })
}
StepperState.uploadedFiles = StepperState.uploadedFiles.filter(function (f) {
return f !== fileEntry
})
updateUploadState()
updateValidateButtonState()
renderUploadedFiles()
if (error.message !== 'abort') {
showNotification('Upload failed for ' + file.name + ': ' + (error.message || 'Unknown error'), 'error')
}
})
}