Project

General

Profile

Download (22 KB) Statistics
| Branch: | Revision:

git_sitools_idoc / szcluster-db / workspace / client-user / js / components / forms / projectForm.js @ d16caf89

1
/***************************************
2
* Copyright 2010-2014 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
3
* 
4
* This file is part of SITools2.
5
* 
6
* SITools2 is free software: you can redistribute it and/or modify
7
* it under the terms of the GNU General Public License as published by
8
* the Free Software Foundation, either version 3 of the License, or
9
* (at your option) any later version.
10
* 
11
* SITools2 is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
* 
16
* You should have received a copy of the GNU General Public License
17
* along with SITools2.  If not, see <http://www.gnu.org/licenses/>.
18
***************************************/
19
/*global Ext, sitools, SITOOLS_DATE_FORMAT, SITOOLS_DEFAULT_IHM_DATE_FORMAT, i18n, userLogin, DEFAULT_WIN_HEIGHT, DEFAULT_WIN_WIDTH, getDesktop, projectGlobal, SitoolsDesk, DEFAULT_PREFERENCES_FOLDER, alertFailure*/
20
/*global loadUrl*/
21
/*
22
 * @include "formComponentsPanel.js"
23
 * @include "resultsProjectForm.js"
24
 */
25
Ext.namespace('sitools.user.component.forms');
26

    
27
/**
28
 * The global Panel. A panel with a formComponentsPanel and the buttons. 
29
 * @cfg {string} formId Id of the selected Form
30
 * @cfg {string} formName Name of the selected Form 
31
 * @cfg {Array} formParameters Array of all form Parameters
32
 * @cfg {number} formWidth Form Width 
33
 * @cfg {number} formHeight Form Height 
34
 * @cfg {string} formCss Name of a specific css class to apply to form 
35
 * @cfg {Array} properties An array of Properties. 
36
 * @cfg {string} urlServicePropertiesSearch The url to request properties
37
 * @cfg {string} urlServiceDatasetSearch the url to request for Multids Search
38
 * @cfg {string} dictionaryName the Name of the dictionary attached to the form
39
 * @class sitools.user.component.forms.projectForm
40
 * @extends Ext.Panel
41
 * @requires sitools.user.component.formComponentsPanel
42
 */
