Test Failed
Push — CI ( 0f01dd...c95a04 )
by Adam
55:13
created

campaign_charts::campaign_response_roi_data()   F

Complexity

Conditions 14
Paths 2080

Size

Total Lines 139
Code Lines 96

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 139
rs 2
c 1
b 0
f 0
cc 14
eloc 96
nc 2080
nop 8

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3
/*********************************************************************************
4
 * SugarCRM Community Edition is a customer relationship management program developed by
5
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
6
7
 * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
8
 * Copyright (C) 2011 - 2014 Salesagility Ltd.
9
 *
10
 * This program is free software; you can redistribute it and/or modify it under
11
 * the terms of the GNU Affero General Public License version 3 as published by the
12
 * Free Software Foundation with the addition of the following permission added
13
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
14
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
15
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
16
 *
17
 * This program is distributed in the hope that it will be useful, but WITHOUT
18
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
20
 * details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License along with
23
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
24
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25
 * 02110-1301 USA.
26
 *
27
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
28
 * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
29
 *
30
 * The interactive user interfaces in modified source and object code versions
31
 * of this program must display Appropriate Legal Notices, as required under
32
 * Section 5 of the GNU Affero General Public License version 3.
33
 *
34
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
35
 * these Appropriate Legal Notices must retain the display of the "Powered by
36
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
37
 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
38
 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
39
 ********************************************************************************/
