Saiku嵌入頁面plugin=true效果自定義實現(二十七)

Saiku嵌入頁面使用 自定義實現 Plugin=true 效果

saiku嵌入頁面plugin=true時數據不顯示(plugin=false或者不設定plugin的值時數據顯示正常)這個問題困擾了我很久很久呀....  最近想着先處理問題吧,手動來實現一下相似的效果。html

 

Saiku能夠經過iframe將url嵌入頁面使用,正常狀況下是這樣子的express

http://10.22.33.44:8080/?username=admin&password=123&plugin=true&mode=view#query/open//KPI/ss.saikuapache

plugin的值爲true/falsejson

>> true: 以插件的形式展現,會隱藏菜單欄api

 

>> false: 不以插件的形式展現,會帶出工具欄數組

 

mode的值爲 view/table瀏覽器

>>view 會帶出導出excel那一欄工具按鈕信息app

>>table 只顯示table數據,沒有工具欄信息less

 

我部署在本地的saiku能正常使用以上方法嵌入頁面使用,可是不知道爲何 部署在公司的saiku使用plugin=true時顯示不了...  plugin=false的時候顯示正常 無奈這又很影響使用,因此就本身改了一下源碼,手動控制一些菜單欄以及工具欄的顯示了dom

【debug了好久,沒找到緣由,後期會繼續跟進此問題的,暫時先手工控制來處理此問題~】

 

實現思路:

  嵌入url中添加一個參數  embedFlag,參數值我指定爲 hideToolbar

  而後在Saiku的Query.js文件的run方法中獲取embedFlag參數值而且判斷參數值是否爲 hideToolbar。 若是是就添加控制菜單欄以及工具欄顯示的js代碼,若是不是就正常往下執行。

 

主要添加代碼:

//add embed flag,when the parameter embedFlag equals hideToolbar,hide the toolbar. 20190508
var paramsURI = Saiku.URLParams.paramsURI(); //get the param from url
if(paramsURI.embedFlag != undefined && paramsURI.embedFlag == "hideToolbar"){
	Saiku.toolbar.remove();//hide  toolbar
	$('#header').remove(); //hide tabs
	$('#new_icon').remove(); //hide open query button
	$('#fullscreen_icon').remove(); //hide fullscreen_icon button
}

 

因爲plugin=true嵌入後沒有數據顯示,因此這裏就不設定plugin參數了。

嵌入url:  http://10.22.33.44:8080/?username=admin&password=123&mode=view#query/open//KPI/demo1_1.saiku  

隱藏以前的效果:

 

在url上添加自定義的參數信息 embedFlag=hideToolbar

嵌入url:  http://10.22.33.44:8080/?username=admin&password=123&mode=view&embedFlag=hideToolbar#query/open//KPI/demo1_1.saiku  

隱藏以後的效果:

 

  

其實就是兩個點

1.在Query.js文件中run方法裏面添加此段代碼:

//add embed flag,when the parameter embedFlag equals hideToolbar,hide the toolbar. 20190508 var paramsURI = Saiku.URLParams.paramsURI(); //get the param from url if(paramsURI.embedFlag != undefined && paramsURI.embedFlag == "hideToolbar"){ Saiku.toolbar.remove();//hide toolbar $('#header').remove(); //hide tabs $('#new_icon').remove(); //hide open query button $('#fullscreen_icon').remove(); //hide fullscreen_icon button } 

  

2.在url中添加此參數信息:

embedFlag=hideToolbar

 

ps: 查詢按鈕 以及 全屏按鈕是否須要隱藏可根據本身的須要選擇註釋哦! (我這裏顯示的按鈕比較少 是由於我註釋掉了一些目前用不到的按鈕信息,避免形成用戶視覺混亂~)

隱藏按鈕也比較簡單啦, 谷歌瀏覽器 inspect 一下,而後找到對應的 id ,獲取元素而後調用remove方法就能夠啦~

例如 咱們想隱藏導出excel按鈕

1.inspect  看到對應的id爲  export_xls_icon

2. 在Query.js run方法裏面添加   $('#export_xls_icon').remove(); //hide export xls button  便可

 

 

最後提供完整的Query.js文件(修改後的)

Query.js

/*
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Workspace query
 */