43
sitools.user.component.forms.projectForm = Ext.extend(Ext.Panel, {
44
    initComponent : function () {
45
        var config = this; 
46
        this.componentType = "formProject";
47
        
48
        var panelIdObject = {};
49
        
50
        // New Form model with zones
51
        if (!Ext.isEmpty(this.formZones)){
52
            Ext.each(this.formZones, function(formParam) { 
53
                var containerId = formParam.containerPanelId;
54
                if (Ext.isEmpty(panelIdObject[containerId])){
55
                    panelIdObject[containerId] = [];
56
                }
57
                panelIdObject[containerId].push(formParam);
58
            });
59
        } else { // old form model
60
            Ext.each(config.formParameters, function(formParam) { 
61
                var containerId = formParam.containerPanelId;
62
                if (Ext.isEmpty(panelIdObject[containerId])){
63
                    panelIdObject[containerId] = [];
64
                }
65
                panelIdObject[containerId].push(formParam);
66
            });
67
        }
68
        
69
        var items = [];
70
        var globalParams = {};
71
        
72
        Ext.iterate(panelIdObject, function(key, formParams){
73
            var componentList = new  sitools.user.component.formComponentsPanel({
74
                border: true,
75
                css : config.formCss, 
76
                formId : config.formId,
77
                id : key
78
            });
79

    
80
            if (!Ext.isEmpty(this.formZones)) {
81
                globalParams.formZones = formParams;
82
            } else {
83
                globalParams.oldParameters = formParams;
84
            }
85

    
86
//            componentList.datasetCm = config.dataset.columnModel;
87
            componentList.loadParameters(globalParams, config.dataUrl, "dataset");
88

    
89
            items.push(componentList);
90
        }, this);
91
        
92
        
93
        
94
        /**
95
         * The panel that displays all form components as defined by the administrator. 
96
         */
97
        this.zonesPanel = new Ext.Panel({
98
            width : config.formWidth,
99
            height : config.formHeight, 
100
            css : config.formCss, 
101
            formId : config.formId,
102
            items : [items]
103
        });
104
//        
105
//        if (!Ext.isEmpty(config.formParameters)) {
106
//            this.componentList.loadParameters(config.formParameters, config.dataUrl, "project");
107
//        }
108
    
109
        var displayComponentPanel = new Ext.Panel({
110
            title : i18n.get('label.formConcepts'), 
111
            region : "center", 
112
            flex : 2, 
113
            autoScroll : true,
114
            items : this.zonesPanel,
115
            layout : "absolute",
116
            listeners : {
117
                scope : this, 
118
                resize : function () {
119
                    if (!Ext.isEmpty(this.zonesPanel.getEl())) {
120
                        var cmpChildSize = this.zonesPanel.getSize();
121
                        var size = this.body.getSize();
122
                        var xpos = 0, ypos = 0;
123
                        if (size.height > cmpChildSize.height) {
124
                            ypos = (size.height - cmpChildSize.height) / 2;
125
                        }
126
                        if (size.width > cmpChildSize.width) {
127
                            xpos = (size.width - cmpChildSize.width) / 2;
128
                        }
129
                        this.zonesPanel.setPosition(xpos, ypos);
130
                        
131
                    }
132
                }
133
            }
134
        });
135
        
136
        /**
137
         * The panel that displays Property search
138
         * Each property adds a formField with the buildPropertyField method
139
         */
140
        this.propertyPanel = new Ext.form.FormPanel({
141
            title : i18n.get("label.defineProperties"), 
142
            padding : 10,
143
            labelWidth : 100, 
144
            flex : 2,
145
            autoScroll : true, 
146
            defaults : {
147
                labelSeparator : ""
148
            },
149
            buttons : [{
150
                text : i18n.get('label.refreshDatasets'), 
151
                scope : this, 
152
                handler : this.propertySearch
153
            }]
154
        });
155
        if (!Ext.isEmpty(this.properties)) {
156
            Ext.each(this.properties, function (prop) {
157
                var field = this.buildPropertyField(prop);
158
                this.propertyPanel.add(field);
159
            }, this);
160
        }
161
        
162
        var storeDatasets = new Ext.data.JsonStore({
163
            restful  : true, 
164
            fields : [{
165
                name : "id", 
166
                type : "string"
167
            }, {
168
                name : "name", 
169
                type : "string"
170
            }, {
171
                name : "visible", 
172
                type : "boolean"
173
            }], 
174
            url : projectGlobal.sitoolsAttachementForUsers + this.urlServicePropertiesSearch, 
175
            root : "collection.dataSets", 
176
            listeners : {
177
                load : function (store, recs) {
178
                    Ext.each(recs, function (rec) {
179
                        rec.set("visible", true);
180
                    });
181
                }
182
            }, 
183
            autoLoad : true
184
        });
185
        
186
        var visible = new Ext.grid.CheckColumn({
187
            header : i18n.get('headers.visible'),
188
            dataIndex : 'visible',
189
            width : 55
190
        });
191
        
192
        var cmDatasets = new Ext.grid.ColumnModel({
193
            columns : [ {
194
                header : i18n.get('headers.name'),
195
                dataIndex : 'name',
196
                width : 120
197
            }, visible]
198
        });
199
        
200
        var smDatasets = new Ext.grid.RowSelectionModel({
201
            singleSelect : true
202
        });
203
        
204
        /**
205
         * The dataset list. 
206
         * It is updated when user pressed on refresh dataset button.
207
         */
208
        this.datasetPanel = new Ext.grid.EditorGridPanel({
209
            title : i18n.get('label.defineDatasets'), 
210
            store : storeDatasets, 
211
            cm : cmDatasets, 
212
            sm : smDatasets, 
213
            flex : 1, 
214
            autoScroll : true, 
215
            viewConfig : {
216
                forceFit : true 
217
            }, 
218
            plugins : [visible]
219
        });
220
        
221
        var firstPanel = new Ext.Panel({
222
            height : 300, 
223
            items : [this.propertyPanel, this.datasetPanel], 
224
            layout : "hbox", 
225
            collapsedTitle : i18n.get('label.advancedSearch'),
226
            region : "north",
227
            collapsible : true, 
228
            collapsed : true, 
229
            flex : 2, 
230
            layoutConfig : {
231
                align : "stretch"   
232
            }
233
        });
234

    
235
//      ************************* Reset Form button ************************** //
236
        this.resetFormButton = new Ext.Button({
237
            text : 'Reset Form',
238
            scope : this,
239
            iconCls : 'x-btn-reset',
240
            handler : function () {
241
                var containers = this.find("stype", 'sitoolsFormContainer');
242
                Ext.each(containers, function (container) {
243
                        if(Ext.isFunction(container.resetToDefault)){
244
                        container.resetToDefault();
245
                        }
246
                }, this);
247
            }
248
        });
249
//      ********************************************************************** //
250

    
251
        /**
252
         * A simple button to launch the main request on each selected dataset. 
253
         */
254
        this.searchButton = new Ext.Button({
255
            text : i18n.get('label.search'),
256
            scope : this,
257
            iconCls : 'x-btn-search',
258
            handler : function (button) {
259
                this.onSearch(button);
260
            }
261
        });
262
        
263
        Ext.apply(this, {
264
            height : config.formHeight,
265
            layout : "border", 
266
            layoutConfig : {
267
                align : "stretch"
268
            },
269
            items : [ firstPanel, displayComponentPanel ],
270
            buttons : [this.resetFormButton, this.searchButton], //reset button
271
            listeners : {
272
                scope : this, 
273
                propertyChanged : function () {
274
                    var properties = this.propertyPanel.items.items;
275
                    var params = {};
276
                    var j = 0;
277
                    var k = {};
278
                    for (var i = 0; i < properties.length; i++) {
279
                        var prop = properties[i];
280
                        if (!Ext.isEmpty(prop.getAPIValue())) {
281
                            params["k[" + j + "]"] = prop.getAPIValue();
282
                            j++;
283
                        }
284
                    }
285
                    this.datasetPanel.getStore().load({
286
                        params : params
287
                    });
288
                }, 
289
                multiDsSearchDone : function () {
290
                    this.resetFormButton.setDisabled(false); //reset button
291
                    this.searchButton.setDisabled(false);
292
                }
293

    
294
            },            
295
            bbar : new Ext.ux.StatusBar({
296
                text : i18n.get('label.ready'),
297
                iconCls : 'x-status-valid',
298
                hidden : true
299
            })
300
        });
301
        sitools.user.component.forms.projectForm.superclass.initComponent.call(this);
302
    }, 
303
    /**
304
     * Build the query for the multiDs search
305
     * @param {Ext.Button} button The button that launch the request (to be disabled)
306
     * @returns
307
     */
308
    onSearch : function (button) {
309
        button.setDisabled(true);
310
        var containers = this.find("stype", 'sitoolsFormContainer');
311
        var formMultiDsParams = [];
312
        var glue = "";
313
        var i = 0;
314
        var datasets = [];
315
        this.datasetPanel.getStore().each(function (rec) {
316
            if (rec.get("visible")) {
317
                datasets.push(rec.get('id'));
318
            }
319
        });
320
        if (datasets.length <= 0) {
321
            Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.atLeastOneDataset'));
322
            button.setDisabled(false);
323
            return;
324
        }
325
        
326
        if (! Ext.isEmpty(this.nbDatasetsMax) && datasets.length > this.nbDatasetsMax) {          
327
            Ext.Msg.alert(i18n.get('label.error'), String.format(i18n.get('label.toManyDatasetsAllowed'), this.nbDatasetsMax));
328
            button.setDisabled(false);
329
            return;
330
        }
331
        var valid = true;
332
        
333
        this.zonesPanel.items.each(function(componentList){
334
            valid = valid && componentList.isComponentsValid();            
335
        },this);
336
        
337
        if (!valid) {
338
            this.getBottomToolbar().setStatus({
339
                text : i18n.get('label.checkformvalue'),
340
                iconCls : 'x-status-error'
341
            });
342
            this.getBottomToolbar().setVisible(true);    
343
            button.setDisabled(false);
344
            return;
345
        } else {
346
            this.getBottomToolbar().setVisible(false);
347
        }
348
        
349
        Ext.each(containers, function (container) {
350
            // var f = form.getForm();
351

    
352
            if (Ext.isFunction(container.getParameterValue)) {
353
                var param = container.getParameterValue();
354
                
355
                if (!Ext.isEmpty(param)) {
356
                    formMultiDsParams.push(this.paramValueToApi(param));
357
                }
358
            }
359
        }, this);
360
        
361
        var urlService = projectGlobal.sitoolsAttachementForUsers + this.urlServiceDatasetSearch;
362
        
363
        var params = {};
364
        params.datasetsList = datasets.join("|");
365

    
366
        i = 0;
367
        
368
        if (!Ext.isEmpty(formMultiDsParams)) {
369
            Ext.each(formMultiDsParams, function (param) {
370
                params["c[" + i + "]"] = param;
371
                i += 1;
372
            }, this);
373
        }
374

    
375
        //Launch the first POST Request on service: 
376
        Ext.Ajax.request({
377
            method : "POST", 
378
            params : params, 
379
            //Just to be sure that params are passed with the url request
380
            jsonData : {}, 
381
            scope : this, 
382
            url : urlService, 
383
            success : function (response) {
384
                try {
385
                    var json = Ext.decode(response.responseText);
386
                    if (! json.success) {
387
                        Ext.Msg.alert(i18n.get('label.error'), json.message);
388
                        return;
389
                    }
390
                    var jsObj = SitoolsDesk.navProfile.multiDataset.getObjectResults();
391
                    var componentCfg = {
392
                        urlTask : json.TaskModel.statusUrl,
393
                        formId : this.formId,
394
                        formMultiDsParams : formMultiDsParams,
395
                        datasets : datasets, 
396
                        formName : this.formName, 
397
                        callerId : this.id
398
                    };
399

    
400
                    var windowConfig = {
401
                        id : "windMultiDsResultForm" + this.formId, 
402
                        title : i18n.get('label.MultiDsResultForm') + " : " + this.formName, 
403
                        saveToolbar : false, 
404
                        iconCls : "dataviews"
405
                    };
406
                    SitoolsDesk.addDesktopWindow(windowConfig, componentCfg, jsObj);
407
                    
408
                }
409
                catch (err) {
410
                    Ext.Msg.alert(i18n.get('label.error'), err);
411
                    return;
412
                }
413
            }, 
414
                
415
            failure : alertFailure
416
        });
417
        var desktop = getDesktop();
418
        var win = desktop.getWindow("windMultiDsResultForm" + this.formId);
419
        if (win) {
420
            win.close();
421
        }
422

    
423
    },
424
    /**
425
     * A method to save all the window settings to be abble to reload it when desktop is reloaded. 
426
     * @return {}
427
     */
428
    _getSettings : function () {
429
        return {
430
            objectName : "projectForm", 
431
                formId : this.formId,
432
            formName : this.formName,
433
            formParameters : this.formParameters,
434
            formWidth : this.formWidth,
435
            formHeight : this.formHeight, 
436
            formCss : this.formCss, 
437
            properties : this.properties, 
438
            urlServicePropertiesSearch : this.urlServicePropertiesSearch, 
439
            urlServiceDatasetSearch : this.urlServiceDatasetSearch, 
440
            componentType : this.componentType, 
441
            dictionaryName : this.dictionaryName,
442
            preferencesPath : this.preferencesPath, 
443
            preferencesFileName : this.preferencesFileName,
444
            formZones : this.zones
445
            
446
        };
447
    }, 
448
    /**
449
     * Build a string using a form param Value. 
450
     * @param {} paramValue An object with attributes : at least type, code, value and optionnal userDimension, userUnit
451
     * @return {string} something like "TEXTFIELD|ColumnAlias|value"
452
     */
453
    paramValueToApi : function (paramValue) {
454
        var stringParam = paramValue.type + "|" + this.dictionaryName + "," + paramValue.code + "|" + paramValue.value;
455
        if (!Ext.isEmpty(paramValue.userDimension) && !Ext.isEmpty(paramValue.userUnit)) {
456
            stringParam += "|" + paramValue.userDimension + "|" + paramValue.userUnit.unitName; 
457
        }  
458
        return stringParam;
459
    }, 
460

    
461
//  ******** Reset Form Button *********//
462
    getResetFormButton : function () {
463
        return this.resetFormButton;
464
    },
465
//  ************************************//
466

    
467
    /**
468
     * Returns the search Button. 
469
     * @return {}
470
     */
471
    getSearchButton : function () {
472
        return this.searchButton;
473
    }, 
474
   
475
    /**
476
     * Build for a properties a new formField depending on property type. 
477
     * The property type could be one of : 
478
     *  - TEXTFIELD, 
479
     *  - NUMERIC_FIELD, 
480
     *  - NUMERIC_BETWEEN, 
481
     *  - DATE_BETWEEN
482
     * @param {} prop the Json definition of a property. 
483
     * @return {Ext.form.Field} a simple or composite field. 
484
     */
485
    buildPropertyField : function (prop) {
486
        var field;
487
        switch (prop.type) {
488
        case "TEXTFIELD" : 
489
            field = {
490
                xtype : "textfield", 
491
                name : prop.name, 
492
                anchor : '98%', 
493
                enableKeyEvents : true, 
494
                fieldLabel : prop.name, 
495
                getAPIValue : function () {
496
                    if (Ext.isEmpty(this.getValue())) {
497
                        return null;
498
                    }
499
                    return String.format("{0}|{1}|{2}", prop.type, prop.name, this.getValue());
500
                }
501
            };          
502
            break;
503
        case "NUMBER_FIELD" : 
504
            field = {
505
                xtype : "numberfield", 
506
                name : prop.name, 
507
                anchor : '98%', 
508
                enableKeyEvents : true, 
509
                fieldLabel : prop.name, 
510
                getAPIValue : function () {
511
                    if (Ext.isEmpty(this.getValue())) {
512
                        return null;
513
                    }
514
                    return String.format("{0}|{1}|{2}", prop.type, prop.name, this.getValue());
515
                }
516
            };          
517
            break;
518
        case "NUMERIC_BETWEEN" : 
519
            field = {
520
                xtype: 'compositefield',
521
                defaults: {
522
                    flex: 1
523
                },
524
                msgTarget: 'under',
525
                anchor : '98%', 
526
                items: [
527
                    {
528
                        xtype: 'numberfield',
529
                        name : prop.name + "deb", 
530
                        enableKeyEvents : true
531
                    },
532
                    {
533
                        xtype: 'numberfield',
534
                        name : prop.name + "fin"
535
                
536
                    }
537
                ],
538
                fieldLabel : prop.name, 
539
                getAPIValue : function () {
540
                    var deb = this.items.itemAt(0).getValue();
541
                    var fin = this.items.itemAt(1).getValue();
542
                    if (Ext.isEmpty(deb) || Ext.isEmpty(fin)) {
543
                        return null;
544
                    }
545
                    return String.format("{0}|{1}|{2}|{3}", prop.type, prop.name, deb, fin);
546
                }
547
            };          
548
            break;
549
        case "DATE_BETWEEN" : 
550
            field = {
551
                xtype: 'compositefield',
552
                defaults: {
553
                    flex: 1
554
                },
555
                msgTarget: 'under',
556
                anchor : '98%', 
557
                items: [
558
                    {
559
                        xtype: 'datefield',
560
                        name : prop.name + "deb", 
561
                        enableKeyEvents : true, 
562
                        format : SITOOLS_DEFAULT_IHM_DATE_FORMAT, 
563
                        showTime : true
564
                    },
565
                    {
566
                        xtype: 'datefield',
567
                        name : prop.name + "fin", 
568
                        format : SITOOLS_DEFAULT_IHM_DATE_FORMAT, 
569
                        showTime : true
570
                
571
                    }
572
                ],
573
                fieldLabel : prop.name, 
574
                getAPIValue : function () {
575
                    var deb, fin;
576
                    try {
577
                        deb = this.items.itemAt(0).getValue().format(SITOOLS_DATE_FORMAT);
578
                        fin = this.items.itemAt(1).getValue().format(SITOOLS_DATE_FORMAT);
579
                    
580
                    }
581
                    catch (err) {
582
                        return null;
583
                    }
584
                    if (Ext.isEmpty(deb) || Ext.isEmpty(fin)) {
585
                        return null;
586
                    }
587
                    return String.format("{0}|{1}|{2}|{3}", prop.type, prop.name, deb, fin);
588
                }
589
            };          
590
            break;
591
        }
592
        return field;
593
    }, 
594
    /**
595
     * Method called when user pressed on refresh Datasets button. 
596
     * Course properties and creates the parameters of the query to search the list of datasets
597
     */
598
    propertySearch : function () {
599
        var properties = this.propertyPanel.items.items;
600
        var params = {};
601
        var j = 0;
602
        var k = {};
603
        for (var i = 0; i < properties.length; i++) {
604
            var prop = properties[i];
605
            if (!Ext.isEmpty(prop.getAPIValue())) {
606
                params["k[" + j + "]"] = prop.getAPIValue();
607
                j++;
608
            }
609
        }
610
        this.datasetPanel.getStore().load({
611
            params : params
612
        });
613
        this.datasetPanel.getView().refresh();
614
    }
615
    
616
});
617