-
Notifications
You must be signed in to change notification settings - Fork 1
/
ui_import.js
732 lines (582 loc) · 22.7 KB
/
ui_import.js
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
module.exports = function () {
var self = this;
// no inbox
self.config.noInbox = self.config.noInbox || false;
// process UI config
self.config['import'].ui.selectors = self.config['import'].ui.selectors || {};
self.config['import'].ui.operationChange = self.config['import'].ui.operationChange || { selector: '.operation', event: 'change', attribute: 'value' };
self.config['import'].ui.selectors.waiter = self.config['import'].ui.selectors.waiter || '.waiter';
self.config['import'].ui.selectors.inboxPage = self.config['import'].ui.selectors.inboxPage || '#inbox';
self.config['import'].ui.selectors.mappingPage = self.config['import'].ui.selectors.mappingPage || '#mapping';
self.config['import'].ui.selectors.operationName = self.config['import'].ui.selectors.operationName || '.operation-name';
self.config['import'].ui.selectors.operationDo = self.config['import'].ui.selectors.operationDo || '.operation-do';
self.config['import'].ui.selectors.operationCancel = self.config['import'].ui.selectors.operationCancel || '.operation-cancel';
// file list
self.config['import'].ui.selectors.file = self.config['import'].ui.selectors.file || '.file';
self.config['import'].ui.selectors.files = self.config['import'].ui.selectors.files || '.files';
self.config['import'].ui.selectors.inboxFilePath = self.config['import'].ui.selectors.inboxFilePath || '.path';
self.config['import'].ui.selectors.inboxFileImport = self.config['import'].ui.selectors.inboxFileImport || '.import';
self.config['import'].ui.selectors.inboxFileDelete = self.config['import'].ui.selectors.inboxFileDelete || '.delete';
self.config['import'].ui.selectors.inboxFileDownload = self.config['import'].ui.selectors.inboxFileDownload || '.download';
// column mapping
self.config['import'].ui.selectors.field = self.config['import'].ui.selectors.field || '.field';
self.config['import'].ui.selectors.fields = self.config['import'].ui.selectors.fields || '.fields';
self.config['import'].ui.selectors.template = self.config['import'].ui.selectors.template || '.template';
self.config['import'].ui.selectors.mappingPath = self.config['import'].ui.selectors.mappingPath || '.path';
self.config['import'].ui.selectors.templateSel = self.config['import'].ui.selectors.templateSel || '.field-template';
self.config['import'].ui.selectors.nameSel = self.config['import'].ui.selectors.nameSel || '.field-name';
self.config['import'].ui.selectors.fieldSelectSel = self.config['import'].ui.selectors.fieldSelectSel || '.field-select';
self.config['import'].ui.selectors.fieldRequired = self.config['import'].ui.selectors.fieldRequired || '.required';
// the waiter
self.$.waiter = $(self.config['import'].ui.selectors.waiter, self.dom);
// the pages
self.$.pages = {};
self.$.pages.inbox = $(self.config['import'].ui.selectors.inboxPage, self.dom);
self.$.pages.mapping = $(self.config['import'].ui.selectors.mappingPage, self.dom);
// the file template
self.$.file = $(self.config['import'].ui.selectors.file, self.dom).detach();
// the file container
self.$.files = $(self.config['import'].ui.selectors.files, self.dom);
// the field template
self.$.field = $(self.config['import'].ui.selectors.field, self.dom).detach();
// the field container
self.$.fields = $(self.config['import'].ui.selectors.fields, self.dom);
// field template
self.$.fieldTemplate = $('.field-template', self.dom);
// the template select
self.$.select = $(self.config['import'].ui.selectors.template, self.dom);
// columnData cache
self.columnData = {};
self.operation = 'insert';
$(self.dom).on('click', self.config['import'].ui.selectors.operationCancel, function() {
self.emit('reset');
});
$(self.dom).on('click', self.config['import'].ui.selectors.operationDo, function () {
self.emit('import');
});
// configure internal events
self.on('_startWaiting', startWaiting);
self.on('_endWaiting', endWaiting);
self.on('_deleteFile', deleteFile);
self.on('_download', download);
self.on('_showMappings', showMappings);
self.on('_setTemplates', setTemplates);
self.on('_refreshTable', refreshTable);
self.on('_refreshFields', refreshFields);
// configure external events
self.on('readInbox', readInbox);
self.on('reset', reset);
self.on('setTemplate', setTemplate);
self.on('import', importData);
// ******************************************
// read the inbox
if (!self.config.noInbox) {
self.emit('readInbox');
}
// detect field select change
// TODO Why this doesn't work?
//$(self.dom).on('change', 'select.field-select', function () {
$(document).on('change', 'select.field-select', function () {
// get field name
var columnIndex = parseInt($(this).val());
var fieldKey = $(this).attr('name');
self.mappings = self.mappings || {};
if (isNaN(columnIndex)) {
// if empty value, delete that field
delete self.mappings[fieldKey];
} else {
// else set it in mappings
self.mappings[fieldKey] = columnIndex;
}
// refresh table
self.emit('_refreshTable');
});
// changes in data-option fields
$(document).on('change', '#' + self.miid + ' [data-option]', function () {
// get option name
var option = $(this).attr('data-option');
// update column data
self.columnData[option] = $(this).attr('type') !== 'checkbox' ? $(this).val() : $(this).prop('checked');
// and show mappings
self.emit('_showMappings', function(err) {
if (err) {
alert(err);
return;
}
resetMappings.call(self);
self.emit('_refreshTable');
self.emit('_refreshFields');
});
});
// changes to the operation controls
$(document).on(self.config['import'].ui.operationChange.event, self.config['import'].ui.operationChange.selector, function () {
// handle radio buttons or checkboxes
if ($(self.config['import'].ui.operationChange.selector).first().prop('tagName') === 'INPUT') {
self.operation = 'insert';
$(self.config['import'].ui.operationChange.selector).each(function () {
if ($(this).prop('checked')) {
self.operation = $(this).attr(self.config['import'].ui.operationChange.attribute);
}
});
}
// handle other DOM elements
else {
self.operation = $(this).attr(self.config['import'].ui.operationChange.value);
}
if (!self.operation) {
return;
}
// give the import button a better name
$(self.config['import'].ui.selectors.operationName).text(self.operation.charAt(0).toUpperCase() + self.operation.slice(1));
if (self.operation === 'insert') {
$('#upsert').attr('disabled', true);
$('.update').hide();
$('.delete').hide();
} else if (self.operation === 'update') {
$('#upsert').removeAttr('disabled');
$('.delete').hide();
$('.update').show();
} else if (self.operation === 'delete') {
$('#upsert').attr('disabled', true);
$('.update').hide();
$('.delete').show();
}
});
// add change handler for template select
templateChangeHandler.call(self);
}
function readInbox () {
var self = this;
// start a waiter
self.emit('_startWaiting');
self.link('readInbox', function(err, files) {
// end the waiter
self.emit('_endWaiting', 'inbox');
if (err) {
alert(err);
return;
}
self.inbox = files;
// no need to continue if we don't have a file container
if (!self.$.files.length) {
return;
}
// remove all the files
self.$.files.empty();
// add back the new files
for (var i = 0; i < files.length; ++i) {
appendFile.call(self, files[i]);
}
});
}
function templateChangeHandler () {
var self = this;
$(self.dom).off('change');
$(self.dom).on('change', self.config['import'].ui.selectors.template, function () {
self.emit('setTemplate', $(this).val());
});
}
function resetMappings () {
var self = this;
if (self.mappings) {
self.mappings = {};
}
}
function setTemplate (templateId) {
var self = this;
// we reset if the user clears the template selection
if (!templateId) {
self.emit('reset');
return;
}
// otherwise we refresh the fields and the table
self.emit('template', self['import'].template);
self.emit('_refreshFields');
self.emit('_refreshTable');
}
function importData () {
var self = this;
// getting required info
var info = gatherInfo.call(self);
//
// operation checks
//
// no mappings, no fun
if (!Object.keys(info.mappings).length) {
self.emit('notifications.show', {
type: 'error',
message: 'You must map the columns in the CSV file with some template fields'
});
return;
}
// update and delete operations need a query key
if (['delete', 'update'].indexOf(info.operation) !== -1) {
if (!info.key) {
self.emit('notifications.show', {
type: 'error',
message: 'You must select a key field for this operation'
});
return;
}
}
// calling server operation
self.link('import', { data: info }, function (err) {
// TODO add translations
var notificationMessage = {
de: 'Importen startet.',
fr: 'Impotaux startaux.',
it: 'Importi starti.'
}
self.emit('notifications.show', {
type: err ? 'error' : 'info',
message: err ? err.error || err : notificationMessage[M.getLocale()]
});
self.emit('reset');
});
}
function getSelectedTemplate (templateId) {
var self = this;
for (var templateId in self.templates) {
if (!self.templates.hasOwnProperty(templateId)) continue;
if (templateId === templateId) {
return self.templates[templateId];
}
}
return undefined;
}
// Set template fields to DOM if page is rendered. Otherwise, it does not render templates options again.
function refreshFields () {
var self = this;
if (!self['import'].template) {
return;
}
// TODO Move to config
var templateSel = self.config['import'].ui.selectors.templateSel,
nameSel = self.config['import'].ui.selectors.nameSel,
reqSel = self.config['import'].ui.selectors.fieldRequired,
fieldSelectSel = self.config['import'].ui.selectors.fieldSelectSel;
// set template
var $template = self.$.fieldTemplate;
var fieldsToAdd = [];
// show mapping fields
$('.mapping-fields').show();
// reorder the fields
var fields = [];
var schema = self['import'].template.schema;
// get the schema fields with keys and computed labels
for (var key in schema) {
if (!schema.hasOwnProperty(key)) continue;
// ignore core fields and link fields
if (key[0] === '_' || schema[key].link) continue;
// clone the schema field to avoid changes in the referenced object
var field = JSON.parse(JSON.stringify(schema[key]));
// label (i18n) if available, else key
var label = field.label || key;
if (typeof label === 'object') {
label = label[M.getLocale()] || key;
}
field.key = key;
field.label = label;
fields.push(field);
}
// sort the fields
fields.sort(function(f1, f2) {
if (f1.order < f2.order) {
return -1;
} else if (f1.order > f2.order) {
return 1;
} else {
return f1.label <= f2.label ? -1 : 1;
}
});
// add the fields
for (var i = 0; i < fields.length; ++i) {
// clone DOM template
// TODO possible error due to substring
var $field = $template.clone().removeClass(templateSel.substring(1));
// set the label
$field.find(nameSel).text(fields[i].label);
// show the required marker
if (fields[i].required) {
$field.find(reqSel).show();
}
// append options
if (self.$.fieldOptions) {
$(fieldSelectSel, $field).append(self.$.fieldOptions.clone()).attr('name', fields[i].key);
}
if (fields[i].type === 'number') {
$('.operator', $field).removeClass('hide');
} else {
$('.operator', $field).addClass('hide');
}
// push field into array
fieldsToAdd.push($field);
}
// empty all fields
self.$.fields.empty()
// and append the new fields
.append(fieldsToAdd);
};
function appendFile (file) {
var self = this;
var $file = self.$.file.clone();
var ps = self.config['import'].ui.selectors.inboxFilePath;
var path = file.path;
$file.find(ps).html(file.path);
$file.on('click', self.config['import'].ui.selectors.inboxFileImport, function() {
// save path in column data
self.columnData.path = $(this).parents(self.config['import'].ui.selectors.file).find(ps).text();
// and show mappings
self.emit('_showMappings');
});
$file.on('click', self.config['import'].ui.selectors.inboxFileDelete, function() {
var $thisFile = $(this).parents(self.config['import'].ui.selectors.file);
/*
* This function is called after the confirm popup answer is `true`
* */
function deleteThisFile () {
// only hide the file
$thisFile.hide();
// trigger a file deletion operations
self.emit('_deleteFile', $thisFile.find(ps).text(), function(err) {
// show back the file on error or remove on success
if (err) {
$thisFile.fadeIn();
} else {
$thisFile.remove();
}
});
}
// create the English message
var deleteEnglishMessage = 'Are you sure you want to delete this file?';
// if module has i18n
if (self.config.i18n) {
// emit message event for i18n module
self.emit('message', deleteEnglishMessage, function (err, translatedData) {
// get the translated message
if (confirm(translatedData.message)) {
// if confirmed, call delete file function
deleteThisFile();
}
});
// no i18n, show the Enlish message
} else if (confirm(deleteEnglishMessage)) {
// if confirmed, call delete file function
deleteThisFile();
}
});
$file.on('click', self.config['import'].ui.selectors.inboxFileDownload, function () {
self.emit('_download', path);
});
// add the new file to the dom
self.$.files.append($file);
}
function setTemplates () {
var self = this;
var selectElem = self.config['import'].ui.selectors.template;
var $options = $('<div>');
for (var templateId in self.templates) {
if (!self.templates.hasOwnProperty(templateId)) continue;
var value = templateId;
var name = self.templates[templateId].options.label[M.getLocale()] || self.templates[templateId].options.label;
if (self.templates[templateId].options.group) {
name = self.templates[templateId].options.group + ' - ' + name;
}
var $option = $('<option>').attr('value', value).text(name);
$options.append($option);
}
$(selectElem).append($options.children());
}
function deleteFile (path, callback) {
var self = this;
self.link('deleteFile', { data: path }, callback);
}
function download (path) {
// get the module
var self = this;
// create a form
var $form = $('<form>').attr({
'action': '/@/' + self.miid + '/download',
'method': 'POST'
});
// append some inputs
$form
.append($('<input>').val(path).attr('name', 'path'))
.hide()
.appendTo(document.body);
// submit the form
$form.submit();
}
function showMappings (callback) {
var self = this;
callback = callback || function () {};
// start a waiter
self.emit('_startWaiting');
var $pathLabel = self.$.pages.mapping.find(self.config['import'].ui.selectors.mappingPath);
if ($pathLabel.prop('tagName') === 'INPUT') {
$pathLabel.val(self.columnData.path);
} else {
$pathLabel.text(self.columnData.path);
}
self.link('getColumns', { data: self.columnData }, function(err, columns) {
// end the waiter
self.emit('_endWaiting', 'mapping');
if (err) {
alert(err);
return;
}
// separators
var separators = {
',': 'COMMA',
';': 'SEMICOLON',
'\t': 'TAB',
' ': 'SPACE'
};
// set separator
columns.separator = separators[columns.separator];
// update options in UI
for (var op in columns) {
$('[data-option="' + op + '"]', self.dom).val(columns[op]);
}
self.columns = columns;
// remove all the files
self.$.fields.empty();
// build the options to be cloned later
var $options = $('<div>');
var firstLine = self.columns.lines[0];
// column translations
var COLUMN_TEXT = {
de : 'Spalte',
fr : 'Colonne',
it : 'Colonna'
}
for (var j = 0; j < firstLine.length; ++j) {
// build a new jQuery option element
var $option = $('<option>');
// and set its value to the field key
$option.attr('value', j);
// and the label
if (self.columns.hasHeaders) {
$option.text(COLUMN_TEXT[M.getLocale()] + ' ' + (j + 1) + (self.columns.headers[j] ? ' (' + self.columns.headers[j] + ')' : ''));
} else {
$option.text(COLUMN_TEXT[M.getLocale()] + ' ' + (j + 1) + (firstLine[j] ? ' (' + firstLine[j] + ')' : ''));
}
// and finally, push it
$options.append($option);
}
self.$.fieldOptions = $options.children();
callback(err);
});
}
function refreshTable () {
var self = this;
var data = [];
if (!jQuery.isEmptyObject(self.mappings) && self['import'].template) {
var lineTemplate = {};
var lines = self.columns.lines || [];
// if headers, ignore first line
// TODO add the headers option linked to the headers checkbox
for (var i = (self.headers ? 1 : 0); i < lines.length; ++i) {
var dataLine = {};
for (var fieldKey in self.mappings) {
if (!self.mappings.hasOwnProperty(fieldKey)) continue;
// we must buid real object now not a flat one
var splits = fieldKey.split('.');
var curObj = dataLine;
var j = 0;
for (; j < splits.length - 1; ++j) {
curObj[splits[j]] = curObj[splits[j]] || {};
curObj = curObj[splits[j]];
}
curObj[splits[j]] = self.columns.lines[i][self.mappings[fieldKey]];
}
// push the object to the result set
data.push(dataLine);
}
}
if (data) {
self.emit('result', null, data);
} else {
//TODO clear table
}
}
function startWaiting () {
var self = this;
// hide all the pages
for (var id in self.$.pages) {
self.$.pages[id].hide();
}
// show wwaiter if one available
if (self.$.waiter) {
self.$.waiter.show();
}
}
function endWaiting (pageId) {
var self = this;
// show wwaiter if one available
if (self.$.waiter) {
self.$.waiter.hide();
}
// show the wanted page
if (self.$.pages[pageId]) {
self.$.pages[pageId].show();
}
}
function reset () {
var self = this;
// remove the template selection
$(self.config['import'].ui.selectors.template, self.dom).val(null);
// hide mapping fields
$('.mapping-fields').hide();
// remove sample table content
// TODO Replace with a clear event emit that the table reacts to.
// The table should probably have 2 clears:
// - clearData
// - clearTemplate (which also clears the data)
// Here we will call then clearTemplate
$('.sample-table', self.dom).find('tbody, thead').empty();
// column data is cleaned up
self.columnData = {};
self.$.pages['mapping'].hide();
self.$.pages['inbox'].show();
// empty the fields
self.$.fields.empty();
// remove the last getColumns select options
self.$.options = $();
}
function gatherInfo () {
var self = this;
var info = {};
var schema = self['import'].template.schema;
info.path = self.columnData.path;
info.template = $(self.config['import'].ui.selectors.template).val();
info.separator = self.columnData.separator || self.columns.separator;
info.charset = self.columnData.charset || 'ascii';
info.headers = self.columnData.hasHeaders || false;
info.operation = self.operation;
info.mappings = self.mappings || {};
if (['delete', 'update'].indexOf(info.operation) !== -1) {
// both the update and the delete operations have a query key
info.key = $('[name=mapping]:checked').closest('.form-group').find('select.field-select').attr('name') || '';
// if the update option is selected get the mapping
if (info.operation === 'update') {
info.upsert = $('[name=upsert]:checked').length ? true : false;
var updateMappings = {};
var fields = $('.field-select');
for (var i = 0, l = fields.length; i < l; ++ i) {
var fieldVal = $(fields[i]).val();
if (fieldVal) {
var templateKey = $(fields[i]).attr('name');
if (schema[templateKey].type === 'number') {
var operator = $(fields[i]).closest('.form-group').find('div.operator>select').val();
updateMappings[templateKey] = { value: fieldVal, operator: operator};
} else {
updateMappings[templateKey] = { value: fieldVal };
}
}
}
info.mappings = updateMappings;
}
}
return info;
}