var Query = Backbone.Model.extend({

    formatter: Settings.CELLSET_FORMATTER,
    properties: null,

	/*初始化方法*/
    initialize: function(args, options) {
		if(args != null && args != undefined && args != "" && args.flag == "resultForstatisdate"){
			
			this.get_all_statisdate(args);
		}else{
        // Save cube
        _.extend(this, options);

        // Bind `this`
        _.bindAll(this, "run");

        // Generate a unique query id
        this.uuid = 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
            function (c) {
                var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            }).toUpperCase();

        this.model = _.extend({ name: this.uuid }, SaikuOlapQueryTemplate);
        if (args.cube) {
            this.model.cube = args.cube;
        }
        this.helper = new SaikuOlapQueryHelper(this);

        // Initialize properties, action handler, and result handler
        this.action = new QueryAction({}, { query: this });
        this.result = new Result({ limit: Settings.RESULT_LIMIT }, { query: this });
        this.scenario = new QueryScenario({}, { query: this });

        // A flag to tell who changed selection members
        this.updatedSelectionFromModal = false;
		}
    },

    parse: function(response) {
        // Assign id so Backbone knows to PUT instead of POST
        this.id = this.uuid;
        if (response.name) {
            this.id = response.name;
            this.uuid = response.name;
        }
        this.model = _.extend(this.model, response);
        this.model.properties = _.extend({}, Settings.QUERY_PROPERTIES, this.model.properties);
    },

    setProperty: function(key, value) {
            this.model.properties[key] = value;
    },

    getProperty: function(key) {
        return this.model.properties[key];
    },

    syncSelectionsModalAndUpdateParameters: function() {
        if (this.updatedSelectionFromModal) {
            var mParameters = this.helper.model().parameters;
            for (var mKey in mParameters) {
                var mVal       = mParameters[mKey];
                var selections = this.helper.getSelectionsForParameter(mKey);

                mVal = selections.map(function(sel) { return sel.caption; }).join();
                mParameters[mKey] = mVal;
            }
        } else {
            var mParameters = this.helper.model().parameters;
            for (var mKey in mParameters) {
                var mVal       = mParameters[mKey];
                var mLevel     = this.helper.getLevelForParameter(mKey);
                var selections = this.helper.getSelectionsForParameter(mKey);

                if (mVal !== null && mVal !== undefined) {
                    this.helper.setSelectionsForParameter(mKey, _.filter(selections, function(sel) {
                        var containsParam = false;
                        _.each(mVal.split(','), function (v) {
                            if (sel.caption === v) {
                                containsParam = true;
                                return false;
                            }
                        });
                        return containsParam;
                    }));
                }
            }
        }

        this.updatedSelectionFromModal = false;
    },

	/*執行查詢的方法*/
    run: function(force, mdx) {
		
		//add embed flag,when the parameter embedFlag equals hideToolbar,hide the toolbar. 20190508
		var paramsURI = Saiku.URLParams.paramsURI(); //get the param from url
		if(paramsURI.embedFlag != undefined && paramsURI.embedFlag == "hideToolbar"){
			Saiku.toolbar.remove();//hide  toolbar
			$('#header').remove(); //hide tabs
			$('#new_icon').remove(); //hide open query button
			$('#fullscreen_icon').remove(); //hide fullscreen_icon button
		}
		
        this.syncSelectionsModalAndUpdateParameters();

        var self = this;
        // Check for automatic execution
        Saiku.ui.unblock();
        if (typeof this.model.properties != "undefined" && this.model.properties['saiku.olap.query.automatic_execution'] === false &&
			(force === false || force === undefined || force === null)) {
            return;
        }
        this.workspace.unblock();

        $(this.workspace.el).find(".workspace_results_info").empty();
        this.workspace.trigger('query:run');
        this.result.result = null;
        var validated = false;
        var errorMessage = '<span class="i18n">Query Validation failed!</span>';

        var exModel = this.helper.model();
		
		//針對Summary數據作出更改 當行數據為空的時候 也須要展現出來
		var cubename = exModel.cube.name ;
		if(cubename == "SummaryKPI_2018_ext" ||cubename == "SummaryKPI_2019_ext" ||cubename == "SummaryKPI_2019_Dynamic" ) {
			exModel.queryModel.axes.ROWS.nonEmpty=false;//設置行數據為空的時候也顯示數據! 20190425 for summaryKPI Data
		}else{
			exModel.queryModel.axes.ROWS.nonEmpty=true;
		}
		for(var k in this.attributes) {
			var att = this.attributes[k];
			if(k.substring(0,5)==="PARAM"){
				var p = k.substring(5, k.length);
				exModel.parameters[p] = att;
			}

		}
        if (exModel.queryType == "OLAP") {
            if (exModel.type == "QUERYMODEL") {
                var columnsOk = Object.keys(exModel.queryModel.axes.COLUMNS.hierarchies).length > 0;
                var rowsOk = Object.keys(exModel.queryModel.axes.ROWS.hierarchies).length > 0;
                var detailsOk = exModel.queryModel.details.axis == 'COLUMNS' && exModel.queryModel.details.measures.length > 0;
                if (!rowsOk || !columnsOk || !detailsOk) {
                    errorMessage = "";
                }
                if (!columnsOk && !detailsOk) {
                    errorMessage += '<span class="i18n">You need to include at least one measure or a level on columns for a valid query.</span>';
                }
                if(!rowsOk) {
                    errorMessage += '<span class="i18n">You need to include at least one level on rows for a valid query.</span>';

                }
                if ( (columnsOk || detailsOk) && rowsOk) {
                    validated = true;
                }

            } else if (exModel.type == "MDX") {
                validated = (exModel.mdx && exModel.mdx.length > 0);
                if (!validated) {
                    errorMessage = '<span class="i18n">You need to enter some MDX statement to execute.</span>';
                }
            }
        }
        if (!validated) {
            this.workspace.table.clearOut();
            $(this.workspace.processing).html(errorMessage).show();
            this.workspace.adjust();
            Saiku.i18n.translate();
            return;
        }


        // Run it
        this.workspace.table.clearOut();
        $(this.workspace.processing).html('<span class="processing_image">  </span> <span class="i18n">Running query...</span> [ <a class="cancel i18n" href="#cancel">Cancel</a> ]').show();
        this.workspace.adjust();
        this.workspace.trigger('query:fetch');
		Saiku.i18n.translate();
        var message = '<span class="processing_image">  </span> <span class="i18n">Running query...</span> [ <a class="cancel i18n" href="#cancel">Cancel</a> ]';
        this.workspace.block(message);
/*
        TODO: i wonder if we should clean up the model (name and captions etc.)
        delete this.model.queryModel.axes['FILTER'].name;
*/
		
		
		/**根據ROWS中的statisdate字段過濾!*/
		//根據用戶輸入的開始日期與結束日期查詢範圍數據
		/*
		var dimensionArr = exModel.queryModel.axes.ROWS.hierarchies; //取出行信息中的全部維度信息 dimension,用一個數組接收
		var statisdateFlag = "no";
		for(var i=0;i<dimensionArr.length;i++){
			//判斷維度信息中是否有statisdate這個時間維度(這是固定的)
			if(dimensionArr[i]!=null && ((dimensionArr[i].dimension == "statisdate")||(dimensionArr[i].levels.statisdate != null)) ){
				var paramsURI = Saiku.URLParams.paramsURI(); //get the param from url
				//判斷參數是否爲空
				if(paramsURI.startdate != null && paramsURI.startdate != undefined && paramsURI.startdate != ""&&
					paramsURI.enddate != null && paramsURI.enddate != undefined && paramsURI.enddate != ""){
					statisdateFlag = "yes";	
					this.startdateThis=null;
					this.enddateThis=null;
					var key="statisdateSpec";
					 (new SelectionsModal({
						key: key,
						exModel: exModel,
						result: this.result,
						workspace: this.workspace
					}));

				}
			}
		}
		*/
		
		/**根據Fliter中的statisdate字段過濾!*/
		var dimensionArr = exModel.queryModel.axes.FILTER.hierarchies; //取出FILTER信息中的全部維度信息 dimension,用一個數組接收
		var statisdateFlag = "no";
		for(var i=0;i<dimensionArr.length;i++){
			//判斷維度信息中是否有statisdate這個時間維度(這是固定的)
			if(dimensionArr[i]!=null && ((dimensionArr[i].dimension == "statisdate")||(dimensionArr[i].levels.statisdate != null)) ){
				var paramsURI = Saiku.URLParams.paramsURI(); //get the param from url
				//判斷參數是否爲空
				if(paramsURI.startdate != null && paramsURI.startdate != undefined && paramsURI.startdate != ""&&
					paramsURI.enddate != null && paramsURI.enddate != undefined && paramsURI.enddate != ""){
					statisdateFlag = "yes";	
					this.startdateThis=null;
					this.enddateThis=null;
					var key="statisdateSpec";
					 (new SelectionsModal({
						key: key,
						exModel: exModel,
						result: this.result,
						workspace: this.workspace
					}));

				}
			}
		}
		
		//根據入參是否有statisdate字段來判斷是否執行如下查詢
		if(statisdateFlag == 'no'){
			this.result.save({},{ contentType: "application/json", data: JSON.stringify(exModel), error: function() {
				Saiku.ui.unblock();
				var errorMessage = '<span class="i18n">Error executing query. Please check the server logs or contact your administrator!</span>';
				self.workspace.table.clearOut();
				$(self.workspace.processing).html(errorMessage).show();
				self.workspace.adjust();
				Saiku.i18n.translate();
			} });
		}
    },

	//獲得返回的全部statisdate參數信息
	get_all_statisdate: function(args){
		var response = args.response;
		this.result = args.result;
		//var exModel = args.exModel;
		var statisdateArr= new Array();
		for(var i=0;i<response.length;i++){
			statisdateArr[i]=response[i].name;
		}
		//this.helper = new SaikuOlapQueryHelper(this);
		var exModel = args.exModel;
		var paramsURI = Saiku.URLParams.paramsURI(); //get the param from url
		var startdate=null;
		var enddate=null;
		if(this.startdateThis != null){
			startdate=this.dateToStr(this.startdateThis); //獲取修正後的開始日期
		}else{
			startdate=paramsURI.startdate;//開始日期(參數中的)
		}
		
		if(this.enddateThis != null){
			enddate=this.dateToStr(this.enddateThis); //獲取修正後的結束日期
		}else{
			enddate=paramsURI.enddate;//結束日期(參數中的)
		}
		
		//startdate = this.dateToStr(startdate); // 日期格式化
		//enddate = this.dateToStr(enddate); // 日期格式化
		if(statisdateArr.indexOf(startdate) > -1){// 這裏是判斷開始日期是否屬於statisdateArr
			
			if(statisdateArr.indexOf(enddate) > -1){// 這裏是判斷結束日期是否屬於statisdateArr
				
				//var dimensionArr = exModel.queryModel.axes.ROWS.hierarchies; //根據ROWS
				var dimensionArr = exModel.queryModel.axes.FILTER.hierarchies; //根據Filter
				for(var i=0;i<dimensionArr.length;i++){
					if(dimensionArr[i]!=null && (dimensionArr[i].dimension == "statisdate" || dimensionArr[i].levels.statisdate != null ) ){
						//更改level下的mdx表達式(使用開始日期與結束日期來控制過濾數據)
						dimensionArr[i].levels.statisdate.mdx="[statisdate].[statisdate].[statisdate].["+startdate+"]:[statisdate].[statisdate].[statisdate].["+enddate+"]";
						//須要清除以前默認展現本週數據的過濾腳本信息
						//exModel.queryModel.axes.ROWS.filters=[];//在ROWS中定義了過濾表達式時,清除此表達式
						exModel.queryModel.axes.FILTER.filters=[];//在Filter中定義了過濾表達式時,清除此表達式
					}
				}

				this.result.save({},{ contentType: "application/json", data: JSON.stringify(exModel), error: function() {
					Saiku.ui.unblock();
					var errorMessage = '<span class="i18n">Error executing query. Please check the server logs or contact your administrator!</span>';
					self.workspace.table.clearOut();
					$(self.workspace.processing).html(errorMessage).show();
					self.workspace.adjust();
					Saiku.i18n.translate();
				} });
			}else{//結束日期不存在時:若是結束日期大於開始日期,將結束日期往前減一天
			
				var tmpStartdate = this.strToDate(startdate);//StringToDate方法不存在
				var tmpEnddate = this.strToDate(enddate);
			
				if(tmpEnddate>=tmpStartdate){
					tmpEnddate = tmpEnddate.valueOf();
					tmpEnddate = tmpEnddate - 1*24*60*60*1000;
					tmpEnddate = new Date(tmpEnddate);
					
					//這裏改變paramURL中的結束日期參數值,而後回調當前函數 get_all_statisdate
					this.enddateThis=tmpEnddate;
					this.get_all_statisdate(args);
					
				}else{ //不然的話直接執行查詢,直接無數據返回
				
					var dimensionArr = exModel.queryModel.axes.FILTER.hierarchies;
					for(var i=0;i<dimensionArr.length;i++){
						if(dimensionArr[i]!=null && (dimensionArr[i].dimension == "statisdate" || dimensionArr[i].levels.statisdate != null ) ){
							enddate = this.dateToStr(tmpStartdate)
							//更改level下的mdx表達式(使用開始日期與結束日期來控制過濾數據)
							dimensionArr[i].levels.statisdate.mdx="[statisdate].[statisdate].[statisdate].["+enddate+"]:[statisdate].[statisdate].[statisdate].["+enddate+"]";
							//須要清除以前默認展現本週數據的過濾腳本信息
							//exModel.queryModel.axes.ROWS.filters=[];//在ROWS中定義了過濾表達式時,清除此表達式
							exModel.queryModel.axes.FILTER.filters=[];//在Filter中定義了過濾表達式時,清除此表達式
					
						}
					}
					
					this.result.save({},{ contentType: "application/json", data: JSON.stringify(exModel), error: function() {
						Saiku.ui.unblock();
						var errorMessage = '<span class="i18n">Error executing query. Please check the server logs or contact your administrator!</span>';
						self.workspace.table.clearOut();
						$(self.workspace.processing).html(errorMessage).show();
						self.workspace.adjust();
						Saiku.i18n.translate();
					} });
					
				}
			}
		}else{ //開始日期不存在時: 若是開始日期小於結束日期,將開始日期日後加一天
			
			var tmpStartdate = this.strToDate(startdate);
			var tmpEnddate = this.strToDate(enddate);
			if(tmpStartdate<=tmpEnddate){
				tmpStartdate = tmpStartdate.valueOf();
				tmpStartdate = tmpStartdate + 1*24*60*60*1000;
				tmpStartdate = new Date(tmpStartdate);
				
				//這裏改變paramURL中的結束日期參數值,而後回調當前函數get_all_statisdate
				this.startdateThis=tmpStartdate;
				this.get_all_statisdate(args);
			}else{ //不然的話直接執行查詢,直接無數據返回
			
				var dimensionArr = exModel.queryModel.axes.FILTER.hierarchies;
				for(var i=0;i<dimensionArr.length;i++){
					if(dimensionArr[i]!=null && (dimensionArr[i].dimension == "statisdate" || dimensionArr[i].levels.statisdate != null ) ){
						startdate = this.dateToStr(tmpEnddate)
						//更改level下的mdx表達式(使用開始日期與結束日期來控制過濾數據)
						dimensionArr[i].levels.statisdate.mdx="[statisdate].[statisdate].[statisdate].["+startdate+"]:[statisdate].[statisdate].[statisdate].["+startdate+"]";
						//須要清除以前默認展現本週數據的過濾腳本信息
						//exModel.queryModel.axes.ROWS.filters=[];//在ROWS中定義了過濾表達式時,清除此表達式
						exModel.queryModel.axes.FILTER.filters=[];//在Filter中定義了過濾表達式時,清除此表達式	
					}
				}
				
				this.result.save({},{ contentType: "application/json", data: JSON.stringify(exModel), error: function() {
					Saiku.ui.unblock();
					var errorMessage = '<span class="i18n">Error executing query. Please check the server logs or contact your administrator!</span>';
					self.workspace.table.clearOut();
					$(self.workspace.processing).html(errorMessage).show();
					self.workspace.adjust();
					Saiku.i18n.translate();
				} });
				
			}
		}
	},
	
	/*將string類型的數據轉換為date類型*/
	strToDate: function(strDate){
		strDate = strDate.toLocaleString();
		strDate = strDate.substring(-1,10);
		var convert = Date.parse(strDate);
		var tmpdate = new Date(convert);
		return tmpdate;
	},
	
	/*將Date類型轉換爲String類型 格式爲:2019-03-03*/
	dateToStr: function(dateStr){
		//dateStr = this.strToDate(dateStr);
		var tmpYear= dateStr.getFullYear();
		var tmpMonth = dateStr.getMonth()+1;
		var tmpDay = dateStr.getDate();
		if(tmpMonth < 10){ tmpMonth = "0"+tmpMonth;}
		if(tmpDay < 10){ tmpDay = "0"+tmpDay;}
		var tmpdate = tmpYear+"-"+tmpMonth+"-"+tmpDay;
		return tmpdate;	
	},
	
	
    enrich: function() {
        var self = this;
        this.workspace.query.action.post("/../enrich", {
            contentType: "application/json",
            data: JSON.stringify(self.model),
            async: false,
            success: function(response, model) {
                self.model = model;
            }
        });
    },

    url: function() {
        return "api/query/" + encodeURI(this.uuid);
    }
	 /**
	get_statisdate_members: function() {
            var path = "/result/metadata/hierarchies/%5Bstatisdate%5D.%5Bstatisdate%5D/levels/statisdate";
           
       
         * gett isn't a typo, although someone should probably rename that method to avoid confusion.
         
            this.workspace.query.action.gett(path, {
                success: this.fetch_statisdate_members,
                error: function() {
                   alert("error");
                },
                data: {result: true, searchlimit: 30000 }});
    },
	
	獲得獲取statisdate字段的結果信息然後處理
	 fetch_statisdate_members: function(model, response) {
        
        if (response && response.length > 0) {
          alert("Fetch_statisdate_member++++++++++++"+response);
        }
      
    },
	
	*/
});
相關文章
相關標籤/搜索