dustin@975: /* Copyright (C) 2013 by Bundesamt fuer Strahlenschutz
dustin@975:  * Software engineering by Intevation GmbH
dustin@975:  *
dustin@975:  * This file is Free Software under the GNU GPL (v>=3)
dustin@975:  * and comes with ABSOLUTELY NO WARRANTY! Check out
dustin@975:  * the documentation coming with IMIS-Labordaten-Application for details.
dustin@975:  */
dustin@975: 
dustin@975: /**
dustin@975:  * Controller for the ProbeList result grid.
dustin@975:  */
dustin@975: Ext.define('Lada.controller.grid.ProbeList', {
dustin@975:     extend: 'Ext.app.Controller',
dustin@975:     requires: [
tom@1227:         'Lada.view.window.FileUpload',
dustin@975:         'Lada.view.window.ProbeEdit',
dustin@975:         'Lada.view.window.GenProbenFromMessprogramm'
dustin@975:     ],
dustin@975: 
dustin@975:     /**
dustin@975:      * Initialize the Controller with listeners
dustin@975:      */
dustin@975:     init: function() {
dustin@975:         this.control({
dustin@975:             'probelistgrid': {
dustin@977:                 itemdblclick: this.editItem,
dustin@977:                 select: this.activateButtons,
dustin@977:                 deselect: this.deactivateButtons
dustin@975:             },
dustin@975:             'probelistgrid toolbar button[action=addProbe]': {
dustin@975:                 click: this.addProbeItem
dustin@975:             },
dustin@975:             'probelistgrid toolbar button[action=import]': {
dustin@975:                 click: this.uploadFile
dustin@975:             },
dustin@975:             'probelistgrid toolbar button[action=export]': {
dustin@975:                 click: this.downloadFile
dustin@975:             },
dustin@1244:             'probelistgrid toolbar button[action=printSheet]': {
dustin@1244:                 click: {
dustin@1244:                     fn: this.printSelection,
dustin@1244:                     mode: 'printsheet'
dustin@1244:                 }
dustin@1244:             },
dustin@1244:             'probelistgrid toolbar button[action=printExtract]': {
dustin@1244:                 click: {
dustin@1244:                     fn: this.printSelection,
dustin@1244:                     mode: 'printextract'
dustin@1244:                 }
raimund@1111:             },
raimund@1111:             'probelistgrid gridview': {
raimund@1111:                 expandbody: this.expandBody,
raimund@1111:                 collapsebody: this.collapseBody
dustin@975:             }
dustin@975:         });
dustin@975:         this.callParent(arguments);
dustin@975:     },
dustin@975: 
dustin@975:     /**
dustin@975:      * This function is called after a Row in the
dustin@975:      * {@link Lada.view.grid.ProbeList}
dustin@975:      * was double-clicked.
dustin@975:      * The function opens a {@link Lada.view.window.ProbeEdit}
dustin@975:      * or a {@link Lada.view.window.Messprogramm}.
dustin@975:      * To determine which window has to be opened, the function
dustin@975:      * analyse the records modelname.
dustin@975:      */
dustin@975:     editItem: function(grid, record) {
dustin@975:         var winname = 'Lada.view.window.ProbeEdit';
dustin@975: 
dustin@975:         var win = Ext.create(winname, {
dustin@975:             record: record,
dustin@975:             style: 'z-index: -1;' //Fixes an Issue where windows could not be created in IE8
dustin@975:         });
ehuber@1164:         win.setPosition(30);
dustin@975:         win.show();
dustin@975:         win.initData();
dustin@975:     },
dustin@975: 
dustin@975:     /**
dustin@975:      * This function opens a new window to create a Probe
dustin@975:      * {@link Lada.view.window.ProbeCreate}
dustin@975:      */
dustin@975:     addProbeItem: function() {
dustin@975:         var win = Ext.create('Lada.view.window.ProbeCreate');
dustin@975:         win.show();
dustin@975:         win.initData();
dustin@975:     },
dustin@975: 
dustin@975:     /**
dustin@975:      * This function opens a {@link Lada.view.window.FileUpload}
dustin@975:      * window to upload a LAF-File
dustin@975:      */
dustin@975:     uploadFile: function() {
dustin@975:         var win = Ext.create('Lada.view.window.FileUpload', {
dustin@975:             title: 'Datenimport',
dustin@975:             modal: true
dustin@975:         });
dustin@975: 
dustin@975:         win.show();
dustin@975:     },
dustin@975: 
dustin@975:     /**
dustin@975:      * This function can be used to Download the items which
dustin@975:      * were selected in the {@link Lada.view.grid.ProbeList}
dustin@975:      * The Download does not work with Internet Explorers older than v.10
dustin@975:      */
dustin@975:     downloadFile: function(button) {
dustin@975:         var grid = button.up('grid');
dustin@975:         var selection = grid.getView().getSelectionModel().getSelection();
dustin@975:         var i18n = Lada.getApplication().bundle;
dustin@975:         var proben = [];
dustin@975:         for (var i = 0; i < selection.length; i++) {
dustin@975:             proben.push(selection[i].get('id'));
dustin@975:         }
dustin@975:         var me = this;
dustin@975:         Ext.Ajax.request({
dustin@999:             url: 'lada-server/data/export/laf',
dustin@975:             jsonData: {'proben': proben},
raimund@1246:             timeout: 2 * 60 * 1000,
dustin@975:             success: function(response) {
dustin@975:                 var content = response.responseText;
dustin@975:                 var blob = new Blob([content],{type: 'text/plain'});
dustin@975:                 saveAs(blob, 'export.laf');
dustin@975:             },
dustin@975:             failure: function(response) {
dustin@975:                 /*
dustin@975:                 SSO will send a 302 if the Client is not authenticated
dustin@975:                 unfortunately this seems to be filtered by the browser.
dustin@975:                 We assume that a 302 was send when the follwing statement
dustin@975:                 is true.
dustin@975:                 */
dustin@975:                 if (response.status == 0 && response.responseText === "") {
dustin@975:                     Ext.MessageBox.confirm('Erneutes Login erforderlich',
dustin@975:                         'Ihre Session ist abgelaufen.<br/>'+
dustin@975:                         'Für ein erneutes Login muss die Anwendung neu geladen werden.<br/>' +
dustin@975:                         'Alle ungesicherten Daten gehen dabei verloren.<br/>' +
dustin@975:                         'Soll die Anwendung jetzt neu geladen werden?', this.reload);
dustin@975:                 } else {
tom@1256:                     // further error handling
dustin@975:                     Ext.Msg.alert(i18n.getMsg('err.msg.generic.title'),
dustin@975:                     i18n.getMsg('err.msg.laf.filecreatefailed'));
dustin@975:                 }
dustin@975:             }
dustin@975:         });
dustin@975:     },
dustin@975: 
dustin@975:     /**
dustin@975:      * Send the selection to a Printservice
dustin@975:      */
dustin@1244:     printSelection: function(button, e, eOpts) {
dustin@1244:         switch (eOpts.mode) {
dustin@1244:             case "printextract" :
dustin@1244:                 var printData = this.createExtractData(button);
dustin@1244:                 this.printpdf(printData, 'lada_print', 'lada-print.pdf', button);
dustin@1244:                 break;
dustin@1244:             case "printsheet" :
dustin@1244:                 // The Data is loaded from the server again, so we need
dustin@1244:                 // to be a little bit asynchronous here...
dustin@1244:                 callback = function(response) {
dustin@1244:                     var data = response.responseText;
dustin@1261:                     data = this.prepareData(data); // Wraps all messstellen and deskriptoren objects into an array
dustin@1244:                     var printData = '{"layout": "A4 portrait", "outputFormat": "pdf",'
dustin@1244:                             +   '"attributes": { "proben": ' +  data
dustin@1244:                             +   '}}';
dustin@1244:                     this.printpdf(printData, 'lada_erfassungsbogen',
dustin@1244:                                   'lada-erfassungsbogen.pdf', button);
dustin@1244:                 }
dustin@975: 
dustin@1244:                 this.createSheetData(button, callback, this);
dustin@1244:                 break;
dustin@1244:         }
dustin@1244:     },
dustin@1244: 
dustin@1261:     prepareData: function(data) {
dustin@1261:         // Copy data
dustin@1261:         prep = JSON.parse(data);
dustin@1261:         data = JSON.parse(data);
dustin@1261:         // ensure data and prep are equal, not sure
dustin@1261:         // if json.parse changes order of things
dustin@1262: 
dustin@1262:         emptyMessstelle = {
dustin@1262:             "id": null,
dustin@1262:             "amtskennung": null,
dustin@1262:             "beschreibung": null,
dustin@1262:             "messStelle": null,
dustin@1262:             "mstTyp": null,
dustin@1262:             "netzbetreiberId":null
dustin@1262:         };
dustin@1262: 
dustin@1262:         emptyDeskriptor = {
dustin@1262:             "s0":  null,
dustin@1262:             "s1":  null,
dustin@1262:             "s2":  null,
dustin@1262:             "s3":  null,
dustin@1262:             "s4":  null,
dustin@1262:             "s5":  null,
dustin@1262:             "s6":  null,
dustin@1262:             "s7":  null,
dustin@1262:             "s8":  null,
dustin@1262:             "s9":  null,
dustin@1262:             "s10": null,
dustin@1262:             "s11": null
dustin@1262:         };
dustin@1262: 
dustin@1266:         for (var i in data) {
dustin@1261:             probe = data[i];
dustin@1261:             deskriptoren = probe.deskriptoren;
dustin@1261:             messstelle = probe.messstelle;
dustin@1267:             labormessstelle = probe.labormessstelle;
dustin@1266:             ortszuordnung = probe.ortszuordnung;
dustin@1272:             zusatzwerte = probe.zusatzwerte;
dustin@1266: 
dustin@1262:             if (messstelle != null) {
dustin@1262:                 prep[i].messstelle = [];
dustin@1262:                 prep[i].messstelle[0] = messstelle;
dustin@1267:                 prep[i]['messstelle.messStelle'] = messstelle.messStelle;
dustin@1262:             }
dustin@1262:             else {
dustin@1262:                 prep[i].messstelle = [];
dustin@1262:                 prep[i].messstelle[0] = emptyMessstelle;
dustin@1267:                 prep[i]['messstelle.messStelle'] = '';
dustin@1267:             }
dustin@1267: 
dustin@1267:             if (labormessstelle != null) {
dustin@1267:                 prep[i]['labormessstelle.messStelle'] = labormessstelle.messStelle;
dustin@1267:             }
dustin@1267:             else {
dustin@1267:                 prep[i]['labormessstelle.messStelle'] = '';
dustin@1262:             }
dustin@1262: 
dustin@1262:             if (deskriptoren != null) {
dustin@1262:                 prep[i].deskriptoren = [];
dustin@1262:                 prep[i].deskriptoren[0] = deskriptoren;
dustin@1262:             }
dustin@1262:             else {
dustin@1262:                 prep[i].deskriptoren = [];
dustin@1262:                 prep[i].deskriptoren[0] = emptyDeskriptor;
dustin@1262:             }
dustin@1266: 
dustin@1272:             // See: app/view/grid/Probenzusatzwert.js
dustin@1272:             // Calculate NWG < symbol , as this is NOT done by the server
dustin@1272:             for (z in zusatzwerte){
dustin@1272:                 var nwg = zusatzwerte[z]['nwgZuMesswert'];
dustin@1272:                 var mw = zusatzwerte[z]['messwertPzs'];
dustin@1272:                 if ( mw < nwg) {
dustin@1272:                     prep[i].zusatzwerte[z]['messwertNwg'] = '<';
dustin@1272:                 }
dustin@1272:                 else {
dustin@1272:                     prep[i].zusatzwerte[z]['messwertNwg'] = null;
dustin@1272:                 }
dustin@1272:             }
dustin@1266: 
dustin@1266:             // Flatten the Ortszuodnung Array
dustin@1266:             for (var o in ortszuordnung) {
dustin@1266:                 oz = ortszuordnung[o];
dustin@1266:                 for (var e in oz.ort) {
dustin@1266:                     prep[i].ortszuordnung[o]['ort']=null;
dustin@1266:                     prep[i].ortszuordnung[o]['ort.'+e]=oz.ort[e];
dustin@1266:                 }
dustin@1266:             }
dustin@1261:         }
dustin@1266: 
dustin@1261:         return JSON.stringify(prep);
dustin@1261:     },
dustin@1261: 
dustin@1244:     /**
dustin@1244:      * Toggles the buttons in the toolbar
dustin@1244:      **/
dustin@1244:     activateButtons: function(rowModel, record) {
dustin@1244:         var grid = rowModel.view.up('grid');
dustin@1244:         this.buttonToggle(true, grid);
dustin@1244:     },
dustin@1244: 
dustin@1244:     /**
dustin@1244:      * Toggles the buttons in the toolbar
dustin@1244:      **/
dustin@1244:     deactivateButtons: function(rowModel, record) {
dustin@1244:         var grid = rowModel.view.up('grid');
dustin@1244:         // Only disable buttons when nothing is selected
dustin@1244:         if (rowModel.selected.items == 0) {
dustin@1244:             this.buttonToggle(false, grid);
dustin@1244:         }
dustin@1244:     },
dustin@1244: 
dustin@1244:     /**
dustin@1244:      * Enables/Disables a set of buttons
dustin@1244:      **/
dustin@1244:     buttonToggle: function(enabled, grid) {
dustin@1244:         if (!enabled) {
dustin@1244:             grid.down('button[action=export]').disable();
dustin@1244:             grid.down('button[action=printExtract]').disable();
dustin@1244:             grid.down('button[action=printSheet]').disable();
dustin@1244:         }
dustin@1244:         else {
dustin@1244:             grid.down('button[action=export]').enable();
dustin@1244:             grid.down('button[action=printExtract]').enable();
dustin@1244:             grid.down('button[action=printSheet]').enable();
dustin@1244:         }
dustin@1244:     },
dustin@1244: 
dustin@1244:     reload: function(btn) {
dustin@1244:         if (btn === 'yes') {
dustin@1244:             location.reload();
dustin@1244:         }
dustin@1244:     },
dustin@1244: 
dustin@1244:     expandBody: function(rowNode, record, expandRow) {
dustin@1244: //        var row = Ext.get('probe-row-' + record.get('id'));
dustin@1244: //        var messungGrid = Ext.create('Lada.view.grid.Messung', {
dustin@1244: //            recordId: record.get('id'),
dustin@1244: //            bottomBar: false,
dustin@1244: //            rowLines: true
dustin@1244: //        });
dustin@1244: //        row.swallowEvent(['click', 'mousedown', 'mouseup', 'dblclick'], true);
dustin@1244: //        messungGrid.render(row);
dustin@1244:     },
dustin@1244: 
dustin@1244:     collapseBody: function(rowNode, record, expandRow) {
dustin@1244: //        var element = Ext.get('probe-row-' + record.get('id')).down('div');
dustin@1244: //        element.destroy();
dustin@1244:     },
dustin@1244: 
dustin@1244:     /**
dustin@1262:      * Returns a Json-Object which contains the data which has
dustin@1244:      * to be printed.
dustin@1244:      * The parameter printFunctionCallback will be called once the ajax-request
dustin@1244:      * starting the json-export was evaluated
dustin@1244:      **/
dustin@1244:     createSheetData: function(button, printFunctionCallback, cbscope){
dustin@1244:         //disable Button and setLoading...
dustin@1262:         button.disable();
dustin@1262:         button.setLoading(true);
dustin@1244: 
dustin@1244: 
dustin@1244:         // get Selected Items.
dustin@1244:         var grid = button.up('grid');
dustin@1244:         var selection = grid.getView().getSelectionModel().getSelection();
dustin@1244:         var i18n = Lada.getApplication().bundle;
dustin@1244:         var me = this;
dustin@1244:         var ids = [];
dustin@1244: 
dustin@1244:         for (item in selection) {
dustin@1244:             ids.push(selection[item].data['id']);
dustin@1244:         }
dustin@1244: 
dustin@1244:         //basically, thats the same as the downloadFile
dustin@1244:         // code does.
dustin@1244:         var data = '{ "proben": ['+ids.toString()+'] }';
dustin@1244: 
dustin@1244:         Ext.Ajax.request({
dustin@1244:             url: 'lada-server/data/export/json',
dustin@1244:             jsonData: data,
dustin@1244:             binary: false,
dustin@1244:             scope: cbscope,
dustin@1244:             success: printFunctionCallback,
dustin@1244:             failure: function(response) {
dustin@1244:                 console.log('failure');
dustin@1244:                 // Error handling
dustin@1244:                 button.enable();
dustin@1244:                 button.setLoading(false);
dustin@1262:                 if (response.responseText) {
dustin@1262:                     try {
dustin@1262:                         var json = Ext.JSON.decode(response.responseText);
dustin@1262:                     }
dustin@1262:                     catch(e){
dustin@1262:                         console.log(e);
dustin@1262:                     }
dustin@1244:                 }
dustin@1244:                 if (json) {
dustin@1244:                     if(json.errors.totalCount > 0 || json.warnings.totalCount > 0){
dustin@1244:                         formPanel.setMessages(json.errors, json.warnings);
dustin@1244:                     }
dustin@1244:                     if(json.message){
dustin@1244:                         Ext.Msg.alert(Lada.getApplication().bundle.getMsg('err.msg.generic.title')
dustin@1244:                             +' #'+json.message,
dustin@1244:                             Lada.getApplication().bundle.getMsg(json.message));
dustin@1244:                     } else {
dustin@1244:                         Ext.Msg.alert(i18n.getMsg('err.msg.generic.title'),
dustin@1262:                             i18n.getMsg('err.msg.response.body'));
dustin@1244:                     }
dustin@1244:                 } else {
dustin@1244:                     Ext.Msg.alert(i18n.getMsg('err.msg.generic.title'),
dustin@1262:                     i18n.getMsg('err.msg.response.body'));
dustin@1244:                 }
dustin@1244:                 return null;
dustin@1244:             }
dustin@1244:         });
dustin@1244:     },
dustin@1244: 
dustin@1244:     /**
dustin@1262:      * Returns a Json-Object which contains the data which has
dustin@1244:      * to be printed.
dustin@1244:      **/
dustin@1244:     createExtractData: function(button){
dustin@975:         //disable Button and setLoading...
dustin@975:         button.disable();
dustin@975:         button.setLoading(true);
dustin@975: 
dustin@975:         var grid = button.up('grid');
dustin@975:         var selection = grid.getView().getSelectionModel().getSelection();
dustin@975:         var i18n = Lada.getApplication().bundle;
dustin@975:         var me = this;
dustin@975:         var columns = [];
dustin@975:         var columnNames = [];
dustin@975:         var visibleColumns = [];
dustin@975:         var displayName = '';
dustin@975:         var data = [];
dustin@975: 
dustin@975:         // Write the columns to an array
dustin@975:         try {
dustin@975:             for (key in selection[0].data) {
dustin@975:                 // Do not write owner or readonly or id
raimund@1082:                 if (["owner", "readonly", "id", "probeId"].indexOf(key) == -1){
dustin@975:                     columns.push(key);
dustin@975:                 }
dustin@975:             }
dustin@975:         }
dustin@975:         catch (e) {
dustin@975:             console.log(e);
dustin@975:         }
dustin@975: 
dustin@975:         //Retrieve visible columns' id's and names.
dustin@975:         // and set displayName
dustin@975:         try {
dustin@975:             var grid = button.up('grid');
dustin@975:             var cman = grid.columnManager;
dustin@975:             var cols = cman.getColumns();
dustin@975: 
dustin@975:             displayName = grid.down('tbtext').text;
dustin@975: 
dustin@975:             for (key in cols) {
dustin@975:                 if (cols[key].dataIndex) {
dustin@975:                     visibleColumns[cols[key].dataIndex] = cols[key].text;
dustin@975:                 }
dustin@975:             }
dustin@975:         }
dustin@975:         catch (e) {
dustin@975:             console.log(e);
dustin@975:         }
dustin@975: 
dustin@975: 
dustin@975:         // Retrieve Data from selection
dustin@975:         try {
dustin@975:             for (item in selection) {
dustin@975:                 var row = selection[item].data;
dustin@975:                 var out = [];
dustin@975:                 //Lookup every column and write to data array.
dustin@975:                 for (key in columns){
dustin@975:                     var attr = columns[key];
dustin@975:                     //Only write data to output when the column is not hidden.
dustin@975:                     if (row[attr] != null &&
dustin@975:                         visibleColumns[attr] != null) {
dustin@975:                         out.push(row[attr].toString());
dustin@975:                     }
dustin@975:                     else if (visibleColumns[attr] != null) {
dustin@975:                         out.push('');
dustin@975:                     }
dustin@975:                 }
dustin@975:                 data.push(out);
dustin@975:             }
dustin@975:         }
dustin@975:         catch (e){
dustin@975:             console.log(e);
dustin@975:         }
dustin@975: 
dustin@975:         //Retrieve the names of the columns.
dustin@975:         try {
dustin@975:             var grid = button.up('grid');
dustin@975:             var cman = grid.columnManager;
dustin@975:             var cols = cman.getColumns();
dustin@975:             //Iterate columns and find column names for the key...
dustin@975:             // This WILL run into bad behaviour when column-keys exist twice.
dustin@975:             for (key in columns){
dustin@975:                 for (k in cols){
dustin@975:                     if (cols[k].dataIndex == columns[key]){
dustin@975:                         columnNames.push(cols[k].text);
dustin@975:                         break;
dustin@975:                     }
dustin@975:                 }
dustin@975:             }
dustin@975:         }
dustin@975:         catch (e) {
dustin@975:             console.log(e);
dustin@975:         }
dustin@975: 
dustin@975:         var printData = {
dustin@975:             'layout': 'A4 landscape',
dustin@975:             'outputFormat': 'pdf',
dustin@975:             'attributes': {
dustin@975:                 'title': 'Auszug aus LADA',
dustin@975:                 'displayName': displayName,
dustin@975:                 'table': {
dustin@975:                     'columns': columnNames,
dustin@975:                     'data': data
dustin@975:                 }
dustin@975:             }
dustin@975:         }
dustin@1244:         return printData;
dustin@1244:     },
dustin@975: 
dustin@1244:     /**
dustin@1244:      * this function uses an AJAX request in order to
dustin@1244:      * send the data to the endpoint of the mapfish-print
dustin@1244:      */
dustin@1244:     printpdf: function(data, endpoint, filename, button){
dustin@975:         Ext.Ajax.request({
dustin@1244:             url: 'lada-printer/'+endpoint+'/buildreport.pdf',
dustin@975:             //configure a proxy in apache conf!
dustin@1244:             jsonData: data,
dustin@975:             binary: true,
dustin@975:             success: function(response) {
dustin@975:                 var content = response.responseBytes;
dustin@975:                 var filetype = response.getResponseHeader('Content-Type');
dustin@975:                 var blob = new Blob([content],{type: filetype});
dustin@1244:                 saveAs(blob, filename);
dustin@975:                 button.enable();
dustin@975:                 button.setLoading(false);
dustin@975:             },
dustin@975:             failure: function(response) {
dustin@1244:                 var i18n = Lada.getApplication().bundle;
dustin@975:                 console.log('failure');
dustin@975:                 // Error handling
dustin@975:                 button.enable();
dustin@975:                 button.setLoading(false);
dustin@975:                 if (response.responseText) {
dustin@975:                     try {
dustin@975:                         var json = Ext.JSON.decode(response.responseText);
dustin@975:                     }
dustin@975:                     catch(e){
dustin@975:                         console.log(e);
dustin@975:                     }
dustin@975:                 }
dustin@975:                 if (json) {
dustin@975:                     if(json.errors.totalCount > 0 || json.warnings.totalCount > 0){
dustin@975:                         formPanel.setMessages(json.errors, json.warnings);
dustin@975:                     }
dustin@975:                     if(json.message){
dustin@975:                         Ext.Msg.alert(Lada.getApplication().bundle.getMsg('err.msg.generic.title')
dustin@975:                             +' #'+json.message,
dustin@975:                             Lada.getApplication().bundle.getMsg(json.message));
dustin@975:                     } else {
dustin@975:                         Ext.Msg.alert(i18n.getMsg('err.msg.generic.title'),
dustin@975:                             i18n.getMsg('err.msg.print.noContact'));
dustin@975:                     }
dustin@975:                 } else {
dustin@975:                     Ext.Msg.alert(i18n.getMsg('err.msg.generic.title'),
dustin@975:                     i18n.getMsg('err.msg.print.noContact'));
dustin@975:                 }
dustin@975:             }
dustin@975:         });
dustin@1244:     }
dustin@977: 
dustin@975: });