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-2012 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
38 /*********************************************************************************
40 * Description: returns HTML for client-side image map.
41 ********************************************************************************/
45 require_once('include/charts/Charts.php');
49 class Chart_outcome_by_month
51 var $modules = array('Opportunities');
53 function Chart_outcome_by_month()
58 function draw($extra_tools)
63 global $app_list_strings, $current_language, $sugar_config, $currentModule, $action, $theme;
64 $current_module_strings = return_module_language($current_language, 'Charts');
67 if (isset($_REQUEST['obm_refresh'])) { $refresh = $_REQUEST['obm_refresh']; }
68 else { $refresh = false; }
70 $date_start = array();
72 //get the dates to display
74 $user_date_start = $current_user->getPreference('obm_date_start');
75 if (!empty($user_date_start) && !isset($_REQUEST['obm_date_start'])) {
76 $date_start =$user_date_start;
77 $GLOBALS['log']->debug("USER PREFERENCES['obm_date_start'] is:");
78 $GLOBALS['log']->debug($user_date_start);
80 elseif (isset($_REQUEST['obm_year']) && $_REQUEST['obm_year'] != '') {
81 $date_start = $_REQUEST['obm_year'].'-01-01';
82 $current_user->setPreference('obm_date_start', $date_start);
83 $GLOBALS['log']->debug("_REQUEST['obm_date_start'] is:");
84 $GLOBALS['log']->debug($_REQUEST['obm_date_start']);
85 $GLOBALS['log']->debug("_SESSION['obm_date_start'] is:");
86 $GLOBALS['log']->debug($current_user->getPreference('obm_date_start'));
89 $date_start = date('Y').'-01-01';
91 $user_date_end = $current_user->getPreference('obm_date_end');
92 if (!empty($user_date_end) && !isset($_REQUEST['obm_date_end'])) {
93 $date_end =$user_date_end;
94 $GLOBALS['log']->debug("USER PREFERENCES['obm_date_end'] is:");
95 $GLOBALS['log']->debug($date_end);
97 elseif (isset($_REQUEST['obm_year']) && $_REQUEST['obm_year'] != '') {
98 $date_end = $_REQUEST['obm_year'].'-12-31';
99 $current_user->setPreference('obm_date_end', $date_end );
100 $GLOBALS['log']->debug("_REQUEST['obm_date_end'] is:");
101 $GLOBALS['log']->debug($_REQUEST['obm_date_end']);
102 $GLOBALS['log']->debug("USER PREFERENCES['obm_date_end'] is:");
103 $GLOBALS['log']->debug($current_user->getPreference('obm_date_end'));
106 $date_end = date('Y').'-12-31';
110 //get list of user ids for which to display data
111 $user_ids = $current_user->getPreference('obm_ids');
112 if (!empty($user_ids) && count($user_ids) != 0 && !isset($_REQUEST['obm_ids'])) {
114 $GLOBALS['log']->debug("USER PREFERENCES['obm_ids'] is:");
115 $GLOBALS['log']->debug($user_ids);
117 elseif (isset($_REQUEST['obm_ids']) && count($_REQUEST['obm_ids']) > 0) {
118 $ids = $_REQUEST['obm_ids'];
119 $current_user->setPreference('obm_ids', $_REQUEST['obm_ids']);
120 $GLOBALS['log']->debug("_REQUEST['obm_ids'] is:");
121 $GLOBALS['log']->debug($_REQUEST['obm_ids']);
122 $GLOBALS['log']->debug("USER PREFRENCES['obm_ids'] is:");
123 $GLOBALS['log']->debug($current_user->getPreference('obm_ids'));
126 $ids = get_user_array(false);
127 $ids = array_keys($ids);
130 //create unique prefix based on selected users for image files
134 $id_hash = crc32(implode('',$ids));
137 $id_hash = $id_hash * -1;
140 $GLOBALS['log']->debug("ids is:");
141 $GLOBALS['log']->debug($ids);
142 $id_md5 = substr(md5($current_user->id),0,9);
145 // cn: format date_start|end to user's preferred
147 $dateDisplayStart = strftime($timedate->get_user_date_format(), strtotime($date_start));
148 $dateDisplayEnd = strftime($timedate->get_user_date_format(), strtotime($date_end));
149 $seps = array("-", "/");
150 $dates = array($date_start, $date_end);
151 $dateFileNameSafe = str_replace($seps, "_", $dates);
153 $cache_file_name = sugar_cached("xml/").$current_user->getUserPrivGuid()."_outcome_by_month_".$dateFileNameSafe[0]."_".$dateFileNameSafe[1].".xml";
155 $GLOBALS['log']->debug("cache file name is: $cache_file_name");
159 $tools='<div align="right"><a href="index.php?module='.$currentModule.'&action='. $action .'&obm_refresh=true" class="tabFormAdvLink">'.SugarThemeRegistry::current()->getImage('refresh','border="0" align="absmiddle"', null,null,'.gif',$mod_strings['LBL_REFRESH']).' '.$current_module_strings['LBL_REFRESH'].'</a> <a href="javascript: toggleDisplay(\'outcome_by_month_edit\');" class="tabFormAdvLink">'.SugarThemeRegistry::current()->getImage('edit','border="0" align="absmiddle"',null,null,'.gif',$mod_strings['LBL_EDIT']).' '. $current_module_strings['LBL_EDIT'].'</a> '.$extra_tools.'</div>';
161 <?php echo '<span onmouseover="this.style.cursor=\'move\'" id="chart_handle_' . $this->order . '">' . get_form_header($current_module_strings['LBL_YEAR_BY_OUTCOME'],$tools,false) . '</span>';?>
165 $cal_dateformat = parse_calendardate($app_strings['NTC_DATE_FORMAT']);
167 if (empty($_SESSION['obm_ids'])) $_SESSION['obm_ids'] = "";
170 <div id='outcome_by_month_edit' style='display: none;'>
171 <form name="outcome_by_month" action="index.php" method="post" >
172 <input type="hidden" name="module" value="<?php echo $currentModule;?>">
173 <input type="hidden" name="action" value="<?php echo $action;?>">
174 <input type="hidden" name="obm_refresh" value="true">
175 <input type="hidden" name="obm_date_start" value="<?php if (isset($_SESSION['obm_date_start'])) echo $_SESSION['obm_date_start']?>">
176 <input type="hidden" name="obm_date_end" value="<?php if (isset($_SESSION['obm_date_end'])) echo $_SESSION['obm_date_end']?>">
177 <table cellpadding="0" cellspacing="0" border="0" class="edit view" align="center">
179 <td valign='top' nowrap ><b><?php echo $current_module_strings['LBL_YEAR']?></b><br><span class="dateFormat"><?php echo $app_strings['NTC_YEAR_FORMAT']?></span></td>
180 <td valign='top' ><input class="text" name="obm_year" size='12' maxlength='10' id='obm_year' value='<?php if (isset($date_start)) echo substr($date_start,0,4)?>'> </td>
181 <td valign='top'><b><?php echo $current_module_strings['LBL_USERS'];?></b></td>
182 <td valign='top'><select name="obm_ids[]" multiple size='3'><?php echo get_select_options_with_id(get_user_array(false),$ids); ?></select></td>
183 <td align="right" valign="top"><input class="button" onclick="return verify_chart_data_outcome_by_month();" type="submit" title="<?php echo $app_strings['LBL_SELECT_BUTTON_TITLE']; ?>" value="<?php echo $app_strings['LBL_SELECT_BUTTON_LABEL']?>" /><input class="button" onClick="javascript: toggleDisplay('outcome_by_month_edit');" type="button" title="<?php echo $app_strings['LBL_CANCEL_BUTTON_TITLE']; ?>" accessKey="<?php echo $app_strings['LBL_CANCEL_BUTTON_KEY'];?>" value="<?php echo $app_strings['LBL_CANCEL_BUTTON_LABEL']?>"/></td>
192 echo "<p align='center'>".$this->gen_xml($date_start, $date_end, $ids, $cache_file_name, $refresh,$current_module_strings)."</p>";
193 echo "<P align='center'><span class='chartFootnote'>".$current_module_strings['LBL_MONTH_BY_OUTCOME_DESC']."</span></P>";
201 if (file_exists($cache_file_name)) {
202 $file_date = $timedate->asUser($timedate->fromTimestamp(filemtime($cache_file_name)));
209 <span class='chartFootnote'>
210 <p align="right"><i><?php echo $current_module_strings['LBL_CREATED_ON'].' '.$file_date; ?></i></p>
213 echo get_validate_chart_js();
218 * Creates opportunity pipeline image as a VERTICAL accumlated bar graph for multiple users.
219 * param $datax- the month data to display in the x-axis
220 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
221 * All Rights Reserved..
222 * Contributor(s): ______________________________________..
224 function gen_xml($date_start='1971-10-15', $date_end='2010-10-15', $user_id=array('1'), $cache_file_name='a_file', $refresh=false,$current_module_strings) {
225 global $app_strings, $app_list_strings, $charset, $lang, $barChartColors, $current_user;
227 $kDelim = $current_user->getPreference('num_grp_sep');
230 if (!file_exists($cache_file_name) || $refresh == true) {
231 $GLOBALS['log']->debug("date_start is: $date_start");
232 $GLOBALS['log']->debug("date_end is: $date_end");
233 $GLOBALS['log']->debug("user_id is: ");
234 $GLOBALS['log']->debug($user_id);
235 $GLOBALS['log']->debug("cache_file_name is: $cache_file_name");
238 //build the where clause for the query that matches $user
239 $count = count($user_id);
242 foreach ($user_id as $the_id) {
243 $id[] = "'".$the_id."'";
245 $ids = join(",",$id);
246 $where .= "opportunities.assigned_user_id IN ($ids) ";
250 // cn: adding user-pref date handling
251 $dateStartDisplay = $timedate->asUserDate($timedate->fromString($date_start));
252 $dateEndDisplay = $timedate->asUserDate($timedate->fromString($date_end));
254 $opp = new Opportunity();
255 //build the where clause for the query that matches $date_start and $date_end
256 $where .= "AND opportunities.date_closed >= ".db_convert("'".$date_start."'",'date')." AND opportunities.date_closed <= ".db_convert("'".$date_end."'",'date')." AND opportunities.deleted=0";
257 $query = "SELECT sales_stage,".db_convert('opportunities.date_closed','date_format',array("'%Y-%m'"),array("'YYYY-MM'"))." as m, sum(amount_usdollar/1000) as total, count(*) as opp_count FROM opportunities ";
258 $query .= "WHERE ".$where;
259 $query .= " GROUP BY sales_stage,".db_convert('opportunities.date_closed','date_format',array("'%Y-%m'"),array("'YYYY-MM'"))."ORDER BY m";
260 //Now do the db queries
261 //query for opportunity data that matches $datay and $user
264 $result = $opp->db->query($query, true);
265 //build pipeline by sales stage data
268 global $sugar_config;
269 $symbol = $sugar_config['default_currency_symbol'];
270 $other = $current_module_strings['LBL_LEAD_SOURCE_OTHER'];
271 $rowTotalArr = array();
273 global $current_user;
274 $salesStages = array("Closed Lost"=>$app_list_strings['sales_stage_dom']["Closed Lost"],"Closed Won"=>$app_list_strings['sales_stage_dom']["Closed Won"],"Other"=>$other);
275 if($current_user->getPreference('currency') ){
277 $currency = new Currency();
278 $currency->retrieve($current_user->getPreference('currency'));
279 $div = $currency->conversion_rate;
280 $symbol = $currency->symbol;
284 while($row = $opp->db->fetchByAssoc($result, false))
286 if($row['total']*$div<=100){
287 $sum = round($row['total']*$div, 2);
289 $sum = round($row['total']*$div);
291 if($row['sales_stage'] == 'Closed Won' || $row['sales_stage'] == 'Closed Lost'){
292 $salesStage = $row['sales_stage'];
293 $salesStageT = $app_list_strings['sales_stage_dom'][$row['sales_stage']];
295 $salesStage = "Other";
296 $salesStageT = $other;
299 $months[$row['m']] = $row['m'];
300 if(!isset($monthArr[$row['m']]['row_total'])) {$monthArr[$row['m']]['row_total']=0;}
301 $monthArr[$row['m']][$salesStage]['opp_count'][] = $row['opp_count'];
302 $monthArr[$row['m']][$salesStage]['total'][] = $sum;
303 $monthArr[$row['m']]['outcome'][$salesStage]=$salesStageT;
304 $monthArr[$row['m']]['row_total'] += $sum;
309 $fileContents = ' <xData length="20">'."\n";
310 if (!empty($months)) {
311 foreach ($months as $month){
312 $rowTotalArr[]=$monthArr[$month]['row_total'];
313 if($monthArr[$month]['row_total']>100)
315 $monthArr[$month]['row_total']=round($monthArr[$month]['row_total']);
317 $fileContents .= ' <dataRow title="'.$month.'" endLabel="'.currency_format_number($monthArr[$month]['row_total'], array('currency_symbol' => true)).'">'."\n";
318 arsort($salesStages);
319 foreach ($salesStages as $outcome=>$outcome_translation){
320 if(isset($monthArr[$month][$outcome])) {
321 $fileContents .= ' <bar id="'.$outcome.'" totalSize="'.array_sum($monthArr[$month][$outcome]['total']).'" altText="'.$month.': '.format_number(array_sum($monthArr[$month][$outcome]['opp_count']), 0, 0).' '.$current_module_strings['LBL_OPPS_WORTH'].' '.currency_format_number(array_sum($monthArr[$month][$outcome]['total']),array('currency_symbol' => true)).$current_module_strings['LBL_OPP_THOUSANDS'].' '.$current_module_strings['LBL_OPPS_OUTCOME'].' '.$outcome_translation.'" url="index.php?module=Opportunities&action=index&date_closed='.$month.'&sales_stage='.urlencode($outcome).'&query=true&searchFormTab=advanced_search"/>'."\n";
324 $fileContents .= ' </dataRow>'."\n";
327 $fileContents .= ' <dataRow title="" endLabel="">'."\n";
328 $fileContents .= ' <bar id="" totalSize="0" altText="" url=""/>'."\n";
329 $fileContents .= ' </dataRow>'."\n";
330 $rowTotalArr[] = 1000;
332 $fileContents .= ' </xData>'."\n";
333 $max = get_max($rowTotalArr);
334 $fileContents .= ' <yData min="0" max="'.$max.'" length="10" prefix="'.$symbol.'" suffix="" kDelim="'.$kDelim.'" defaultAltText="'.$current_module_strings['LBL_ROLLOVER_DETAILS'].'"/>'."\n";
335 $fileContents .= ' <colorLegend status="on">'."\n";
338 foreach ($salesStages as $outcome=>$outcome_translation) {
339 $color = generate_graphcolor($outcome,$i);
340 $fileContents .= ' <mapping id="'.$outcome.'" name="'.$outcome_translation.'" color="'.$color.'"/>'."\n";
343 $fileContents .= ' </colorLegend>'."\n";
344 $fileContents .= ' <graphInfo>'."\n";
345 $fileContents .= ' <![CDATA['.$current_module_strings['LBL_DATE_RANGE']." ".$dateStartDisplay." ".$current_module_strings['LBL_DATE_RANGE_TO']." ".$dateEndDisplay."<br/>".$current_module_strings['LBL_OPP_SIZE'].' '.$symbol.'1'.$current_module_strings['LBL_OPP_THOUSANDS'].']]>'."\n";
346 $fileContents .= ' </graphInfo>'."\n";
347 $fileContents .= ' <chartColors ';
348 foreach ($barChartColors as $key => $value) {
349 $fileContents .= ' '.$key.'='.'"'.$value.'" ';
351 $fileContents .= ' />'."\n";
352 $fileContents .= '</graphData>'."\n";
353 $total = round($total, 2);
354 $title = '<graphData title="'.$current_module_strings['LBL_TOTAL_PIPELINE'].currency_format_number($total, array('currency_symbol' => true)).$app_strings['LBL_THOUSANDS_SYMBOL'].'">'."\n";
355 $fileContents = $title.$fileContents;
357 //echo $fileContents;
358 save_xml_file($cache_file_name, $fileContents);
360 $return = create_chart('vBarF',$cache_file_name);
365 function constructQuery(){
366 global $current_user;
369 $user_date_start = $current_user->getPreference('obm_date_start');
370 if (!empty($user_date_start) && !isset($_REQUEST['obm_date_start'])) {
371 $date_start =$user_date_start;
372 $GLOBALS['log']->debug("USER PREFERENCES['obm_date_start'] is:");
373 $GLOBALS['log']->debug($user_date_start);
375 elseif (isset($_REQUEST['obm_year']) && $_REQUEST['obm_year'] != '') {
376 $date_start = $_REQUEST['obm_year'].'-01-01';
377 $current_user->setPreference('obm_date_start', $date_start);
378 $GLOBALS['log']->debug("_REQUEST['obm_date_start'] is:");
379 $GLOBALS['log']->debug($_REQUEST['obm_date_start']);
380 $GLOBALS['log']->debug("_SESSION['obm_date_start'] is:");
381 $GLOBALS['log']->debug($current_user->getPreference('obm_date_start'));
384 $date_start = date('Y').'-01-01';
386 $user_date_end = $current_user->getPreference('obm_date_end');
387 if (!empty($user_date_end) && !isset($_REQUEST['obm_date_end'])) {
388 $date_end =$user_date_end;
389 $GLOBALS['log']->debug("USER PREFERENCES['obm_date_end'] is:");
390 $GLOBALS['log']->debug($date_end);
392 elseif (isset($_REQUEST['obm_year']) && $_REQUEST['obm_year'] != '') {
393 $date_end = $_REQUEST['obm_year'].'-12-31';
394 $current_user->setPreference('obm_date_end', $date_end );
395 $GLOBALS['log']->debug("_REQUEST['obm_date_end'] is:");
396 $GLOBALS['log']->debug($_REQUEST['obm_date_end']);
397 $GLOBALS['log']->debug("USER PREFERENCES['obm_date_end'] is:");
398 $GLOBALS['log']->debug($current_user->getPreference('obm_date_end'));
401 $date_end = date('Y').'-12-31';
405 //get list of user ids for which to display data
406 $user_ids = $current_user->getPreference('obm_ids');
407 if (!empty($user_ids) && count($user_ids) != 0 && !isset($_REQUEST['obm_ids'])) {
409 $GLOBALS['log']->debug("USER PREFERENCES['obm_ids'] is:");
410 $GLOBALS['log']->debug($user_ids);
412 elseif (isset($_REQUEST['obm_ids']) && count($_REQUEST['obm_ids']) > 0) {
413 $ids = $_REQUEST['obm_ids'];
414 $current_user->setPreference('obm_ids', $_REQUEST['obm_ids']);
415 $GLOBALS['log']->debug("_REQUEST['obm_ids'] is:");
416 $GLOBALS['log']->debug($_REQUEST['obm_ids']);
417 $GLOBALS['log']->debug("USER PREFRENCES['obm_ids'] is:");
418 $GLOBALS['log']->debug($current_user->getPreference('obm_ids'));
421 $ids = get_user_array(false);
422 $ids = array_keys($ids);
428 //build the where clause for the query that matches $user
429 $count = count($user_id);
432 foreach ($user_id as $the_id) {
433 $id[] = "'".$the_id."'";
435 $ids = join(",",$id);
436 $where .= "opportunities.assigned_user_id IN ($ids) ";
440 // cn: adding user-pref date handling
441 $dateStartDisplay = $timedate->asUserDate($timedate->fromString($date_start));
442 $dateEndDisplay = $timedate->asUserDate($timedate->fromString($date_end));
444 $opp = new Opportunity();
445 //build the where clause for the query that matches $date_start and $date_end
446 $where .= "AND opportunities.date_closed >= ".db_convert("'".$date_start."'",'date')." AND opportunities.date_closed <= ".db_convert("'".$date_end."'",'date')." AND opportunities.deleted=0";
447 $query = "SELECT sales_stage,".db_convert('opportunities.date_closed','date_format',array("'%Y-%m'"),array("'YYYY-MM'"))." as m, sum(amount_usdollar/1000) as total, count(*) as opp_count FROM opportunities ";
448 $query .= "WHERE ".$where;
449 $query .= " GROUP BY sales_stage,".db_convert('opportunities.date_closed','date_format',array("'%Y-%m'"),array("'YYYY-MM'"))."ORDER BY m";
453 function constructGroupBy(){
454 return array( 'm', 'sales_stage', );