40
41
/*********************************************************************************
42
43
* Description:  Includes the functions for Customer module specific charts.
44
********************************************************************************/
45
46
47
48
49
require_once('include/SugarCharts/SugarChartFactory.php');
50
51
52
class campaign_charts {
53
	/**
54
	* Creates opportunity pipeline image as a VERTICAL accumlated bar graph for multiple users.
55
	* param $datax- the month data to display in the x-axis
56
	* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
57
	* All Rights Reserved..
58
	* Contributor(s): ______________________________________..
59
	*/
60
61
	function campaign_response_by_activity_type($datay= array(),$targets=array(),$campaign_id, $cache_file_name='a_file', $refresh=false, $marketing_id='') {
62
		global $app_strings, $mod_strings, $charset, $lang, $barChartColors,$app_list_strings;
63
		$sugarChart = SugarChartFactory::getInstance('','Reports');
64
		$xmlFile = $sugarChart->getXMLFileName($campaign_id);
65
66
		if (!file_exists($xmlFile) || $refresh == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
67
			$GLOBALS['log']->debug("datay is:");
68
			$GLOBALS['log']->debug($datay);
69
			$GLOBALS['log']->debug("user_id is: ");
70
			$GLOBALS['log']->debug("cache_file_name is: $xmlFile");
71
72
			$focus = new Campaign();
73
74
			$query = "SELECT activity_type,target_type, count(*) hits ";
75
			$query.= " FROM campaign_log ";
76
			$query.= " WHERE campaign_id = '$campaign_id' AND archived=0 AND deleted=0";
77
78
            //if $marketing id is specified, then lets filter the chart by the value
79
            if (!empty($marketing_id)){
80
                $query.= " AND marketing_id ='$marketing_id'";
81
            }
82
83
			$query.= " GROUP BY  activity_type, target_type";
84
			$query.= " ORDER BY  activity_type, target_type";
85
			$result = $focus->db->query($query);
86
			//$camp_data=$focus->db->fetchByAssoc($result);
87
			$camp_data = array();
88
			$leadSourceArr = array();
89
			$total=0;
90
			$total_targeted=0;
91
			$rowTotalArr = array();
92
			$rowTotalArr[] = 0;
93
			while($row = $focus->db->fetchByAssoc($result))
94
			{
95
				if(!isset($leadSourceArr[$row['activity_type']]['row_total'])) {
96
					$leadSourceArr[$row['activity_type']]['row_total']=0;
97
				}
98
99
				$leadSourceArr[$row['activity_type']][$row['target_type']]['hits'][] = $row['hits'];
100
				$leadSourceArr[$row['activity_type']][$row['target_type']]['total'][] = $row['hits'];
101
				$leadSourceArr[$row['activity_type']]['outcome'][$row['target_type']]=$row['target_type'];
102
				$leadSourceArr[$row['activity_type']]['row_total'] += $row['hits'];
103
104
				if (!isset($leadSourceArr['all_activities'][$row['target_type']])) {
105
					$leadSourceArr['all_activities'][$row['target_type']]=array('total'=>0);
106
				}
107
108
				$leadSourceArr['all_activities'][$row['target_type']]['total'] += $row['hits'];
109
110
				$total += $row['hits'];
111
				if ($row['activity_type'] =='targeted') {
112
					$targeted[$row['target_type']]=$row['hits'];
113
					$total_targeted+=$row['hits'];
114
				}
115
			}
116
117
			foreach ($datay as $key=>$translation) {
118
				if ($key == '') {
119
					//$key = $mod_strings['NTC_NO_LEGENDS'];
120
					$key = 'None';
121
					$translation = $mod_strings['NTC_NO_LEGENDS'];
122
				}
123
				if(!isset($leadSourceArr[$key])){
124
					$leadSourceArr[$key] = $key;
125
				}
126
127
128
				if(is_array($leadSourceArr[$key]) && isset($leadSourceArr[$key]['row_total'])){$rowTotalArr[]=$leadSourceArr[$key]['row_total'];}
129
				if(is_array($leadSourceArr[$key]) && isset($leadSourceArr[$key]['row_total']) && $leadSourceArr[$key]['row_total']>100){
130
					$leadSourceArr[$key]['row_total'] = round($leadSourceArr[$key]['row_total']);
131
				}
132
				$camp_data[$translation] = array();
133
					foreach ($targets as $outcome=>$outcome_translation){
134
						//create alternate text.
135
                        $alttext = ' ';
136
                        if(isset($targeted) && isset($targeted[$outcome])&& !empty($targeted[$outcome])){
137
						$alttext=$targets[$outcome].': '.$mod_strings['LBL_TARGETED'].' '.$targeted[$outcome]. ', '.$mod_strings['LBL_TOTAL_TARGETED'].' '. $total_targeted. ".";
138
                        }
139
						if ($key != 'targeted'){
140
							$hits =  (isset($leadSourceArr[$key][$outcome]) && is_array($leadSourceArr[$key][$outcome]) && is_array($leadSourceArr[$key][$outcome]['hits'])) ? array_sum($leadSourceArr[$key][$outcome]['hits']) : 0;
141
							$alttext.=" $translation ".$hits;
142
						}
143
						$count = (isset($leadSourceArr[$key][$outcome]) && is_array($leadSourceArr[$key][$outcome]) && is_array($leadSourceArr[$key][$outcome]['total'])) ? array_sum($leadSourceArr[$key][$outcome]['total']) : 0;
144
						$camp_data[$translation][$outcome] =
145
							array(
146
							"numerical_value" => $count,
147
							"group_text" => $translation,
148
							"group_key" => "",
149
							"count" => "{$count}",
150
							"group_label" => $alttext,
151
							"numerical_label" => "Hits",
152
							"numerical_key" => "hits",
153
							"module" => 'Campaigns',
154
     						"group_base_text" => $outcome,
155
     						"link" => $key
156
							);
157
					}
158
159
			}
160
161
            // Since this isn't a standard report chart (with report defs), set the group_by manually so the chart bars show properly
162
            $sugarChart->group_by = array('activity_type', 'target_type');
163
164
			if($camp_data)
0 ignored issues
show
Bug Best Practice introduced by
The expression $camp_data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
165
			$sugarChart->setData($camp_data);
166
			else
167
			$sugarChart->setData(array());
168
169
			$sugarChart->setProperties($mod_strings['LBL_CAMPAIGN_RESPONSE_BY_RECIPIENT_ACTIVITY'], "", 'horizontal group by chart');
170
			$sugarChart->saveXMLFile($xmlFile, $sugarChart->generateXML());
171
		}
172
173
		$width = '100%';
174
		$return = '';
175
		$return .= $sugarChart->display($campaign_id, $xmlFile, $width, '480',"");
176
177
		return $return;
178
	}
179
180
	//campaign roi computations.
181
	function campaign_response_roi($datay= array(),$targets=array(),$campaign_id, $cache_file_name='a_file', $refresh=false,$marketing_id='',$is_dashlet=false,$dashlet_id='') {
182
		global $app_strings,$mod_strings, $current_module_strings, $charset, $lang, $app_list_strings, $current_language,$sugar_config;
183
184
		$not_empty = false;
185
186
		if ($is_dashlet){
187
			$mod_strings = return_module_language($current_language, 'Campaigns');
188
		}
189
190
		if (!file_exists($cache_file_name) || $refresh == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
191
			$GLOBALS['log']->debug("datay is:");
192
			$GLOBALS['log']->debug($datay);
193
			$GLOBALS['log']->debug("user_id is: ");
194
			$GLOBALS['log']->debug("cache_file_name is: $cache_file_name");
195
196
			$focus = new Campaign();
197
            $focus->retrieve($campaign_id);
198
			$opp_count=0;
199
			$opp_query  = "select count(*) opp_count,sum(" . db_convert("amount_usdollar","IFNULL",array(0)).")  total_value";
0 ignored issues
show
Deprecated Code introduced by
The function db_convert() has been deprecated with message: use DBManager::convert() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
200
            $opp_query .= " from opportunities";
201
            $opp_query .= " where campaign_id='$campaign_id'";
202
            $opp_query .= " and sales_stage='Prospecting'";
203
            $opp_query .= " and deleted=0";
204
205
            $opp_result=$focus->db->query($opp_query);
206
            $opp_data=$focus->db->fetchByAssoc($opp_result);
207
//            if (empty($opp_data['opp_count'])) $opp_data['opp_count']=0;
208
            if (empty($opp_data['total_value'])) $opp_data['total_value']=0;
209
210
            //report query
211
			$opp_query1  = "select SUM(opp.amount) as revenue";
212
            $opp_query1 .= " from opportunities opp";
213
            $opp_query1 .= " right join campaigns camp on camp.id = opp.campaign_id";
214
            $opp_query1 .= " where opp.sales_stage = 'Closed Won'and camp.id='$campaign_id' and opp.deleted=0";
215
            $opp_query1 .= " group by camp.name";
216
217
            $opp_result1=$focus->db->query($opp_query1);
218
            $opp_data1=$focus->db->fetchByAssoc($opp_result1);
219
220
			//if (empty($opp_data1[]))
221
            if (empty($opp_data1['revenue'])){
222
				$opp_data1[$mod_strings['LBL_ROI_CHART_REVENUE']] = 0;
223
                unset($opp_data1['revenue']);
224
            }else{
225
                $opp_data1[$mod_strings['LBL_ROI_CHART_REVENUE']] = $opp_data1['revenue'];
226
                unset($opp_data1['revenue']);
227
				$not_empty = true;
228
            }
229
230
			$camp_query1  = "select camp.name, SUM(camp.actual_cost) as investment,SUM(camp.budget) as budget,SUM(camp.expected_revenue) as expected_revenue";
231
            $camp_query1 .= " from campaigns camp";
232
            $camp_query1 .= " where camp.id='$campaign_id'";
233
            $camp_query1 .= " group by camp.name";
234
235
            $camp_result1=$focus->db->query($camp_query1);
236
            $camp_data1=$focus->db->fetchByAssoc($camp_result1);
237
            //query needs to be lowercase, but array keys need to be propercased, as these are used in
238
            //chart to display legend
239
240
			if (empty($camp_data1['investment']))
241
				$camp_data1['investment'] = 0;
242
			else
243
				$not_empty = true;
244
			if (empty($camp_data1['budget']))
245
				$camp_data1['budget'] = 0;
246
			else
247
				$not_empty = true;
248
            if (empty($camp_data1['expected_revenue']))
249
            	$camp_data1['expected_revenue'] = 0;
250
			else
251
				$not_empty = true;
252
253
            $opp_data1[$mod_strings['LBL_ROI_CHART_INVESTMENT']]=$camp_data1['investment'];
254
	        $opp_data1[$mod_strings['LBL_ROI_CHART_BUDGET']]=$camp_data1['budget'];
255
	        $opp_data1[$mod_strings['LBL_ROI_CHART_EXPECTED_REVENUE']]=$camp_data1['expected_revenue'];
256
257
258
			$query = "SELECT activity_type,target_type, count(*) hits ";
259
			$query.= " FROM campaign_log ";
260
			$query.= " WHERE campaign_id = '$campaign_id' AND archived=0 AND deleted=0";
261
            //if $marketing id is specified, then lets filter the chart by the value
262
            if (!empty($marketing_id)){
263
                $query.= " AND marketing_id ='$marketing_id'";
264
            }
265
			$query.= " GROUP BY  activity_type, target_type";
266
			$query.= " ORDER BY  activity_type, target_type";
267
			$result = $focus->db->query($query);
268
269
			$leadSourceArr = array();
270
			$total=0;
271
			$total_targeted=0;
272
273
		}
274
275
		global $current_user;
276
		$user_id = $current_user->id;
277
278
279
		$width = '100%';
280
281
		$return = '';
282
		if (!$is_dashlet){
283
			$return .= '<br />';
284
		}
285
286
287
        $currency_id = $focus->currency_id;
288
        $currency_symbol = $sugar_config['default_currency_symbol'];
289
        if(!empty($currency_id)){
290
291
            $cur = new Currency();
292
            $cur->retrieve($currency_id);
293
            $currency_symbol = $cur->symbol;
294
        }
295
296
297
		$sugarChart = SugarChartFactory::getInstance();
298
		$sugarChart->is_currency = true;
299
        $sugarChart->currency_symbol = $currency_symbol;
300
301
		if ($not_empty)
302
	 		$sugarChart->setData($opp_data1);
303
		else
304
			$sugarChart->setData(array());
305
		$sugarChart->setProperties($mod_strings['LBL_CAMPAIGN_RETURN_ON_INVESTMENT'], $mod_strings['LBL_AMOUNT_IN'].$currency_symbol, 'bar chart');
306
307
    	if (!$is_dashlet){
308
			$xmlFile = $sugarChart->getXMLFileName('roi_details_chart');
309
			$sugarChart->saveXMLFile($xmlFile, $sugarChart->generateXML());
310
			$return .= $sugarChart->display('roi_details_chart', $xmlFile, $width, '480');
311
		}
312
		else{
313
			$xmlFile = $sugarChart->getXMLFileName($dashlet_id);
314
			$sugarChart->saveXMLFile($xmlFile, $sugarChart->generateXML());
315
			$return .= $sugarChart->display($dashlet_id, $xmlFile, $width, '480');
316
		}
317
318
		return $return;
319
	}
320
321
	//THis is a copy of the campaign_response_roi for rgraph so that the data is separate from the chart / presentation
322
	//this will need refactored later rather than a cut n paste job like this
323
	//perhaps add another boolean to the parameter list to return just the data or the chart
324
	function campaign_response_roi_data($datay= array(),$targets=array(),$campaign_id, $cache_file_name='a_file', $refresh=false,$marketing_id='',$is_dashlet=false,$dashlet_id='') {
325
		global $app_strings,$mod_strings, $current_module_strings, $charset, $lang, $app_list_strings, $current_language,$sugar_config;
326
327
		$not_empty = false;
328
329
		if ($is_dashlet){
330
			$mod_strings = return_module_language($current_language, 'Campaigns');
331
		}
332
333
		if (!file_exists($cache_file_name) || $refresh == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
334
			$GLOBALS['log']->debug("datay is:");
335
			$GLOBALS['log']->debug($datay);
336
			$GLOBALS['log']->debug("user_id is: ");
337
			$GLOBALS['log']->debug("cache_file_name is: $cache_file_name");
338
339
			$focus = new Campaign();
340
			$focus->retrieve($campaign_id);
341
			$opp_count=0;
342
			$opp_query  = "select count(*) opp_count,sum(" . db_convert("amount_usdollar","IFNULL",array(0)).")  total_value";
0 ignored issues
show
Deprecated Code introduced by
The function db_convert() has been deprecated with message: use DBManager::convert() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
343
			$opp_query .= " from opportunities";
344
			$opp_query .= " where campaign_id='$campaign_id'";
345
			$opp_query .= " and sales_stage='Prospecting'";
346
			$opp_query .= " and deleted=0";
347
348
			$opp_result=$focus->db->query($opp_query);
349
			$opp_data=$focus->db->fetchByAssoc($opp_result);
350
//            if (empty($opp_data['opp_count'])) $opp_data['opp_count']=0;
351
			if (empty($opp_data['total_value'])) $opp_data['total_value']=0;
352
353
			//report query
354
			$opp_query1  = "select SUM(opp.amount) as revenue";
355
			$opp_query1 .= " from opportunities opp";
356
			$opp_query1 .= " right join campaigns camp on camp.id = opp.campaign_id";
357
			$opp_query1 .= " where opp.sales_stage = 'Closed Won'and camp.id='$campaign_id' and opp.deleted=0";
358
			$opp_query1 .= " group by camp.name";
359
360
			$opp_result1=$focus->db->query($opp_query1);
361
			$opp_data1=$focus->db->fetchByAssoc($opp_result1);
362
363
			//if (empty($opp_data1[]))
364
			if (empty($opp_data1['revenue'])){
365
				$opp_data1[$mod_strings['LBL_ROI_CHART_REVENUE']] = 0;
366
				unset($opp_data1['revenue']);
367
			}else{
368
				$opp_data1[$mod_strings['LBL_ROI_CHART_REVENUE']] = $opp_data1['revenue'];
369
				unset($opp_data1['revenue']);
370
				$not_empty = true;
371
			}
372
373
			$camp_query1  = "select camp.name, SUM(camp.actual_cost) as investment,SUM(camp.budget) as budget,SUM(camp.expected_revenue) as expected_revenue";
374
			$camp_query1 .= " from campaigns camp";
375
			$camp_query1 .= " where camp.id='$campaign_id'";
376
			$camp_query1 .= " group by camp.name";
377
378
			$camp_result1=$focus->db->query($camp_query1);
379
			$camp_data1=$focus->db->fetchByAssoc($camp_result1);
380
			//query needs to be lowercase, but array keys need to be propercased, as these are used in
381
			//chart to display legend
382
383
			if (empty($camp_data1['investment']))
384
				$camp_data1['investment'] = 0;
385
			else
386
				$not_empty = true;
387
			if (empty($camp_data1['budget']))
388
				$camp_data1['budget'] = 0;
389
			else
390
				$not_empty = true;
391
			if (empty($camp_data1['expected_revenue']))
392
				$camp_data1['expected_revenue'] = 0;
393
			else
394
				$not_empty = true;
395
396
			$opp_data1[$mod_strings['LBL_ROI_CHART_INVESTMENT']]=$camp_data1['investment'];
397
			$opp_data1[$mod_strings['LBL_ROI_CHART_BUDGET']]=$camp_data1['budget'];
398
			$opp_data1[$mod_strings['LBL_ROI_CHART_EXPECTED_REVENUE']]=$camp_data1['expected_revenue'];
399
400
401
			$query = "SELECT activity_type,target_type, count(*) hits ";
402
			$query.= " FROM campaign_log ";
403
			$query.= " WHERE campaign_id = '$campaign_id' AND archived=0 AND deleted=0";
404
			//if $marketing id is specified, then lets filter the chart by the value
405
			if (!empty($marketing_id)){
406
				$query.= " AND marketing_id ='$marketing_id'";
407
			}
408
			$query.= " GROUP BY  activity_type, target_type";
409
			$query.= " ORDER BY  activity_type, target_type";
410
			$result = $focus->db->query($query);
411
412
			$leadSourceArr = array();
413
			$total=0;
414
			$total_targeted=0;
415
416
		}
417
418
		global $current_user;
419
		$user_id = $current_user->id;
420
421
422
		$width = '100%';
423
424
		$return = '';
425
		if (!$is_dashlet){
426
			$return .= '<br />';
427
		}
428
429
430
		$currency_id = $focus->currency_id;
431
		$currency_symbol = $sugar_config['default_currency_symbol'];
432
		if(!empty($currency_id)){
433
434
			$cur = new Currency();
435
			$cur->retrieve($currency_id);
436
			$currency_symbol = $cur->symbol;
437
		}
438
439
440
		$sugarChart = SugarChartFactory::getInstance();
441
		$sugarChart->is_currency = true;
442
		$sugarChart->currency_symbol = $currency_symbol;
443
444
		if ($not_empty)
445
			$sugarChart->setData($opp_data1);
446
		else
447
			$sugarChart->setData(array());
448
		$sugarChart->setProperties($mod_strings['LBL_CAMPAIGN_RETURN_ON_INVESTMENT'], $mod_strings['LBL_AMOUNT_IN'].$currency_symbol, 'bar chart');
449
450
		if (!$is_dashlet){
451
			$xmlFile = $sugarChart->getXMLFileName('roi_details_chart');
452
			$sugarChart->saveXMLFile($xmlFile, $sugarChart->generateXML());
453
			$return .= $sugarChart->display('roi_details_chart', $xmlFile, $width, '480');
454
		}
455
		else{
456
			$xmlFile = $sugarChart->getXMLFileName($dashlet_id);
457
			$sugarChart->saveXMLFile($xmlFile, $sugarChart->generateXML());
458
			$return .= $sugarChart->display($dashlet_id, $xmlFile, $width, '480');
459
		}
460
461
		return $return;
462
	}
463
}// end charts class
464
?>
465