Completed
Push — master ( a75ecc...97ae17 )
by Adam
71:21 queued 52:34
created

CampaignROIChartDashlet::constructQuery()   C

Complexity

Conditions 7
Paths 33

Size

Total Lines 96
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 96
rs 6.4785
cc 7
eloc 57
nc 33
nop 8

How to fix   Long Method    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
44
45
require_once('include/Dashlets/DashletGenericChart.php');
46
47
class CampaignROIChartDashlet extends DashletGenericChart 
48
{
49
    public $campaign_id;
50
    /**
51
     * @see DashletGenericChart::$_seedName
52
     */
53
    protected $_seedName = 'Campaigns';
54
55
    /**
56
     * @see DashletGenericChart::displayOptions()
57
     */
58
    public function displayOptions()
59
    {
60
        $this->getSeedBean()->disable_row_level_security = false;
61
62
        $campaigns = $this->getSeedBean()->get_full_list("","");
63
        if ( $campaigns != null )
64
            foreach ($campaigns as $c)
65
                $this->_searchFields['campaign_id']['options'][$c->id] = $c->name;
66
        else
67
            $this->_searchFields['campaign_id']['options'] = array();
68
69
        return parent::displayOptions();
70
    }
71
72
    /**
73
     * @see DashletGenericChart::display()
74
     */
75
    public function display()
76
    {
77
        $rawData = $this->constructQuery(
78
            $GLOBALS['app_list_strings']['roi_type_dom'],
79
            $GLOBALS['app_list_strings']['roi_type_dom'],
80
            $this->campaign_id[0],null,true,true,true,$this->id);
81
82
        $currency_symbol = $GLOBALS['sugar_config']['default_currency_symbol'];
83
        if ($GLOBALS['current_user']->getPreference('currency')){
84
85
            $currency = new Currency();
86
            $currency->retrieve($GLOBALS['current_user']->getPreference('currency'));
87
            $currency_symbol = $currency->symbol;
88
        }
89
        $thousands_symbol = translate('LBL_OPP_THOUSANDS', 'Charts');
90
91
        $canvasId = 'rGraphCampaignROI'.uniqid();
92
        $chartWidth     = 900;
93
        $chartHeight    = 500;
94
        $autoRefresh = $this->processAutoRefresh();
95
96
        $chartReadyData = $this->prepareChartData($rawData,$currency_symbol,$thousands_symbol);
97
98
        //$chartReadyData['data'] = [[1.1,2.2],[3.3,4.4]];
99
        $jsonData = json_encode($chartReadyData['data']);
100
        $jsonLabels = json_encode($chartReadyData['labels']);
101
        $jsonLabelsAndValues = json_encode($chartReadyData['labelsAndValues']);
102
103
104
        $jsonKey = json_encode($chartReadyData['key']);
105
        $jsonTooltips = json_encode($chartReadyData['tooltips']);
106
107
        //$colours = "['red','blue','green','orange','yellow','pink']";
108
        $colours = "['#a6cee3','#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a','#ffff99','#b15928']";
109
110
        if(!is_array($chartReadyData['data'])||count($chartReadyData['data']) < 1)
111
        {
112
            return "<h3 class='noGraphDataPoints'>$this->noDataMessage</h3>";
113
        }
114
115
        //<canvas id='$canvasId'  width=canvas.width height=canvas.width class='resizableCanvas'>[No canvas support]</canvas>
116
117
        $chart = <<<EOD
118
        <canvas id='$canvasId' class='resizableCanvas' width='$chartWidth' height='$chartHeight'>[No canvas support]</canvas>
119
             $autoRefresh
120
         <script>
121
           var bar = new RGraph.Bar({
122
            id: '$canvasId',
123
            data:$jsonData,
124
            options: {
125
                //grouping: 'stacked',
126
                colorsSequential:true,
127
                labels: $jsonLabels,
128
                xlabels:true,
129
                labelsAbove: true,
130
                labelsAbovedecimals: 2,
131
                linewidth: 2,
132
                //eventsClick:outcomeByMonthClick,
133
                textSize:10,
134
                //labelsAboveSize:10,
135
                strokestyle: 'white',
136
                //colors: ['Gradient(#4572A7:#66f)','Gradient(#AA4643:white)','Gradient(#89A54E:white)'],
137
                //shadowOffsetx: 1,
138
                //shadowOffsety: 1,
139
                //shadowBlur: 10,
140
                //hmargin: 25,
141
                colors:$colours,
142
                gutterLeft: 80,
143
                //gutterTop:50,
144
                //gutterRight:160,
145
                //gutterBottom: 155,
146
                //textAngle: 45,
147
                backgroundGridVlines: false,
148
                backgroundGridBorder: false,
149
                tooltips:$jsonLabels,
150
                tooltipsEvent:'mousemove',
151
                //key: $jsonKey,
152
                //keyColors: $colours,
153
                //keyPosition: 'gutter',
154
                //keyPositionX: $canvasId.width - 150,
155
                //keyPositionY: 18,
156
                //keyPositionGutterBoxed: true,
157
                axisColor: '#ccc',
158
                unitsPre:'$currency_symbol',
159
                labelsAboveUnitsPre:'$currency_symbol',
160
                //unitsPost:'$thousands_symbol',
161
                tooltipsCssClass: 'rgraph_chart_tooltips_css',
162
                noyaxis: true
163
            }
164
        }).draw();
165
        /*
166
        .on('draw', function (obj)
167
        {
168
            for (var i=0; i<obj.coords.length; ++i) {
169
                obj.context.fillStyle = 'black';
170
                if(obj.data_arr[i] > 0)
171
                {
172
                RGraph.Text2(obj.context, {
173
                    font:'Verdana',
174
                    'size':text_size,
175
                    'x':obj.coords[i][0] + (obj.coords[i][2] / 2),
176
                    'y':obj.coords[i][1] + (obj.coords[i][3] / 2),
177
                    'text':obj.data_arr[i].toString(),
178
                    'valign':'center',
179
                    'halign':'center'
180
                });
181
                }
182
            }
183
        }).draw();
184
185
        bar.canvas.onmouseout = function (e)
186
        {
187
            // Hide the tooltip
188
            RGraph.hideTooltip();
189
190
            // Redraw the canvas so that any highlighting is gone
191
            RGraph.redraw();
192
        }
193
        */
194
/*
195
         var sizeIncrement = new RGraph.Drawing.Text({
196
            id: '$canvasId',
197
            x: 10,
198
            y: 20,
199
            text: 'Amount in ${currency_symbol}',
200
            options: {
201
                font: 'Arial',
202
                bold: true,
203
                //halign: 'left',
204
                //valign: 'bottom',
205
                colors: ['black'],
206
                size: text_size
207
            }
208
        }).draw();
209
*/
210
</script>
211
EOD;
212
        return $chart;
213
214
215
216
        //   return $this->getTitle('<div align="center"></div>') . '<div align="center">' . $returnStr . '</div>'. $this->processAutoRefresh();
217
    }
218
219
    protected function constructQuery($datay= array(),$targets=array(),$campaign_id = null, $cache_file_name='a_file', $refresh=false,$marketing_id='',$is_dashlet=false,$dashlet_id='') {
220
        //global $app_strings,$mod_strings, $current_module_strings, $charset, $lang, $app_list_strings, $current_language,$sugar_config;
221
        global $mod_strings;
222
223
        $campaign_id = (int) $campaign_id;
224
        if(!$campaign_id) {
225
            $GLOBALS['log']->debug('roi chart need a campaign id');
226
            return false;
227
        }
228
229
        $not_empty = false;
230
231
        $chartData = array();
232
233
        $focus = new Campaign();
234
        $focus->retrieve($campaign_id);
235
        $opp_count=0;
236
        $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...
237
        $opp_query .= " from opportunities";
238
        $opp_query .= " where campaign_id='$campaign_id'";
239
        $opp_query .= " and sales_stage='Prospecting'";
240
        $opp_query .= " and deleted=0";
241
242
        $opp_result=$focus->db->query($opp_query);
243
        $opp_data=$focus->db->fetchByAssoc($opp_result);
244
        if (empty($opp_data['total_value'])) $opp_data['total_value']=0;
245
246
        $chartData['Total Value']= $opp_data['total_value'];
247
248
        //report query
249
        $opp_query1  = "select SUM(opp.amount) as revenue";
250
        $opp_query1 .= " from opportunities opp";
251
        $opp_query1 .= " right join campaigns camp on camp.id = opp.campaign_id";
252
        $opp_query1 .= " where opp.sales_stage = 'Closed Won'and camp.id='$campaign_id' and opp.deleted=0";
253
        $opp_query1 .= " group by camp.name";
254
255
        $opp_result1=$focus->db->query($opp_query1);
256
        $opp_data1=$focus->db->fetchByAssoc($opp_result1);
257
258
        //if (empty($opp_data1[]))
259
        if (empty($opp_data1['revenue'])){
260
            $opp_data1[$mod_strings['LBL_ROI_CHART_REVENUE']] = 0;
261
            unset($opp_data1['revenue']);
262
        }else{
263
            $opp_data1[$mod_strings['LBL_ROI_CHART_REVENUE']] = $opp_data1['revenue'];
264
            unset($opp_data1['revenue']);
265
            $not_empty = true;
266
        }
267
268
        $chartData['Revenue']= $opp_data1[$mod_strings['LBL_ROI_CHART_REVENUE']];
269
270
        $camp_query1  = "select camp.name, SUM(camp.actual_cost) as investment,SUM(camp.budget) as budget,SUM(camp.expected_revenue) as expected_revenue";
271
        $camp_query1 .= " from campaigns camp";
272
        $camp_query1 .= " where camp.id='$campaign_id'";
273
        $camp_query1 .= " group by camp.name";
274
275
        $camp_result1=$focus->db->query($camp_query1);
276
        $camp_data1=$focus->db->fetchByAssoc($camp_result1);
277
278
279
        if (empty($camp_data1['investment']))
280
            $camp_data1['investment'] = 0;
281
        else
282
            $not_empty = true;
283
        if (empty($camp_data1['budget']))
284
            $camp_data1['budget'] = 0;
285
        else
286
            $not_empty = true;
287
        if (empty($camp_data1['expected_revenue']))
288
            $camp_data1['expected_revenue'] = 0;
289
        else
290
            $not_empty = true;
291
292
        $chartData['Investment']= $camp_data1['investment'];
293
        $chartData['Budget']= $camp_data1['budget'];
294
        $chartData['Expected Revenue']= $camp_data1['expected_revenue'];
295
296
        /*
297
            $opp_data1[$mod_strings['LBL_ROI_CHART_INVESTMENT']]=$camp_data1['investment'];
298
            $opp_data1[$mod_strings['LBL_ROI_CHART_BUDGET']]=$camp_data1['budget'];
299
            $opp_data1[$mod_strings['LBL_ROI_CHART_EXPECTED_REVENUE']]=$camp_data1['expected_revenue'];
300
301
302
            $query = "SELECT activity_type,target_type, count(*) hits ";
303
            $query.= " FROM campaign_log ";
304
            $query.= " WHERE campaign_id = '$campaign_id' AND archived=0 AND deleted=0";
305
            //if $marketing id is specified, then lets filter the chart by the value
306
            if (!empty($marketing_id)){
307
                $query.= " AND marketing_id ='$marketing_id'";
308
            }
309
            $query.= " GROUP BY  activity_type, target_type";
310
            $query.= " ORDER BY  activity_type, target_type";
311
            $result = $focus->db->query($query);
312
*/
313
        return $chartData;
314
    }
315
316
    protected function prepareChartData($data,$currency_symbol, $thousands_symbol)
317
    {
318
        //Use the  lead_source to categorise the data for the charts
319
        $chart['labels'] = array();
320
        $chart['data'] = array();
321
        //Need to add all elements into the key, as they are stacked (even though the category is not present, the value could be)
322
        $chart['key'] = array();
323
        $chart['tooltips']= array();
324
325
        foreach($data as $key=>$value)
326
        {
327
            $formattedFloat = (float)number_format((float)$value, 2, '.', '');
328
            $chart['labels'][] = $key;
329
            $chart['data'][] = $formattedFloat;
330
            /*
331
            $key = $i["m"];
332
            $stage = $i["sales_stage"];
333
            if(!in_array($key,$chart['labels']))
334
            {
335
                $chart['labels'][] = $key;
336
                $chart['data'][] = array();
337
            }
338
            if(!in_array($stage,$chart['key']))
339
                $chart['key'][] = $stage;
340
341
            $formattedFloat = (float)number_format((float)$i["total"], 2, '.', '');
342
            $chart['data'][count($chart['data'])-1][] = $formattedFloat;
343
            $chart['tooltips'][]="<div><input type='hidden' class='stage' value='$stage'><input type='hidden' class='date' value='$key'></div>".$stage.'('.$currency_symbol.$formattedFloat.$thousands_symbol.') '.$key;
344
            */
345
        }
346
        return $chart;
347
    }
348
}