-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathspeciesFieldsSettings.js
581 lines (486 loc) · 20.1 KB
/
speciesFieldsSettings.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
/**
* Created by mol109 on 27/1/17.
*/
var SpeciesConstraintViewModel = function (o, fieldName) {
var self = this;
var defaultValues = {
type: 'ALL_SPECIES',
speciesDisplayFormat: 'SCIENTIFICNAME(COMMONNAME)',
commonNameField: 'commonName',
scientificNameField: 'matchedName'
};
o = $.extend(defaultValues, o);
self.type = ko.observable(o.type);
self.allSpeciesLists = new SpeciesListsViewModel();
self.singleSpecies = new SpeciesViewModel(o.singleSpecies || {}, fcConfig);
self.commonNameField = ko.observable(o.commonNameField);
self.scientificNameField = ko.observable(o.scientificNameField);
self.commonFields = ko.observableArray();
self.speciesLists = ko.observableArray();
self.speciesLists.subscribe(getCommonKeys);
self.newSpeciesLists = new NewSpeciesListViewModel();
self.speciesDisplayFormat = ko.observable(o.speciesDisplayFormat);
self.speciesOptions = [{id: 'ALL_SPECIES', name:'All species'},{id:'SINGLE_SPECIES', name:'Single species'}, {id:'GROUP_OF_SPECIES',name:'A selection or group of species'}];
self.speciesLists($.map(o.speciesLists ? o.speciesLists : [], function (obj, i) {
return new SpeciesList(obj);
}));
addDefaultCommonFields();
self.transients = {};
self.transients.bioProfileUrl = ko.computed(function () {
return fcConfig.bieUrl + '/species/' + self.singleSpecies.guid();
});
self.transients.inputSettingsTooltip = ko.computed(function () {
var type = self.type();
if(type === 'SINGLE_SPECIES') {
return 'Single species';
} else if(type === 'GROUP_OF_SPECIES') {
if(self.speciesLists().length > 0) {
var speciesListsTooltip = '<p>Lists</p>';
for(var i =0 ; i < self.speciesLists().length; i++ ) {
speciesListsTooltip += '<span class="pull-left text-left">' + self.speciesLists()[i].transients.truncatedListName() + '</span> <br/>\n';
}
speciesListsTooltip += '<br/>';
return speciesListsTooltip;
} else {
return "No lists configured yet";
}
} else {
return '';
}
});
self.transients.inputSettingsSummary = ko.computed(function () {
var type = self.type();
if(type === 'ALL_SPECIES'){
return 'All species';
} else if(type === 'SINGLE_SPECIES') {
return self.singleSpecies.name();
} else if(type === 'GROUP_OF_SPECIES') {
if(self.speciesLists().length > 0) {
var moreListsMessage = (self.speciesLists().length > 1) ? ' and ' + (self.speciesLists().length - 1) + ' more.' : '';
return 'List ' + self.speciesLists()[0].transients.truncatedListName() + moreListsMessage;
} else {
return "No lists configured yet"
}
} else if(type === 'DEFAULT_SPECIES'){
return 'Default species';
} else {
return 'Not configured';
}
});
self.transients.isValid = ko.computed(function () {
var type = self.type();
return !!type
});
self.transients.fieldName = ko.observable(fieldName);
self.transients.bioSearch = ko.observable(fcConfig.speciesSearchUrl);
self.transients.allowedListTypes = [
{id: 'SPECIES_CHARACTERS', name: 'Species characters'},
{id: 'CONSERVATION_LIST', name: 'Conservation species list'},
{id: 'SENSITIVE_LIST', name: 'Sensitive list'},
{id: 'LOCAL_LIST', name: 'Local checklist'},
{id: 'COMMON_TRAIT', name: 'Traits'},
{id: 'TEST', name: 'Testing List'}
];
self.transients.allowedLicences = [
{
"value": "CC0",
"label": "Creative Commons Zero"
},
{
"value": "CC-BY",
"label": "Creative Commons By Attribution"
},
{
"value": "CC-BY-NC",
"label": "Creative Commons By Attribution-Noncommercial"
},
{
"value": "CC-BY-NC-ND",
"label": "Creative Commons By Attribution-Noncommercial-Noderivatives"
},
{
"value": "CC-BY-NC-SA",
"label": "Creative Commons By Attribution-Noncommercial-Sharealike"
},
{
"value": "CC-BY-ND",
"label": "Creative Commons By Attribution-Noderivatives"
},
{
"value": "CC-BY-SA",
"label": "Creative Commons By Attribution-Sharealike"
}
]
self.transients.showAddSpeciesLists = ko.observable(false);
self.transients.showExistingSpeciesLists = ko.observable(false);
self.transients.toggleShowAddSpeciesLists = function () {
self.transients.showAddSpeciesLists(!self.transients.showAddSpeciesLists());
if (self.transients.showAddSpeciesLists()) {
self.transients.showExistingSpeciesLists(false);
}
};
self.transients.toggleShowExistingSpeciesLists = function () {
self.allSpeciesLists.transients.loading(true);
self.transients.showExistingSpeciesLists(!self.transients.showExistingSpeciesLists());
if (self.transients.showExistingSpeciesLists()) {
self.allSpeciesLists.setDefault();
self.transients.showAddSpeciesLists(false);
}
};
self.addSpeciesLists = function (list) {
if(!self.containsList(list)) {
self.speciesLists.push(list);
list.transients.check(true);
}
};
self.containsList = function(list) {
var result = false;
ko.utils.arrayForEach(self.speciesLists(), function(existingList) {
if(existingList.dataResourceUid() == list.dataResourceUid()) {
result = existingList;
}
});
return result;
}
self.removeSpeciesLists = function (list) {
list.transients.check(false);
self.speciesLists.remove(list);
};
self.allSpeciesInfoVisible = ko.computed(function () {
return (self.type() == "ALL_SPECIES");
});
self.groupInfoVisible = ko.computed(function () {
return (self.type() == "GROUP_OF_SPECIES");
});
self.singleInfoVisible = ko.computed(function () {
return (self.type() == "SINGLE_SPECIES");
});
self.type.subscribe(function (type) {
if (self.type() == "SINGLE_SPECIES") {
} else if (self.type() == "GROUP_OF_SPECIES") {
}
});
self.asJson = function () {
var jsData = {};
// Type specific parameters
if (self.type() == "SINGLE_SPECIES") {
jsData.singleSpecies = ko.mapping.toJS(self.singleSpecies, {ignore: ['transients']});
}
else if (self.type() == "GROUP_OF_SPECIES") {
jsData.speciesLists = ko.mapping.toJS(self.speciesLists, {ignore: ['listType', 'fullName', 'itemCount', 'description', 'listType', 'allSpecies', 'transients']});
jsData.commonNameField = self.commonNameField();
jsData.scientificNameField = self.scientificNameField();
}
// Only generate output for known types
if ($.inArray(self.type(), ["SINGLE_SPECIES", "GROUP_OF_SPECIES", "ALL_SPECIES", "DEFAULT_SPECIES"]) >-1) {
// Common parameters
jsData.type = self.type();
}
// Display format is independent of type and derivate type fields
jsData.speciesDisplayFormat = self.speciesDisplayFormat()
return jsData;
};
self.isValid = function(){
return ((self.type() == "ALL_SPECIES") || (self.type() == "SINGLE_SPECIES" && self.singleSpecies.guid()) ||
(self.type() == "GROUP_OF_SPECIES" && self.speciesLists().length > 0)) || (self.type() == "DEFAULT_SPECIES")
};
self.hasErrors = function() {
if(!self.type()) {
return "You must select an option from the list";
} else if(self.type() == "SINGLE_SPECIES" && !self.singleSpecies.guid()) {
return "You must type and select a species name"
} else if(self.type() == "GROUP_OF_SPECIES" && self.speciesLists().length == 0) {
return "You must either select existing species lists or create a new one"
}
}
self.saveNewSpeciesName = function () {
if (!$('#project-activities-species-validation').validationEngine('validate')) {
return;
}
var jsData = {};
jsData.listName = self.newSpeciesLists.listName();
jsData.listType = self.newSpeciesLists.listType();
jsData.licence = self.newSpeciesLists.licence();
jsData.description = self.newSpeciesLists.description();
jsData.listItems = "";
var lists = ko.mapping.toJS(self.newSpeciesLists, { 'ignore': ["transients"] });
$.each(lists.allSpecies, function (index, species) {
var UNMATCHED_TAXON = " (Unmatched taxon)";
var name = (species.guid) ? // Matched Taxon ?
species.name :
species.name.substr(0, species.name.indexOf(UNMATCHED_TAXON));
if (index == 0) {
jsData.listItems = name;
} else {
jsData.listItems = jsData.listItems + "," + name;
}
});
var model = JSON.stringify(jsData, function (key, value) {
return value === undefined ? "" : value;
});
var divId = 'species-dialog-alert-placeholder';
$("#addNewSpecies-status").show();
$.ajax({
url: fcConfig.addNewSpeciesListsUrl,
type: 'POST',
data: model,
contentType: 'application/json',
success: function (data) {
if (data.error) {
showAlert("Error :" + data.error, "alert-danger", divId);
}
else {
showAlert("Successfully added the new species list - " + self.newSpeciesLists.listName() + " (" + data.id + ")", "alert-success", divId);
self.newSpeciesLists.dataResourceUid(data.id);
self.speciesLists.push(new SpeciesList(ko.mapping.toJS(self.newSpeciesLists, { 'ignore': ["transients"] })));
self.newSpeciesLists = new NewSpeciesListViewModel();
self.transients.toggleShowAddSpeciesLists();
}
$("#addNewSpecies-status").hide();
},
error: function (data) {
showAlert("Error : An unhandled error occurred" + data.status, "alert-danger", divId);
$("#addNewSpecies-status").hide();
}
});
};
function getCommonKeys(){
var url = fcConfig.commonKeysUrl, druids = $.map(self.speciesLists(), function (list) {
return list.dataResourceUid();
});
if(druids && druids.length){
$.get(url,{
druid: druids.join(',')
}, function (fields) {
self.commonFields(fields);
}).fail(addDefaultCommonFields);
} else {
addDefaultCommonFields()
}
}
function addDefaultCommonFields() {
self.commonFields(fcConfig.defaultCommonFields);
}
};
var NewSpeciesListViewModel = function (o) {
var self = this;
if (!o) o = {};
self.listName = ko.observable(o.listName);
self.dataResourceUid = ko.observable(o.dataResourceUid);
self.description = ko.observable(o.description);
self.listType = ko.observable(o.listType);
self.licence = ko.observable(o.licence);
self.allSpecies = ko.observableArray();
self.inputSpeciesViewModel = new SpeciesViewModel({}, fcConfig);
self.inputSpeciesViewModel.transients.searchValue = ko.observable("");
self.inputSpeciesViewModel.transients.guid.subscribe(function (newName) {
var newSpecies = new SpeciesViewModel({}, fcConfig);
newSpecies.name(self.inputSpeciesViewModel.transients.name());
newSpecies.guid(self.inputSpeciesViewModel.transients.guid());
if(self.inputSpeciesViewModel.transients.guid()) {
newSpecies.transients.bieUrl(self.inputSpeciesViewModel.transients.bieUrl());
}
self.allSpecies.push(newSpecies);
self.clearSearchValue();
});
self.clearSearchValue = function () {
self.inputSpeciesViewModel.transients.searchValue("");
};
self.removeNewSpeciesName = function (species) {
self.allSpecies.remove(species);
};
self.transients = {};
self.transients.url = ko.observable(fcConfig.speciesListsServerUrl + "/" + o.dataResourceUid);
};
/**
* Creates a bootstrap modal from the supplied UI element to collect a species field configuration and returns a
* jquery Deferred promise to access it.
* @param speciesFieldConfigViewModel default model for the document. can be used to populate role, etc.
* @param templateSelector a selector identifying the element that calls the ko template and where data binding will be applied
* @returns an instance of jQuery.Deferred - the uploaded document will be supplied to a chained 'done' function.
*/
function showSpeciesFieldConfigInModal(speciesFieldConfigViewModel, templateSelector) {
var modalSelector = '#configureSpeciesFieldModal';
// Get the native object (index 0) rather than jquery wrapper, ko needs it.
var template = $(templateSelector)[0];
// Used to communicate the result back to the calling process.
var result = $.Deferred();
// Decorate the model so it can handle the button presses and close the modal window.
speciesFieldConfigViewModel.cancel = function() {
//TODO reject validation engine result
result.reject();
closeModal();
};
speciesFieldConfigViewModel.accept = function() {
var error = speciesFieldConfigViewModel.hasErrors();
$modal.find('form').validationEngine('validate');
if(!error){
result.resolve(speciesFieldConfigViewModel.asJson());
closeModal();
} else {
showAlert(error, 'alert-danger', 'species-dialog-alert-placeholder')
}
};
// Close the modal and tidy up the bindings.
var closeModal = function() {
$modal.modal('hide');
};
ko.applyBindings(speciesFieldConfigViewModel, template);
//Modal selector won't exist until ko 'instantiates' the template hence we wait for it before trying to
// get the element
var $modal = $(modalSelector);
// Don't allow ESC to close dialog, it will bypass the cancel function and hence mess the KO binding/unbinding
// mechanism
$modal.modal({
backdrop:'static',
keyboard: false
});
$modal.addClass("modal-open");
$("body").addClass("modal-open");
$modal.modal('show');
$modal.on('shown.bs.modal', function() {
$modal.find('form').validationEngine();
});
$modal.on('hidden.bs.modal', function(){
$modal.removeClass("modal-open");
$("body").removeClass("modal-open");
$modal.find('form').validationEngine('detach');
ko.cleanNode(template);
});
return result;
}
var SpeciesFieldViewModel = function (o) {
var self = this;
if (!o) o = {};
self.label = o.label || "";
self.dataFieldName = o.dataFieldName || "";
self.context = o.context || "";
self.output = o.output || "";
self.transients = {};
self.transients.fieldName = self.output + ' - ' + self.label;
self.config = ko.observable(new SpeciesConstraintViewModel(o.config));
self.asJson = function () {
var jsData = {};
jsData.label = self.label;
jsData.dataFieldName = self.dataFieldName;
jsData.context = self.context;
jsData.output = self.output;
jsData.config = self.config().asJson();
return jsData;
};
self.load = function (data) {
if (data) {
self.label = data.label;
self.dataFieldName = data.dataFieldName;
self.context = data.context;
self.output = data.output;
self.transients.fieldName = self.output + ' - ' + self.label;
self.config(new SpeciesConstraintViewModel(data.config));
}
};
};
var SpeciesListsViewModel = function (o) {
var self = this;
if (!o) o = {};
self.ascIconClass = "fas fa-sort-up";
self.descIconClass = "fas fa-sort-down";
self.searchGuid = ko.observable();
self.searchName = ko.observable();
self.pagination = new PaginationViewModel({}, self);
self.pagination.rppOptions = [10, 20, 30];
self.allSpeciesListsToSelect = ko.observableArray();
self.offset = ko.observable(0);
// self.max = ko.observable(100);
self.listCount = ko.observable();
self.transients = {};
self.transients.loading = ko.observable(false);
self.transients.sortCol = ko.observable("listName");
self.transients.sortOrder = ko.observable("asc");
self.sort = function(column, order) {
if (!self.transients.loading()) {
if (column == self.transients.sortCol()) {
//toggle the order
if (order == "asc") {
self.transients.sortOrder("desc");
} else {
self.transients.sortOrder("asc");
}
} else {
self.transients.sortCol(column)
self.transients.sortOrder("asc");
}
self.loadAllSpeciesLists(self.transients.sortCol(), self.transients.sortOrder())
}
}
self.loadAllSpeciesLists = function (sortCol, order) {
self.transients.loading(true);
var url = fcConfig.speciesListUrl + "?sort=" + sortCol + "&offset=" + self.offset() + "&max=" + self.pagination.resultsPerPage() + "&order=" + order;
if (self.searchGuid()) {
url += "&guid=" + self.searchGuid();
}
if (self.searchName() && self.searchName().trim() != ""){
url += "&searchTerm=" + self.searchName().trim();
}
var divId = 'project-activities-result-placeholder';
$.ajax({
url: url,
type: 'GET',
contentType: 'application/json',
beforeSend: function () {
self.transients.loading(true);
},
success: function (data) {
if (data.error) {
showAlert("Error :" + data.text, "alert-danger", divId);
}
else {
self.listCount(data.listCount);
self.allSpeciesListsToSelect($.map(data.lists ? data.lists : [], function (obj, i) {
return new SpeciesList(obj);
})
);
if (self.offset() == 0) {
self.pagination.loadPagination(0, data.listCount);
}
}
},
complete: function () {
self.transients.loading(false);
},
error: function (data) {
var status = data.status;
showAlert("Error : An unhandled error occurred" + data.status, "alert-danger", divId);
}
});
};
self.clearSearch = function() {
self.searchGuid(null);
self.searchName(null);
self.setDefault()
}
self.setDefault = function() {
self.transients.sortCol("listName");
self.transients.sortOrder("asc");
self.transients.loading(true);
self.refreshPage(0);
}
self.refreshPage = function(offset) {
self.offset( offset || 0);
self.loadAllSpeciesLists(self.transients.sortCol(), self.transients.sortOrder());
}
};
var SpeciesList = function (o) {
var self = this;
if (!o) o = {};
self.listName = ko.observable(o.listName);
self.dataResourceUid = ko.observable(o.dataResourceUid);
self.listType = ko.observable(o.listType);
self.fullName = ko.observable(o.fullName);
self.itemCount = ko.observable(o.itemCount);
self.transients = {};
self.transients.url = ko.observable(fcConfig.speciesListsServerUrl + "/" + o.dataResourceUid);
self.transients.check = ko.observable(false);
self.transients.truncatedListName = ko.computed(function () {
return truncate(self.listName(), 45);
});
};