Example #1
0
 function populateLineItems()
 {
     global $app_strings, $mod_strings;
     $sql = "SELECT * FROM aos_products_quotes WHERE parent_type = 'AOS_Quotes' AND parent_id = '" . $this->bean->id . "' AND deleted = 0";
     $result = $this->bean->db->query($sql);
     $html = "";
     $html .= "<div style='width:1000px;'><table border='0' width='100%' cellpadding='0' cellspacing='0'>";
     $html .= "<tr>";
     $html .= "<td width='2%' class='tabDetailViewDL' style='text-align: left;'>&nbsp;</td>";
     $html .= "<td width='15%' class='tabDetailViewDL' style='text-align: left;'>" . $mod_strings['LBL_PRODUCT_NAME'] . "</td>";
     $html .= "<td width='5%' class='tabDetailViewDL' style='text-align: left;'>Asset</td>";
     $html .= "<td width='5%' class='tabDetailViewDL' style='text-align: left;'>" . $mod_strings['LBL_UNIT_PRICE'] . "</td>";
     $html .= "<td width='5%' class='tabDetailViewDL' style='text-align: left;'>Rate</td>";
     $html .= "<td width='5%' class='tabDetailViewDL' style='text-align: left;'>Start Date</td>";
     $html .= "<td width='5%' class='tabDetailViewDL' style='text-align: left;'>Stop Date</td>";
     $html .= "<td width='20%' class='tabDetailViewDL' style='text-align: left;'>Notes</td>";
     $html .= "</tr>";
     $i = 1;
     while ($row = $this->bean->db->fetchByAssoc($result)) {
         $html .= "<tr>";
         $product_note = wordwrap($row['description'], 40, "<br />\n");
         $product_note2 = wordwrap($row['description2'], 40, "<br />\n");
         $html .= "<td class='tabDetailViewDF'>" . $i++ . "</td>";
         $html .= "<td class='tabDetailViewDF'><a href='index.php?module=AOS_Products&action=DetailView&record=" . $row['product_id'] . "' class='tabDetailViewDFLink'>" . $row['name'] . "</a></td>";
         $html .= "<td class='tabDetailViewDF'>" . $product_note . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . currency_format_number($row['product_unit_price']) . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . $row['product_rate'] . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . $row['start_date'] . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . $row['stop_date'] . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . $product_note2 . "</td>";
         $html .= "</tr>";
     }
     $html .= "</table></div>";
     $this->ss->assign('LINE_ITEMS', $html);
 }
Example #2
0
 function populateLineItems()
 {
     global $app_strings, $mod_strings;
     $sql = "SELECT * FROM aos_products_quotes WHERE parent_type = 'AOS_Invoices' AND parent_id = '" . $this->bean->id . "' AND deleted = 0";
     $result = $this->bean->db->query($sql);
     $html = "";
     $html .= "<table border='0' width='100%' cellpadding='0' cellspacing='0'>";
     $html .= "<tr>";
     $html .= "<td width='10%' class='tabDetailViewDL' style='text-align: left;'>&nbsp;</td>";
     $html .= "<td width='10%' class='tabDetailViewDL' style='text-align: left;'>" . $mod_strings['LBL_PRODUCT_QUANITY'] . "</td>";
     $html .= "<td width='15%' class='tabDetailViewDL' style='text-align: left;'>" . $mod_strings['LBL_PRODUCT_NAME'] . "</td>";
     $html .= "<td width='15%' class='tabDetailViewDL' style='text-align: left;'>" . $mod_strings['LBL_LIST_PRICE'] . "</td>";
     $html .= "<td width='15%' class='tabDetailViewDL' style='text-align: left;'>" . $mod_strings['LBL_UNIT_PRICE'] . "</td>";
     $html .= "<td width='15%' class='tabDetailViewDL' style='text-align: left;'>" . $mod_strings['LBL_VAT'] . " %</td>";
     $html .= "<td width='15%' class='tabDetailViewDL' style='text-align: left;'>" . $mod_strings['LBL_VAT_AMT'] . "</td>";
     $html .= "<td width='15%' class='tabDetailViewDL' style='text-align: left;'>" . $mod_strings['LBL_TOTAL_PRICE'] . "</td>";
     $html .= "</tr>";
     $i = 1;
     while ($row = $this->bean->db->fetchByAssoc($result)) {
         $html .= "<tr>";
         $product_note = wordwrap($row['description'], 40, "<br />\n");
         $html .= "<td class='tabDetailViewDF'>" . $i++ . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . number_format($row['product_qty']) . "</td>";
         $html .= "<td class='tabDetailViewDF'><a href='index.php?module=AOS_Products&action=DetailView&record=" . $row['product_id'] . "' class='tabDetailViewDFLink'>" . $row['name'] . "</a><br />" . $product_note . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . currency_format_number($row['product_list_price']) . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . currency_format_number($row['product_unit_price']) . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . $row['vat'] . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . currency_format_number($row['vat_amt']) . "</td>";
         $html .= "<td class='tabDetailViewDF'>" . currency_format_number($row['product_total_price']) . "</td>";
         $html .= "</tr>";
     }
     $html .= "</table>";
     $this->ss->assign('LINE_ITEMS', $html);
 }
Example #3
0
 function listViewProcess()
 {
     $this->processSearchForm();
     $this->lv->searchColumns = $this->searchForm->searchColumns;
     if (!$this->headers) {
         return;
     }
     if (empty($_REQUEST['search_form_only']) || $_REQUEST['search_form_only'] == false) {
         $this->lv->setup($this->seed, 'modules/Contracts/tpls/ListViewGeneric.tpl', $this->where, $this->params);
         $savedSearchName = empty($_REQUEST['saved_search_select_name']) ? '' : ' - ' . $_REQUEST['saved_search_select_name'];
         echo get_form_header($GLOBALS['mod_strings']['LBL_LIST_FORM_TITLE'] . $savedSearchName, '', false);
         /**
          * added by Hoc Bui
          *
          * @var OpportunitiesViewList
          */
         $filter_fields = array();
         $orderBy = "";
         $ret_array = $this->seed->create_new_list_query($orderBy, $this->where, $filter_fields, $this->params, 0, '', true, $this->seed, true);
         $main_query = $ret_array['select'] . $params['custom_select'] . $ret_array['from'] . $params['custom_from'] . $ret_array['inner_join'] . $ret_array['where'] . $params['custom_where'] . $ret_array['order_by'] . $params['custom_order_by'];
         //print_r($ret_array);
         //exit;
         /*$query = "SELECT amount_usdollar,amount, deleted FROM opportunities " ;
           if($this->where)
           $query .= "WHERE ".$this->where;*/
         global $db;
         $result = $db->query($main_query);
         $i = 0;
         $total = 0;
         while (($row = $db->fetchByAssoc($result)) != null) {
             if ($row['deleted'] != 1) {
                 $total += $row['tongtien'];
             }
             $i++;
         }
         // $this->lv->ss->assign("total", currency_format_number($GLOBALS['ESCOppAmount'])) ;
         $this->lv->ss->assign("total", currency_format_number($total));
         /**
          * end Hoc Bui
          *
          * @var OpportunitiesViewList
          */
         echo $this->lv->display();
         //echo currency_format_number($GLOBALS['ESCOppAmount']);
     }
 }
Example #4
0
 function get_list_view_data()
 {
     global $action;
     if (isset($this->currency_id) && ($action == 'DetailView' || $action == "SubPanelViewer")) {
         global $locale, $current_language, $current_user, $mod_strings, $app_list_strings, $sugar_config;
         $app_strings = return_application_language($current_language);
         $params = array();
         $temp_array = $this->get_list_view_array();
         $params = array('currency_id' => $this->currency_id, 'convert' => true);
         foreach ($temp_array as $field => $value) {
             $fieldLow = strToLower($field);
             if (!empty($this->field_defs[$fieldLow]) && $this->field_defs[$fieldLow]['type'] == 'currency') {
                 $temp_array[$field] = currency_format_number($this->{$fieldLow}, $params);
             }
         }
         return $temp_array;
     } else {
         return parent::get_list_view_data();
     }
 }
/**
 * Smarty {sugar_currency_format} function plugin
 *
 * Type:     function<br>
 * Name:     sugar_currency_format<br>
 * Purpose:  formats a number
 * 
 * @author Wayne Pan {wayne at sugarcrm.com}
 * @param array
 * @param Smarty
 */
function smarty_function_sugar_currency_format($params, &$smarty)
{
    if (!isset($params['var']) || $params['var'] == '') {
        return '';
    }
    global $locale;
    if (empty($params['currency_id'])) {
        $params['currency_id'] = $locale->getPrecedentPreference('currency');
        if (!isset($params['convert'])) {
            $params['convert'] = true;
        }
        if (!isset($params['currency_symbol'])) {
            $params['currency_symbol'] = $locale->getPrecedentPreference('default_currency_symbol');
        }
    }
    $_contents = currency_format_number($params['var'], $params);
    if (!empty($params['assign'])) {
        $smarty->assign($params['assign'], $_contents);
    } else {
        return $_contents;
    }
}
Example #6
0
function get_discount_string($type, $amount, $params, $locale, $sep)
{
    if ($amount != '' && $amount != '0.00') {
        if ($type == 'Amount') {
            return currency_format_number($amount, $params) . "</td>";
        } else {
            if ($locale->getPrecision()) {
                return rtrim(rtrim(format_number($amount), '0'), $sep[1]) . "%";
            } else {
                return format_number($amount) . "%";
            }
        }
    } else {
        return "-";
    }
}
Example #7
0
 private static function formatResultSetRows($reportId, $dashletId, $resulsetFields, &$rowValues, $userDateFormat, $userDateTimeFormat, $userTZ, $currencyId, $gmtDates, $isGroupedReport, $auditedReport, $auditedAppliedFields, $auditedFieldType, $referenceAlias)
 {
     global $timedate;
     foreach ($resulsetFields as &$fieldDef) {
         $isTotal = !$isGroupedReport && $fieldDef['function'] !== '0';
         if (!$isTotal) {
             $oldType = $fieldDef['type'];
             $formatType = !empty($fieldDef['format']['type']) ? $fieldDef['format']['type'] : (!empty($fieldDef['type']) ? $fieldDef['type'] : "");
             $currentUnformattedValue = $rowValues[$fieldDef['alias']];
             if ($auditedReport && in_array($fieldDef['field'], $auditedAppliedFields)) {
                 $formatType = $auditedFieldType;
             }
             if (in_array($formatType, array("enum", "radioenum"))) {
                 $rowValues[$fieldDef['alias']] = !isset($fieldDef['enumLabels'][$currentUnformattedValue]) ? $currentUnformattedValue : $fieldDef['enumLabels'][$currentUnformattedValue];
             } else {
                 if ($formatType == "multienum") {
                     $multiEnumValues = explode(',', $currentUnformattedValue);
                     foreach ($multiEnumValues as &$multiEnumValue) {
                         $multiEnumValue = trim($multiEnumValue, '^');
                         $multiEnumValue = !isset($fieldDef['enumLabels'][$multiEnumValue]) ? $multiEnumValue : $fieldDef['enumLabels'][$multiEnumValue];
                     }
                     $rowValues[$fieldDef['alias']] = implode(', ', $multiEnumValues);
                 } else {
                     if ($formatType == "date") {
                         if ($currentUnformattedValue != "" && date('Y-m-d H:i:s', strtotime($currentUnformattedValue)) == $currentUnformattedValue) {
                             if ($gmtDates && in_array($oldType, array("datetime", "datetimecombo"))) {
                                 $currentUnformattedValue = $timedate->handle_offset($currentUnformattedValue, $timedate->get_db_date_time_format(), true, null, $userTZ);
                             }
                             $currentUnformattedValue = date('Y-m-d', strtotime($currentUnformattedValue));
                         }
                         if ($currentUnformattedValue != "" && date('Y-m-d', strtotime($currentUnformattedValue)) == $currentUnformattedValue) {
                             $rowValues[$fieldDef['alias']] = $timedate->swap_formats($currentUnformattedValue, $GLOBALS['timedate']->dbDayFormat, $userDateFormat);
                         }
                     } else {
                         if (in_array($formatType, array("datetime", "datetimecombo"))) {
                             if ($currentUnformattedValue != "" && date('Y-m-d H:i:s', strtotime($currentUnformattedValue)) == $currentUnformattedValue) {
                                 if ($gmtDates) {
                                     $rowValues[$fieldDef['alias']] = $timedate->handle_offset($currentUnformattedValue, $timedate->get_db_date_time_format(), true, null, $userTZ);
                                 }
                                 $rowValues[$fieldDef['alias']] = $timedate->swap_formats($rowValues[$fieldDef['alias']], $timedate->get_db_date_time_format(), $userDateTimeFormat);
                             }
                         } else {
                             if ($formatType == "timestamp") {
                                 if ($currentUnformattedValue != "" && date('Y-m-d H:i:s', strtotime($currentUnformattedValue)) == $currentUnformattedValue) {
                                     $rowValues[$fieldDef['alias']] = $timedate->swap_formats($currentUnformattedValue, $timedate->get_db_date_time_format(), $userDateTimeFormat);
                                 }
                             } else {
                                 if ($formatType == "int") {
                                     //***********************//
                                     //***AlineaSol Premium***//
                                     //***********************//
                                     $extraParams = array('numericValue' => $currentUnformattedValue, 'extraFormat' => $fieldDef['format']['extra']);
                                     $returnedPremiumNumeric = asol_ReportsUtils::managePremiumFeature("reportPercentFormat", "reportFunctions.php", "getReportNumericField", $extraParams);
                                     $rowValues[$fieldDef['alias']] = $returnedPremiumNumeric !== false ? $returnedPremiumNumeric : $currentUnformattedValue;
                                     //***********************//
                                     //***AlineaSol Premium***//
                                     //***********************//
                                 } else {
                                     if ($formatType == "currency") {
                                         $params = array('currency_id' => $currencyId, 'convert' => false);
                                         $rowValues[$fieldDef['alias']] = currency_format_number($currentUnformattedValue, $params);
                                     } else {
                                         if (in_array($formatType, array("decimal", "double"))) {
                                             if (!empty($currentUnformattedValue)) {
                                                 $rowValues[$fieldDef['alias']] = format_number($currentUnformattedValue);
                                             } else {
                                                 if ($currentUnformattedValue !== null) {
                                                     $rowValues[$fieldDef['alias']] = format_number(0);
                                                 } else {
                                                     $rowValues[$fieldDef['alias']] = 0;
                                                 }
                                             }
                                             //***********************//
                                             //***AlineaSol Premium***//
                                             //***********************//
                                             $extraParams = array('numericValue' => $rowValues[$fieldDef['alias']], 'extraFormat' => $fieldDef['format']['extra']);
                                             $returnedPremiumNumeric = asol_ReportsUtils::managePremiumFeature("reportPercentFormat", "reportFunctions.php", "getReportNumericField", $extraParams);
                                             $rowValues[$fieldDef['alias']] = $returnedPremiumNumeric !== false ? $returnedPremiumNumeric : $rowValues[$fieldDef['alias']];
                                             //***********************//
                                             //***AlineaSol Premium***//
                                             //***********************//
                                         } else {
                                             if ($formatType == "percent") {
                                                 $rowValues[$fieldDef['alias']] = !empty($currentUnformattedValue) ? $currentUnformattedValue : 0;
                                                 $numericValue = $rowValues[$fieldDef['alias']] * 100;
                                                 //***********************//
                                                 //***AlineaSol Premium***//
                                                 //***********************//
                                                 $extraParams = array('numericValue' => $numericValue, 'extraFormat' => $fieldDef['format']['extra']);
                                                 $returnedPremiumPercent = asol_ReportsUtils::managePremiumFeature("reportPercentFormat", "reportFunctions.php", "getReportPercentField", $extraParams);
                                                 $rowValues[$fieldDef['alias']] = $returnedPremiumPercent !== false ? $returnedPremiumPercent : $numericValue . '%';
                                                 //***********************//
                                                 //***AlineaSol Premium***//
                                                 //***********************//
                                             } else {
                                                 if ($formatType == "bool") {
                                                     $rowValues[$fieldDef['alias']] = '<input type="checkbox" ' . (!empty($currentUnformattedValue) ? 'checked=""' : '') . ' disabled="true" class="checkbox">';
                                                 } else {
                                                     if ($formatType == "button") {
                                                         //***********************//
                                                         //***AlineaSol Premium***//
                                                         //***********************//
                                                         $extraParams = array('reportId' => $reportId, 'currentLabel' => $fieldDef['alias'], 'currentValue' => $currentUnformattedValue, 'currentRef' => $dashletId, 'extraFormat' => $fieldDef['format']['extra'], 'referenceAlias' => $referenceAlias, 'currentRow' => $rowValues);
                                                         $returnedPremiumButton = asol_ReportsUtils::managePremiumFeature("reportButtonFormat", "reportFunctions.php", "getReportButtonField", $extraParams);
                                                         $rowValues[$fieldDef['alias']] = $returnedPremiumButton !== false ? $returnedPremiumButton : '';
                                                         //***********************//
                                                         //***AlineaSol Premium***//
                                                         //***********************//
                                                     } else {
                                                         $rowValues[$fieldDef['alias']] = $currentUnformattedValue;
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             if (in_array($fieldDef['grouping'], array("Minute Detail", "Quarter Hour Detail", "Hour Detail", "Day Detail", "DoW Detail", "WoY Detail", "Month Detail", "Natural Quarter Detail", "Fiscal Quarter Detail", "Natural Year Detail", "Fiscal Year Detail"))) {
                 $rowValues[$fieldDef['alias']] = self::formatDateSpecialsGroup($reportId, $dashletId, $rowValues[$fieldDef['alias']], $fieldDef, $userDateFormat, $userTZ, $currencyId, $gmtDates);
             }
             //***HTML Entities Decoding
             $rowValues[$fieldDef['alias']] = html_entity_decode($rowValues[$fieldDef['alias']]);
             //***HTML Entities Decoding
         }
     }
 }
 function get_list_view_data()
 {
     global $locale, $current_language, $current_user, $mod_strings, $app_list_strings, $sugar_config;
     $app_strings = return_application_language($current_language);
     require_once 'modules/Currencies/Currency.php';
     $temp_array = $this->get_list_view_array();
     $temp_array['SALES_STAGE'] = empty($temp_array['SALES_STAGE']) ? '' : $temp_array['SALES_STAGE'];
     $temp_array['AMOUNT'] = currency_format_number($this->amount);
     $temp_array["ENCODED_NAME"] = $this->name;
     return $temp_array;
 }
 function parse_template_bean($string, $key, &$focus)
 {
     global $app_strings;
     $repl_arr = array();
     foreach ($focus->field_defs as $field_def) {
         if ($field_def['type'] == 'currency') {
             $repl_arr[$key . "_" . $field_def['name']] = currency_format_number($focus->{$field_def}['name'], $params = array('currency_symbol' => false));
         } else {
             if ($field_def['type'] == 'enum' && isset($field_def['options'])) {
                 $repl_arr[$key . "_" . $field_def['name']] = translate($field_def['options'], $focus->module_dir, $focus->{$field_def}['name']);
             } else {
                 if ($field_def['type'] == 'multienum' && isset($field_def['options'])) {
                     $repl_arr[$key . "_" . $field_def['name']] = implode(', ', unencodeMultienum($focus->{$field_def}['name']));
                 } else {
                     $repl_arr[$key . "_" . $field_def['name']] = $focus->{$field_def}['name'];
                 }
             }
         }
     }
     // end foreach()
     krsort($repl_arr);
     reset($repl_arr);
     foreach ($repl_arr as $name => $value) {
         if (strpos($name, 'product_discount') > 0) {
             if ($value != '' && $value != '0.00') {
                 if ($repl_arr['aos_products_quotes_discount'] == 'Percentage') {
                     $sep = get_number_seperators();
                     $value = rtrim(rtrim(format_number($value), '0'), $sep[1]);
                     //.$app_strings['LBL_PERCENTAGE_SYMBOL'];
                 } else {
                     $value = currency_format_number($value, $params = array('currency_symbol' => false));
                 }
             } else {
                 $value = '';
             }
         }
         if ($name === 'aos_products_product_image') {
             $value = '<img src="' . $value . '"width="50" height="50"/>';
         }
         if ($name === 'aos_products_quotes_product_qty') {
             $sep = get_number_seperators();
             $value = rtrim(rtrim(format_number($value), '0'), $sep[1]);
         }
         if ($name === 'aos_products_quotes_vat' || strpos($name, 'pct') > 0 || strpos($name, 'percent') > 0 || strpos($name, 'percentage') > 0) {
             $sep = get_number_seperators();
             $value = rtrim(rtrim(format_number($value), '0'), $sep[1]) . $app_strings['LBL_PERCENTAGE_SYMBOL'];
         }
         if (strpos($name, 'date') > 0 || strpos($name, 'expiration') > 0) {
             if ($value != '') {
                 $dt = explode(' ', $value);
                 $value = $dt[0];
             }
         }
         if ($value != '' && is_string($value)) {
             $string = str_replace("\${$name}", $value, $string);
         } else {
             if (strpos($name, 'address') > 0) {
                 $string = str_replace("\${$name}<br />", '', $string);
                 $string = str_replace("\${$name} <br />", '', $string);
                 $string = str_replace("\${$name}", '', $string);
             } else {
                 $string = str_replace("\${$name}", '&nbsp;', $string);
             }
         }
     }
     return $string;
 }
 /**
  * Creates lead_source_by_outcome pipeline image as a HORIZONAL accumlated bar graph for multiple users.
  * param $datay- the lead source data to display in the x-axis
  * param $ids - list of assigned users of opps to find
  * param $cache_file_name - file name to write image to
  * param $refresh - boolean whether to rebuild image if exists
  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
  * All Rights Reserved..
  * Contributor(s): ______________________________________..
  */
 function gen_xml($datay = array('foo', 'bar'), $user_id = array('1'), $cache_file_name = 'a_file', $refresh = false, $current_module_strings)
 {
     global $app_strings, $charset, $lang, $barChartColors, $app_list_strings, $current_user;
     $kDelim = $current_user->getPreference('num_grp_sep');
     if (!file_exists($cache_file_name) || $refresh == true) {
         $GLOBALS['log']->debug("datay is:");
         $GLOBALS['log']->debug($datay);
         $GLOBALS['log']->debug("user_id is: ");
         $GLOBALS['log']->debug($user_id);
         $GLOBALS['log']->debug("cache_file_name is: {$cache_file_name}");
         $opp = new Opportunity();
         $where = "";
         //build the where clause for the query that matches $user
         $count = count($user_id);
         $id = array();
         if ($count > 0) {
             foreach ($user_id as $the_id) {
                 $id[] = "'" . $the_id . "'";
             }
             $ids = join(",", $id);
             $where .= "opportunities.assigned_user_id IN ({$ids}) ";
         }
         //build the where clause for the query that matches $datay
         $count = count($datay);
         $datayArr = array();
         if ($count > 0) {
             foreach ($datay as $key => $value) {
                 $datayArr[] = "'" . $key . "'";
             }
             $datayArr = join(",", $datayArr);
             $where .= "AND opportunities.lead_source IN\t({$datayArr}) ";
         }
         $query = "SELECT lead_source,sales_stage,sum(amount_usdollar/1000) as total,count(*) as opp_count FROM opportunities ";
         $query .= "WHERE " . $where . " AND opportunities.deleted=0 ";
         $query .= " GROUP BY sales_stage,lead_source ORDER BY lead_source,sales_stage";
         //Now do the db queries
         //query for opportunity data that matches $datay and $user
         $result = $opp->db->query($query) or sugar_die("Error selecting sugarbean: " . mysql_error());
         //build pipeline by sales stage data
         $total = 0;
         $div = 1;
         global $sugar_config;
         $symbol = $sugar_config['default_currency_symbol'];
         $other = $current_module_strings['LBL_LEAD_SOURCE_OTHER'];
         $rowTotalArr = array();
         $rowTotalArr[] = 0;
         global $current_user;
         $salesStages = array("Closed Lost" => $app_list_strings['sales_stage_dom']["Closed Lost"], "Closed Won" => $app_list_strings['sales_stage_dom']["Closed Won"], "Other" => $other);
         if ($current_user->getPreference('currency')) {
             $currency = new Currency();
             $currency->retrieve($current_user->getPreference('currency'));
             $div = $currency->conversion_rate;
             $symbol = $currency->symbol;
         }
         $fileContents = '     <yData defaultAltText="' . $current_module_strings['LBL_ROLLOVER_DETAILS'] . '">' . "\n";
         $leadSourceArr = array();
         while ($row = $opp->db->fetchByAssoc($result, -1, false)) {
             if ($row['total'] * $div <= 100) {
                 $sum = round($row['total'] * $div, 2);
             } else {
                 $sum = round($row['total'] * $div);
             }
             if ($row['lead_source'] == '') {
                 $row['lead_source'] = $current_module_strings['NTC_NO_LEGENDS'];
             }
             if ($row['sales_stage'] == 'Closed Won' || $row['sales_stage'] == 'Closed Lost') {
                 $salesStage = $row['sales_stage'];
                 $salesStageT = $app_list_strings['sales_stage_dom'][$row['sales_stage']];
             } else {
                 $salesStage = "Other";
                 $salesStageT = $other;
             }
             if (!isset($leadSourceArr[$row['lead_source']]['row_total'])) {
                 $leadSourceArr[$row['lead_source']]['row_total'] = 0;
             }
             $leadSourceArr[$row['lead_source']][$salesStage]['opp_count'][] = $row['opp_count'];
             $leadSourceArr[$row['lead_source']][$salesStage]['total'][] = $sum;
             $leadSourceArr[$row['lead_source']]['outcome'][$salesStage] = $salesStageT;
             $leadSourceArr[$row['lead_source']]['row_total'] += $sum;
             $total += $sum;
         }
         foreach ($datay as $key => $translation) {
             if ($key == '') {
                 $key = $current_module_strings['NTC_NO_LEGENDS'];
                 $translation = $current_module_strings['NTC_NO_LEGENDS'];
             }
             if (!isset($leadSourceArr[$key])) {
                 $leadSourceArr[$key] = $key;
             }
             if (isset($leadSourceArr[$key]['row_total'])) {
                 $rowTotalArr[] = $leadSourceArr[$key]['row_total'];
             }
             if (isset($leadSourceArr[$key]['row_total']) && $leadSourceArr[$key]['row_total'] > 100) {
                 $leadSourceArr[$key]['row_total'] = round($leadSourceArr[$key]['row_total']);
             }
             $fileContents .= '          <dataRow title="' . $translation . '" endLabel="' . currency_format_number($leadSourceArr[$key]['row_total'], array('currency_symbol' => true)) . '">' . "\n";
             if (is_array($leadSourceArr[$key]['outcome'])) {
                 foreach ($leadSourceArr[$key]['outcome'] as $outcome => $outcome_translation) {
                     $fileContents .= '               <bar id="' . $outcome . '" totalSize="' . array_sum($leadSourceArr[$key][$outcome]['total']) . '" altText="' . format_number(array_sum($leadSourceArr[$key][$outcome]['opp_count']), 0, 0) . ' ' . $current_module_strings['LBL_OPPS_WORTH'] . ' ' . currency_format_number(array_sum($leadSourceArr[$key][$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&lead_source=' . $key . '&sales_stage=' . urlencode($outcome) . '&query=true&searchFormTab=advanced_search"/>' . "\n";
                 }
             }
             $fileContents .= '          </dataRow>' . "\n";
         }
         $fileContents .= '     </yData>' . "\n";
         $max = get_max($rowTotalArr);
         $fileContents .= '     <xData min="0" max="' . $max . '" length="10" kDelim="' . $kDelim . '" prefix="' . $symbol . '" suffix=""/>' . "\n";
         $fileContents .= '     <colorLegend status="on">' . "\n";
         $i = 0;
         foreach ($salesStages as $outcome => $outcome_translation) {
             $color = generate_graphcolor($outcome, $i);
             $fileContents .= '          <mapping id="' . $outcome . '" name="' . $outcome_translation . '" color="' . $color . '"/>' . "\n";
             $i++;
         }
         $fileContents .= '     </colorLegend>' . "\n";
         $fileContents .= '     <graphInfo>' . "\n";
         $fileContents .= '          <![CDATA[' . $current_module_strings['LBL_OPP_SIZE'] . ' ' . $symbol . '1' . $current_module_strings['LBL_OPP_THOUSANDS'] . ']]>' . "\n";
         $fileContents .= '     </graphInfo>' . "\n";
         $fileContents .= '     <chartColors ';
         foreach ($barChartColors as $key => $value) {
             $fileContents .= ' ' . $key . '=' . '"' . $value . '" ';
         }
         $fileContents .= ' />' . "\n";
         $fileContents .= '</graphData>' . "\n";
         $total = round($total, 2);
         $title = '<graphData title="' . $current_module_strings['LBL_ALL_OPPORTUNITIES'] . currency_format_number($total, array('currency_symbol' => true)) . $app_strings['LBL_THOUSANDS_SYMBOL'] . '">' . "\n";
         $fileContents = $title . $fileContents;
         save_xml_file($cache_file_name, $fileContents);
     }
     $return = create_chart('hBarF', $cache_file_name);
     return $return;
 }
Example #11
0
 *
 * Copyright (C) SugarCRM Inc. All rights reserved.
 */
$module = $_REQUEST['save_module'];
$record = $_REQUEST['save_record'];
$field_value = $_REQUEST['save_value'];
$field = $_REQUEST['save_field_name'];
$type = $_REQUEST['type'];
$bean = BeanFactory::getBean($module, $record);
if ($type != 'currency') {
    $bean->{$field} = $field_value;
} else {
    $bean->{$field} = unformat_number($field_value);
}
$bean->save(false);
$ret_array = array();
$ret_array['id'] = $record;
$ret_array['field'] = $field;
if ($type != 'currency') {
    $ret_array['value'] = $bean->{$field};
} else {
    global $locale;
    $params = array();
    $params['currency_id'] = $_REQUEST['currency_id'];
    $params['convert'] = false;
    $params['currency_symbol'] = $_REQUEST['currency_symbol'];
    $ret_array['currency_formatted_value'] = currency_format_number($bean->{$field}, $params);
    $ret_array['formatted_value'] = format_number($bean->{$field});
}
$json = getJSONobj();
echo 'result = ' . $json->encode($ret_array);
/**
 * Creates opportunity pipeline image as a HORIZONTAL accumlated BAR GRAPH for multiple users.
 * param $datax- the sales stage data to display in the x-axis
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
 * All Rights Reserved..
 * Contributor(s): ______________________________________..
 */
function gen_xml_pipeline_by_sales_stage($datax = array('foo', 'bar'), $date_start = '2071-10-15', $date_end = '2071-10-15', $user_id = array('1'), $cache_file_name = 'a_file', $refresh = false, $chart_size = 'hBarF', $current_module_strings)
{
    global $app_strings, $charset, $lang, $barChartColors, $current_user;
    $kDelim = $current_user->getPreference('num_grp_sep');
    global $timedate;
    if (!file_exists($cache_file_name) || $refresh == true) {
        $GLOBALS['log']->debug("starting pipeline chart");
        $GLOBALS['log']->debug("datax is:");
        $GLOBALS['log']->debug($datax);
        $GLOBALS['log']->debug("user_id is: ");
        $GLOBALS['log']->debug($user_id);
        $GLOBALS['log']->debug("cache_file_name is: {$cache_file_name}");
        $opp = new Opportunity();
        $where = "";
        //build the where clause for the query that matches $user
        $count = count($user_id);
        $id = array();
        $user_list = get_user_array(false);
        foreach ($user_id as $key) {
            $new_ids[$key] = $user_list[$key];
        }
        if ($count > 0) {
            foreach ($new_ids as $the_id => $the_name) {
                $id[] = "'" . $the_id . "'";
            }
            $ids = join(",", $id);
            $where .= "opportunities.assigned_user_id IN ({$ids}) ";
        }
        //build the where clause for the query that matches $datax
        $count = count($datax);
        $dataxArr = array();
        if ($count > 0) {
            foreach ($datax as $key => $value) {
                $dataxArr[] = "'" . $key . "'";
            }
            $dataxArr = join(",", $dataxArr);
            $where .= "AND opportunities.sales_stage IN\t({$dataxArr}) ";
        }
        //build the where clause for the query that matches $date_start and $date_end
        $where .= "\tAND opportunities.date_closed >= " . db_convert("'" . $date_start . "'", 'date') . "\n\t\t\t\t\t\tAND opportunities.date_closed <= " . db_convert("'" . $date_end . "'", 'date');
        $where .= "\tAND opportunities.assigned_user_id = users.id  AND opportunities.deleted=0 ";
        //Now do the db queries
        //query for opportunity data that matches $datax and $user
        $query = "\tSELECT opportunities.sales_stage,\n\t\t\t\t\t\t\tusers.user_name,\n\t\t\t\t\t\t\topportunities.assigned_user_id,\n\t\t\t\t\t\t\tcount( * ) AS opp_count,\n\t\t\t\t\t\t\tsum(amount_usdollar/1000) AS total\n\t\t\t\t\t\tFROM users,opportunities  ";
        $query .= "WHERE " . $where;
        $query .= " GROUP BY opportunities.sales_stage,users.user_name,opportunities.assigned_user_id";
        $result = $opp->db->query($query, true);
        //build pipeline by sales stage data
        $total = 0;
        $div = 1;
        global $sugar_config;
        $symbol = $sugar_config['default_currency_symbol'];
        global $current_user;
        if ($current_user->getPreference('currency')) {
            $currency = new Currency();
            $currency->retrieve($current_user->getPreference('currency'));
            $div = $currency->conversion_rate;
            $symbol = $currency->symbol;
        }
        // cn: adding user-pref date handling
        $dateStartDisplay = $timedate->asUserDate($timedate->fromString($date_start));
        $dateEndDisplay = $timedate->asUserDate($timedate->fromString($date_end));
        $fileContents = '     <yData defaultAltText="' . $current_module_strings['LBL_ROLLOVER_DETAILS'] . '">' . "\n";
        $stageArr = array();
        $usernameArr = array();
        $rowTotalArr = array();
        $rowTotalArr[] = 0;
        while ($row = $opp->db->fetchByAssoc($result, false)) {
            if ($row['total'] * $div <= 100) {
                $sum = round($row['total'] * $div, 2);
            } else {
                $sum = round($row['total'] * $div);
            }
            if (!isset($stageArr[$row['sales_stage']]['row_total'])) {
                $stageArr[$row['sales_stage']]['row_total'] = 0;
            }
            $stageArr[$row['sales_stage']][$row['assigned_user_id']]['opp_count'] = $row['opp_count'];
            $stageArr[$row['sales_stage']][$row['assigned_user_id']]['total'] = $sum;
            $stageArr[$row['sales_stage']]['people'][$row['assigned_user_id']] = $row['user_name'];
            $stageArr[$row['sales_stage']]['row_total'] += $sum;
            $usernameArr[$row['assigned_user_id']] = $row['user_name'];
            $total += $sum;
        }
        foreach ($datax as $key => $translation) {
            if (isset($stageArr[$key]['row_total'])) {
                $rowTotalArr[] = $stageArr[$key]['row_total'];
            }
            if (isset($stageArr[$key]['row_total']) && $stageArr[$key]['row_total'] > 100) {
                $stageArr[$key]['row_total'] = round($stageArr[$key]['row_total']);
            }
            $fileContents .= '     <dataRow title="' . $translation . '" endLabel="';
            if (isset($stageArr[$key]['row_total'])) {
                $fileContents .= $stageArr[$key]['row_total'];
            }
            $fileContents .= '">' . "\n";
            if (isset($stageArr[$key]['people'])) {
                asort($stageArr[$key]['people']);
                reset($stageArr[$key]['people']);
                foreach ($stageArr[$key]['people'] as $nameKey => $nameValue) {
                    $fileContents .= '          <bar id="' . $nameKey . '" totalSize="' . $stageArr[$key][$nameKey]['total'] . '" altText="' . $nameValue . ': ' . $stageArr[$key][$nameKey]['opp_count'] . ' ' . $current_module_strings['LBL_OPPS_WORTH'] . ' ' . currency_format_number($stageArr[$key][$nameKey]['total'], array('currency_symbol' => true)) . $current_module_strings['LBL_OPP_THOUSANDS'] . ' ' . $current_module_strings['LBL_OPPS_IN_STAGE'] . ' ' . $translation . '" url="index.php?module=Opportunities&action=index&assigned_user_id[]=' . $nameKey . '&sales_stage=' . urlencode($key) . '&date_start=' . $date_start . '&date_closed=' . $date_end . '&query=true&searchFormTab=advanced_search"/>' . "\n";
                }
            }
            $fileContents .= '     </dataRow>' . "\n";
        }
        $fileContents .= '     </yData>' . "\n";
        $max = get_max($rowTotalArr);
        if ($chart_size == 'hBarF') {
            $length = "10";
        } else {
            $length = "4";
        }
        $fileContents .= '     <xData min="0" max="' . $max . '" length="' . $length . '" kDelim="' . $kDelim . '" prefix="' . $symbol . '" suffix=""/>' . "\n";
        $fileContents .= '     <colorLegend status="on">' . "\n";
        $i = 0;
        asort($new_ids);
        foreach ($new_ids as $key => $value) {
            $color = generate_graphcolor($key, $i);
            $fileContents .= '          <mapping id="' . $key . '" name="' . $value . '" color="' . $color . '"/>' . "\n";
            $i++;
        }
        $fileContents .= '     </colorLegend>' . "\n";
        $fileContents .= '     <graphInfo>' . "\n";
        $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";
        $fileContents .= '     </graphInfo>' . "\n";
        $fileContents .= '     <chartColors ';
        foreach ($barChartColors as $key => $value) {
            $fileContents .= ' ' . $key . '=' . '"' . $value . '" ';
        }
        $fileContents .= ' />' . "\n";
        $fileContents .= '</graphData>' . "\n";
        $total = $total;
        $title = '<graphData title="' . $current_module_strings['LBL_TOTAL_PIPELINE'] . currency_format_number($total, array('currency_symbol' => true)) . $app_strings['LBL_THOUSANDS_SYMBOL'] . '">' . "\n";
        $fileContents = $title . $fileContents;
        save_xml_file($cache_file_name, $fileContents);
    }
    if ($chart_size == 'hBarF') {
        $width = "800";
        $height = "400";
    } else {
        $width = "350";
        $height = "400";
    }
    $return = create_chart($chart_size, $cache_file_name, $width, $height);
    return $return;
}
Example #13
0
function formatDisplayValue($bean, $value, $vardef, $method = "save")
{
    global $app_list_strings, $timedate;
    //Fake the params so we can pass the values through the sugarwidgets to get the correct display html.
    $GLOBALS['focus'] = $bean;
    $_REQUEST['record'] = $bean->id;
    $vardef['fields']['ID'] = $bean->id;
    $vardef['fields'][strtoupper($vardef['name'])] = $value;
    // If field is of type email.
    if ($vardef['name'] == "email1" && $vardef['group'] == "email1") {
        require_once "include/generic/SugarWidgets/SugarWidgetSubPanelEmailLink.php";
        $SugarWidgetSubPanelEmailLink = new SugarWidgetSubPanelEmailLink($vardef);
        $value = $SugarWidgetSubPanelEmailLink->displayList($vardef);
    }
    //If field is of type link and name.
    if ($vardef['link'] && $vardef['type'] == "name" && $_REQUEST['view'] != "DetailView") {
        require_once "include/generic/SugarWidgets/SugarWidgetSubPanelDetailViewLink.php";
        $vardef['module'] = $bean->module_dir;
        $SugarWidgetSubPanelDetailViewLink = new SugarWidgetSubPanelDetailViewLink($vardef);
        $value = "<b>" . $SugarWidgetSubPanelDetailViewLink->displayList($vardef) . "</b>";
    }
    //If field is of type date time or datetimecombo
    if ($vardef['type'] == "datetimecombo" || $vardef['type'] == "datetime") {
        if ($method != "save") {
            $value = convertDateUserToDB($value);
        }
        $datetime_format = $timedate->get_date_time_format();
        // create utc date (as it's utc in db)
        $datetime = DateTime::createFromFormat("Y-m-d H:i:s", $value, new DateTimeZone('UTC'));
        // convert it to timezone the user uses
        $datetime = $timedate->tzUser($datetime);
        $value = $datetime->format($datetime_format);
    }
    //If field is of type bool, checkbox.
    if ($vardef['type'] == "bool") {
        require_once "include/generic/LayoutManager.php";
        $layoutManager = new LayoutManager();
        require_once "include/generic/SugarWidgets/SugarWidgetFieldbool.php";
        $SugarWidgetFieldbool = new SugarWidgetFieldbool($layoutManager);
        $value = $SugarWidgetFieldbool->displayListPlain($vardef);
    }
    //if field is of type multienum.
    if ($vardef['type'] == "multienum") {
        $value = str_replace("^", "", $value);
        $array_values = explode(",", $value);
        foreach ($array_values as $value) {
            $values[] = $app_list_strings[$vardef['options']][$value];
        }
        $value = implode(", ", $values);
    }
    //if field is of type radio.
    if ($vardef['type'] == "radioenum" || $vardef['type'] == "enum" || $vardef['type'] == "dynamicenum") {
        $value = $app_list_strings[$vardef['options']][$value];
    }
    //if field is of type relate.
    if ($vardef['type'] == "relate" || $vardef['type'] == "parent") {
        if ($vardef['source'] == "non-db") {
            if ($vardef['module'] == "Employees") {
                $vardef['ext2'] = "Users";
                $vardef['rname'] = "full_name";
            }
        }
        if ($vardef['type'] == "parent") {
            $vardef['module'] = $bean->parent_type;
            $name = $bean->parent_name;
        }
        $idName = $vardef['id_name'];
        $record = $bean->{$idName};
        if ($vardef['name'] != "assigned_user_name") {
            $value = "<a class=\"listViewTdLinkS1\" href=\"index.php?action=DetailView&module=" . $vardef['module'] . "&record={$record}\">";
        } else {
            $value = "";
        }
        //To fix github bug 880 (the rname was null and was causing a 500 error in the getFieldValueFromModule call to $fieldname
        $fieldName = 'name';
        //$vardef['name'];
        if (!is_null($vardef['rname'])) {
            $fieldName = $vardef['rname'];
        }
        if ($vardef['ext2']) {
            $value .= getFieldValueFromModule($fieldName, $vardef['ext2'], $record);
        } else {
            if (!empty($vardef['rname']) || $vardef['name'] == "related_doc_name") {
                $value .= getFieldValueFromModule($fieldName, $vardef['module'], $record);
            } else {
                $value .= $name;
            }
        }
        if ($vardef['name'] != "assigned_user_name") {
            $value .= "</a>";
        }
    }
    if ($vardef['type'] == "url") {
        $value = '<a href=' . $value . ' target="_blank">' . $value . '</a>';
    }
    if ($vardef['type'] == "currency") {
        if ($_REQUEST['view'] != "DetailView") {
            $value = currency_format_number($value);
        } else {
            $value = format_number($value);
        }
    }
    return $value;
}
Example #14
0
 public static function kcurrencyRenderer($fieldid, $record)
 {
     if ($record[$fieldid] == '' || $record[$fieldid] == 0) {
         return '';
     }
     // 2014-02-25 .. set teh default system currency .. otherwise sugar might take the default users currency
     if (empty($record[$fieldid . '_curid'])) {
         $record[$fieldid . '_curid'] = '99';
     }
     return currency_format_number($record[$fieldid], array('currency_id' => $record[$fieldid . '_curid'], 'currency_symbol' => true));
 }
 function populateLineItems()
 {
     global $app_strings, $mod_strings;
     $params = array('currency_id' => $this->bean->currency_id);
     $sql = "SELECT * FROM aos_products_quotes WHERE parent_type = 'AOS_Quotes' AND parent_id = '" . $this->bean->id . "' AND product_id != '0' AND deleted = 0 ORDER BY number ASC";
     $result = $this->bean->db->query($sql);
     $countLine = $this->bean->db->getRowCount($result);
     $sep = get_number_seperators();
     $html = "";
     $html .= "<table border='0' width='100%' cellpadding='0' cellspacing='0'>";
     if ($countLine != 0) {
         $html .= "<tr>";
         $html .= "<td width='5%' class='tabDetailViewDL' style='text-align: left;padding:2px;'>&nbsp;</td>";
         $html .= "<td width='10%' class='tabDetailViewDL' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_PRODUCT_QUANITY'] . "</td>";
         $html .= "<td width='12%' class='tabDetailViewDL' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_PRODUCT_NAME'] . "</td>";
         $html .= "<td width='12%' class='tabDetailViewDL' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_LIST_PRICE'] . "</td>";
         $html .= "<td width='12%' class='tabDetailViewDL' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_DISCOUNT_AMT'] . "</td>";
         $html .= "<td width='12%' class='tabDetailViewDL' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_UNIT_PRICE'] . "</td>";
         $html .= "<td width='12%' class='tabDetailViewDL' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_VAT'] . "</td>";
         $html .= "<td width='12%' class='tabDetailViewDL' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_VAT_AMT'] . "</td>";
         $html .= "<td width='12%' class='tabDetailViewDL' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_TOTAL_PRICE'] . "</td>";
         $html .= "</tr>";
     }
     $i = 1;
     while ($row = $this->bean->db->fetchByAssoc($result)) {
         $html .= "<tr>";
         $product_note = wordwrap($row['description'], 40, "<br />\n");
         $html .= "<td class='tabDetailViewDF' style='text-align: left; padding:2px;'>" . $i++ . "</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . rtrim(rtrim(format_number($row['product_qty']), '0'), $sep[1]) . "</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'><a href='index.php?module=AOS_Products&action=DetailView&record=" . $row['product_id'] . "' class='tabDetailViewDFLink'>" . $row['name'] . "</a><br />" . $product_note . "</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . currency_format_number($row['product_list_price'], $params) . "</td>";
         if ($row['product_discount'] != '' && $row['product_discount'] != '0.00') {
             if ($row['discount'] == 'Amount') {
                 $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . currency_format_number($row['product_discount'], $params) . "</td>";
             } else {
                 $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . rtrim(rtrim(format_number($row['product_discount']), '0'), $sep[1]) . "%</td>";
             }
         } else {
             $html .= "<td class='tabDetailViewDF' style='padding:2px;'>-</td>";
         }
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . currency_format_number($row['product_unit_price'], $params) . "</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . rtrim(rtrim(format_number($row['vat']), '0'), $sep[1]) . "%</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . currency_format_number($row['vat_amt'], $params) . "</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . currency_format_number($row['product_total_price'], $params) . "</td>";
         $html .= "</tr>";
     }
     $sql = "SELECT * FROM aos_products_quotes WHERE parent_type = 'AOS_Quotes' AND parent_id = '" . $this->bean->id . "' AND product_id = '0' AND deleted = 0 ORDER BY number ASC";
     $result = $this->bean->db->query($sql);
     $countLine = $this->bean->db->getRowCount($result);
     if ($i != 1 && $countLine != 0) {
         $html .= "<tr>";
         $html .= "<td width='5%' class='tabDetailViewDL' style='text-align: left;padding:2px; padding-top:12px;'>&nbsp;</td>";
         $html .= "<td width='46%' class='dataLabel' style='text-align: left;padding:2px; padding-top:12px;' colspan='4' scope='row'>" . $mod_strings['LBL_SERVICE_NAME'] . "</td>";
         $html .= "<td width='12%' class='dataLabel' style='text-align: left;padding:2px; padding-top:12px;' scope='row'>" . $mod_strings['LBL_SERVICE_PRICE'] . "</td>";
         $html .= "<td width='12%' class='tabDetailViewDL' style='text-align: left;padding:2px; padding-top:12px;' scope='row'>" . $mod_strings['LBL_VAT'] . "</td>";
         $html .= "<td width='12%' class='dataLabel' style='text-align: left;padding:2px; padding-top:12px;' scope='row'>" . $mod_strings['LBL_VAT_AMT'] . "</td>";
         $html .= "<td width='12%' class='dataLabel' style='text-align: left;padding:2px; padding-top:12px;' scope='row'>" . $mod_strings['LBL_TOTAL_PRICE'] . "</td>";
         $html .= "</tr>";
     } else {
         if ($countLine != 0) {
             $html .= "<tr>";
             $html .= "<td width='5%' class='tabDetailViewDL' style='text-align: left;padding:2px;'>&nbsp;</td>";
             $html .= "<td width='46%' class='dataLabel' style='text-align: left;padding:2px;' colspan='4' scope='row'>" . $mod_strings['LBL_SERVICE_NAME'] . "</td>";
             $html .= "<td width='12%' class='dataLabel' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_SERVICE_PRICE'] . "</td>";
             $html .= "<td width='12%' class='tabDetailViewDL' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_VAT'] . "</td>";
             $html .= "<td width='12%' class='dataLabel' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_VAT_AMT'] . "</td>";
             $html .= "<td width='12%' class='dataLabel' style='text-align: left;padding:2px;' scope='row'>" . $mod_strings['LBL_TOTAL_PRICE'] . "</td>";
             $html .= "</tr>";
         }
     }
     while ($row = $this->bean->db->fetchByAssoc($result)) {
         $html .= "<tr>";
         $html .= "<td class='tabDetailViewDF' style='text-align: left; padding:2px;'>" . $i++ . "</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;' colspan='4'>" . $row['name'] . "</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . currency_format_number($row['product_unit_price'], $params) . "</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . rtrim(rtrim(format_number($row['vat']), '0'), $sep[1]) . "%</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . currency_format_number($row['vat_amt'], $params) . "</td>";
         $html .= "<td class='tabDetailViewDF' style='padding:2px;'>" . currency_format_number($row['product_total_price'], $params) . "</td>";
         $html .= "</tr>";
     }
     $html .= "</table>";
     $this->ss->assign('LINE_ITEMS', $html);
 }
Example #16
0
/**
 * builds up a delimited string for export
 * @param string type the bean-type to export
 * @param array records an array of records if coming directly from a query
 * @return string delimited string for export
 */
function export($type, $records = null, $members = false, $sample = false)
{
    global $locale;
    global $beanList;
    global $beanFiles;
    global $current_user;
    global $app_strings;
    global $app_list_strings;
    global $timedate;
    global $mod_strings;
    global $current_language;
    $sampleRecordNum = 5;
    //Array of fields that should not be exported, and are only used for logic
    $remove_from_members = array("ea_deleted", "ear_deleted", "primary_address");
    $focus = 0;
    $bean = $beanList[$type];
    require_once $beanFiles[$bean];
    $focus = new $bean();
    $searchFields = array();
    $db = DBManagerFactory::getInstance();
    if ($records) {
        $records = explode(',', $records);
        $records = "'" . implode("','", $records) . "'";
        $where = "{$focus->table_name}.id in ({$records})";
    } elseif (isset($_REQUEST['all'])) {
        $where = '';
    } else {
        if (!empty($_REQUEST['current_post'])) {
            $ret_array = generateSearchWhere($type, $_REQUEST['current_post']);
            $where = $ret_array['where'];
            $searchFields = $ret_array['searchFields'];
        } else {
            $where = '';
        }
    }
    $order_by = "";
    if ($focus->bean_implements('ACL')) {
        if (!ACLController::checkAccess($focus->module_dir, 'export', true)) {
            ACLController::displayNoAccess();
            sugar_die('');
        }
        if (ACLController::requireOwner($focus->module_dir, 'export')) {
            if (!empty($where)) {
                $where .= ' AND ';
            }
            $where .= $focus->getOwnerWhere($current_user->id);
        }
        /* BEGIN - SECURITY GROUPS */
        if (ACLController::requireSecurityGroup($focus->module_dir, 'export')) {
            require_once 'modules/SecurityGroups/SecurityGroup.php';
            global $current_user;
            $owner_where = $focus->getOwnerWhere($current_user->id);
            $group_where = SecurityGroup::getGroupWhere($focus->table_name, $focus->module_dir, $current_user->id);
            if (!empty($owner_where)) {
                if (empty($where)) {
                    $where = " (" . $owner_where . " or " . $group_where . ")";
                } else {
                    $where .= " AND (" . $owner_where . " or " . $group_where . ")";
                }
            } else {
                if (!empty($where)) {
                    $where .= ' AND ';
                }
                $where .= $group_where;
            }
        }
        /* END - SECURITY GROUPS */
    }
    // Export entire list was broken because the where clause already has "where" in it
    // and when the query is built, it has a "where" as well, so the query was ill-formed.
    // Eliminating the "where" here so that the query can be constructed correctly.
    if ($members == true) {
        $query = $focus->create_export_members_query($records);
    } else {
        $beginWhere = substr(trim($where), 0, 5);
        if ($beginWhere == "where") {
            $where = substr(trim($where), 5, strlen($where));
        }
        $query = $focus->create_export_query($order_by, $where);
    }
    $result = '';
    $populate = false;
    if ($sample) {
        $result = $db->limitQuery($query, 0, $sampleRecordNum, true, $app_strings['ERR_EXPORT_TYPE'] . $type . ": <BR>." . $query);
        if ($focus->_get_num_rows_in_query($query) < 1) {
            $populate = true;
        }
    } else {
        $result = $db->query($query, true, $app_strings['ERR_EXPORT_TYPE'] . $type . ": <BR>." . $query);
    }
    $fields_array = $db->getFieldsArray($result, true);
    //set up the order on the header row
    $fields_array = get_field_order_mapping($focus->module_dir, $fields_array);
    //set up labels to be used for the header row
    $field_labels = array();
    foreach ($fields_array as $key => $dbname) {
        //Remove fields that are only used for logic
        if ($members && in_array($dbname, $remove_from_members)) {
            continue;
        }
        //If labels should not be exportable skip them
        if (isset($focus->field_name_map[$key]) && isset($focus->field_name_map[$key]['exportable']) && $focus->field_name_map[$key]['exportable'] === false) {
            continue;
        }
        //default to the db name of label does not exist
        $field_labels[$key] = translateForExport($dbname, $focus);
    }
    $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    if ($locale->getExportCharset() == 'UTF-8' && !preg_match('/macintosh|mac os x|mac_powerpc/i', $user_agent)) {
        //Bug 55520 - add BOM to the exporting CSV so any symbols are displayed correctly in Excel
        $BOM = "";
        $content = $BOM;
    } else {
        $content = '';
    }
    // setup the "header" line with proper delimiters
    $content .= "\"" . implode("\"" . getDelimiter() . "\"", array_values($field_labels)) . "\"\r\n";
    $pre_id = '';
    if ($populate) {
        //this is a sample request with no data, so create fake datarows
        $content .= returnFakeDataRow($focus, $fields_array, $sampleRecordNum);
    } else {
        $records = array();
        //process retrieved record
        while ($val = $db->fetchByAssoc($result, false)) {
            if ($members) {
                $focus = BeanFactory::getBean($val['related_type']);
            } else {
                // field order mapping is not applied for member-exports, as they include multiple modules
                //order the values in the record array
                $val = get_field_order_mapping($focus->module_dir, $val);
            }
            $new_arr = array();
            if ($members) {
                if ($pre_id == $val['id']) {
                    continue;
                }
                if ($val['ea_deleted'] == 1 || $val['ear_deleted'] == 1) {
                    $val['primary_email_address'] = '';
                }
                unset($val['ea_deleted']);
                unset($val['ear_deleted']);
                unset($val['primary_address']);
            }
            $pre_id = $val['id'];
            foreach ($val as $key => $value) {
                //getting content values depending on their types
                $fieldNameMapKey = $fields_array[$key];
                //Dont export fields that have been explicitly marked not to be exportable
                if (isset($focus->field_name_map[$fieldNameMapKey]) && isset($focus->field_name_map[$fieldNameMapKey]['exportable']) && $focus->field_name_map[$fieldNameMapKey]['exportable'] === false) {
                    continue;
                }
                if (isset($focus->field_name_map[$fieldNameMapKey]) && $focus->field_name_map[$fieldNameMapKey]['type']) {
                    $fieldType = $focus->field_name_map[$fieldNameMapKey]['type'];
                    switch ($fieldType) {
                        //if our value is a currency field, then apply the users locale
                        case 'currency':
                            require_once 'modules/Currencies/Currency.php';
                            $value = currency_format_number($value);
                            break;
                            //if our value is a datetime field, then apply the users locale
                        //if our value is a datetime field, then apply the users locale
                        case 'datetime':
                        case 'datetimecombo':
                            $value = $timedate->to_display_date_time($db->fromConvert($value, 'datetime'));
                            $value = preg_replace('/([pm|PM|am|AM]+)/', ' \\1', $value);
                            break;
                            //kbrill Bug #16296
                        //kbrill Bug #16296
                        case 'date':
                            $value = $timedate->to_display_date($db->fromConvert($value, 'date'), false);
                            break;
                            // Bug 32463 - Properly have multienum field translated into something useful for the client
                        // Bug 32463 - Properly have multienum field translated into something useful for the client
                        case 'multienum':
                            $valueArray = unencodeMultiEnum($value);
                            if (isset($focus->field_name_map[$fields_array[$key]]['options']) && isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']])) {
                                foreach ($valueArray as $multikey => $multivalue) {
                                    if (isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$multivalue])) {
                                        $valueArray[$multikey] = $app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$multivalue];
                                    }
                                }
                            }
                            $value = implode(",", $valueArray);
                            break;
                        case 'enum':
                            if (isset($focus->field_name_map[$fields_array[$key]]['options']) && isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']]) && isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$value])) {
                                $value = $app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$value];
                            }
                            break;
                    }
                }
                // Keep as $key => $value for post-processing
                $new_arr[$key] = preg_replace("/\"/", "\"\"", $value);
            }
            // Use Bean ID as key for records
            $records[$pre_id] = $new_arr;
        }
        // Check if we're going to export non-primary emails
        if ($focus->hasEmails() && in_array('email_addresses_non_primary', $fields_array)) {
            // $records keys are bean ids
            $keys = array_keys($records);
            // Split the ids array into chunks of size 100
            $chunks = array_chunk($keys, 100);
            foreach ($chunks as $chunk) {
                // Pick all the non-primary mails for the chunk
                $query = "\n                      SELECT eabr.bean_id, ea.email_address\n                      FROM email_addr_bean_rel eabr\n                      LEFT JOIN email_addresses ea ON ea.id = eabr.email_address_id\n                      WHERE eabr.bean_module = '{$focus->module_dir}'\n                      AND eabr.primary_address = '0'\n                      AND eabr.bean_id IN ('" . implode("', '", $chunk) . "')\n                      AND eabr.deleted != '1'\n                      ORDER BY eabr.bean_id, eabr.reply_to_address, eabr.primary_address DESC\n                    ";
                $result = $db->query($query, true, $app_strings['ERR_EXPORT_TYPE'] . $type . ": <BR>." . $query);
                while ($val = $db->fetchByAssoc($result, false)) {
                    if (empty($records[$val['bean_id']]['email_addresses_non_primary'])) {
                        $records[$val['bean_id']]['email_addresses_non_primary'] = $val['email_address'];
                    } else {
                        // No custom non-primary mail delimeter yet, use semi-colon
                        $records[$val['bean_id']]['email_addresses_non_primary'] .= ';' . $val['email_address'];
                    }
                }
            }
        }
        $customRelateFields = array();
        $selects = array();
        foreach ($records as $record) {
            foreach ($record as $recordKey => $recordValue) {
                if (preg_match('/{relate\\s+from=""([^"]+)""\\s+to=""([^"]+)""}/', $recordValue, $matches)) {
                    $marker = $matches[0];
                    $relatedValue = '';
                    $splits = explode('.', $matches[1]);
                    $currentModule = $splits[0];
                    $currentField = $splits[1];
                    $currentBean = BeanFactory::getBean($currentModule);
                    $currentTable = $currentBean->table_name;
                    $splits = explode('.', $matches[2]);
                    $relatedModule = $splits[0];
                    $relatedField = $splits[1];
                    $relatedBean = BeanFactory::getBean($relatedModule);
                    $relatedTable = $relatedBean->table_name;
                    $relatedLabel = "{$relatedTable}.name AS related_label, NULL AS related_label1";
                    if (isset($relatedBean->field_defs['name']['source']) && $relatedBean->field_defs['name']['source'] == 'non-db') {
                        //$relatedLabel = 'NULL AS related_label, NULL AS related_label1';
                        if (!isset($relatedBean->field_defs['first_name']['source']) || $relatedBean->field_defs['first_name']['source'] != 'non-db' && !isset($relatedBean->field_defs['last_name']['source']) || $relatedBean->field_defs['last_name']['source'] != 'non-db') {
                            $relatedLabel = "{$relatedTable}.last_name AS related_label, {$relatedTable}.first_name AS related_label1";
                        }
                    }
                    $relatedTableCustomJoin = '';
                    $relatedFieldSelect = "NULL AS related_value";
                    if (!isset($existsTables["{$relatedTable}_cstm"])) {
                        $existsTables["{$relatedTable}_cstm"] = $db->tableExists("{$relatedTable}_cstm");
                    }
                    if ($existsTables["{$relatedTable}_cstm"]) {
                        $relatedTableCustomJoin = "\n                        JOIN {$relatedTable}_cstm ON {$relatedTable}_cstm.id_c = {$currentTable}_cstm.{$relatedField}\n                        ";
                        $relatedFieldSelect = "{$currentTable}_cstm.{$relatedField} AS related_value";
                    }
                    $relatedTableJoin = "LEFT JOIN {$relatedTable} ON {$relatedTable}.id = {$currentTable}_cstm.id_c";
                    if (isset($currentBean->field_defs[$relatedField])) {
                        $relatedTableJoin = "LEFT JOIN {$relatedTable} ON {$relatedTable}.id = {$currentTable}_cstm.{$relatedField}";
                    }
                    //-- $relatedTable.id AS related_id,
                    //-- {$currentTable}_cstm.id_c AS current_id_c,
                    //-- {$relatedTable}_cstm.id_c AS related_id_c,
                    $selects[] = "(SELECT {$currentTable}.id AS current_id,'{$currentModule}' AS current_module,'{$currentField}' AS current_field,'{$relatedModule}' AS related_module,'{$relatedField}' AS related_field,{$relatedFieldSelect},{$relatedLabel} FROM {$currentTable} JOIN {$currentTable}_cstm ON {$currentTable}_cstm.id_c={$currentTable}.id {$relatedTableCustomJoin} {$relatedTableJoin} WHERE {$currentTable}.id='{$record['id']}')";
                }
            }
        }
        $selects = array_unique($selects);
        // grab custom related fields information
        // query max length optimization, measured by mssql FreeTDS connection too
        $queryMaxLength = 620000;
        $query = '';
        $i = 0;
        $selectsCount = count($selects) - 1;
        foreach ($selects as $select) {
            $queryTemp = $query . ($i == 0 ? $select : " UNION {$select}");
            if ($i == $selectsCount || strlen($queryTemp) > $queryMaxLength) {
                $result = $db->query($query, 'export error on custom related type: ' . $query);
                while ($val = $db->fetchByAssoc($result, false)) {
                    $customRelateFields[$val['current_module']][$val['current_id']][$val['related_module']][$val['related_field']] = trim($val['related_label'] . ' ' . $val['related_label1']);
                }
                $query = $select;
            } else {
                $query = $queryTemp;
            }
            $i++;
        }
        foreach ($records as $record) {
            $line = implode("\"" . getDelimiter() . "\"", $record);
            $line = "\"" . $line;
            $line .= "\"\r\n";
            $line = parseRelateFields($line, $record, $customRelateFields);
            $content .= $line;
        }
    }
    return $content;
}
Example #17
0
 function get_list_view_data()
 {
     global $locale, $current_language, $current_user, $mod_strings, $app_list_strings, $sugar_config;
     $app_strings = return_application_language($current_language);
     $params = array();
     $temp_array = $this->get_list_view_array();
     $temp_array['SALES_STAGE'] = empty($temp_array['SALES_STAGE']) ? '' : $temp_array['SALES_STAGE'];
     $params = array('currency_id' => $this->currency_id, 'convert' => true);
     $temp_array['AMOUNT'] = currency_format_number($this->amount_usdollar, $params);
     $temp_array["ENCODED_NAME"] = $this->name;
     return $temp_array;
 }
Example #18
0
 function xmlDataReportChart()
 {
     global $app_strings;
     $data = '';
     // correctly process the first row
     $first = true;
     foreach ($this->data_set as $key => $dataset) {
         $total = $this->calculateReportGroupTotal($dataset);
         $this->checkYAxis($total);
         $data .= $this->tab('<group>', 2);
         $data .= $this->tabValue('title', $key, 3);
         $data .= $this->tabValue('value', $total, 3);
         $label = $total;
         if ($this->isCurrencyReportGroupTotal($dataset)) {
             $label = currency_format_number($total, array('currency_symbol' => $this->currency_symbol, 'decimals' => $this->chart_properties['thousands'] ? 0 : null));
         }
         if ($this->chart_properties['thousands']) {
             $label .= $app_strings['LBL_THOUSANDS_SYMBOL'];
         }
         $data .= $this->tabValue('label', $label, 3);
         $data .= $this->tab('<subgroups>', 3);
         if (isset($dataset[$total]) && $total != $dataset[$total]['numerical_value'] || !array_key_exists($key, $dataset)) {
             $data .= $this->processReportData($dataset, 4, $first);
         } elseif (count($this->data_set) == 1 && $first) {
             foreach ($dataset as $k => $v) {
                 if (isset($v['numerical_value'])) {
                     $data .= $this->processDataGroup(4, $k, $v['numerical_value'], $v['numerical_value'], '');
                 }
             }
         }
         if (!$first) {
             $not_processed = array_diff($this->super_set, $this->processed_report_keys);
             $processed_diff_count = count($this->super_set) - count($not_processed);
             if ($processed_diff_count != 0) {
                 foreach ($not_processed as $title) {
                     $data .= $this->processDataGroup(4, $title, 'NULL', '', '');
                 }
             }
         }
         $data .= $this->tab('</subgroups>', 3);
         $data .= $this->tab('</group>', 2);
         $this->processed_report_keys = array();
         // we're done with the first row!
         //$first = false;
     }
     return $data;
 }
 function displayListPlain($layout_def)
 {
     $value = currency_format_number(parent::displayListPlain($layout_def), array_merge(array('convert' => false), $this->getCurrency($layout_def)));
     return $value;
 }
Example #20
0
/**
 * builds up a delimited string for export
 * @param string type the bean-type to export
 * @param array records an array of records if coming directly from a query
 * @return string delimited string for export
 */
function export($type, $records = null, $members = false)
{
    global $beanList;
    global $beanFiles;
    global $current_user;
    global $app_strings;
    global $app_list_strings;
    global $timedate;
    $contact_fields = array("id" => "Contact ID", "lead_source" => "Lead Source", "date_entered" => "Date Entered", "date_modified" => "Date Modified", "first_name" => "First Name", "last_name" => "Last Name", "salutation" => "Salutation", "birthdate" => "Lead Source", "do_not_call" => "Do Not Call", "email_opt_out" => "Email Opt Out", "title" => "Title", "department" => "Department", "birthdate" => "Birthdate", "do_not_call" => "Do Not Call", "phone_home" => "Phone (Home)", "phone_mobile" => "Phone (Mobile)", "phone_work" => "Phone (Work)", "phone_other" => "Phone (Other)", "phone_fax" => "Fax", "email1" => "Email", "email2" => "Email (Other)", "assistant" => "Assistant", "assistant_phone" => "Assistant Phone", "primary_address_street" => "Primary Address Street", "primary_address_city" => "Primary Address City", "primary_address_state" => "Primary Address State", "primary_address_postalcode" => "Primary Address Postalcode", "primary_address_country" => "Primary Address Country", "alt_address_street" => "Other Address Street", "alt_address_city" => "Other Address City", "alt_address_state" => "Other Address State", "alt_address_postalcode" => "Other Address Postalcode", "alt_address_country" => "Other Address Country", "description" => "Description");
    $account_fields = array("id" => "Account ID", "name" => "Account Name", "website" => "Website", "industry" => "Industry", "account_type" => "Type", "ticker_symbol" => "Ticker Symbol", "employees" => "Employees", "ownership" => "Ownership", "phone_office" => "Phone", "phone_fax" => "Fax", "phone_alternate" => "Other Phone", "email1" => "Email", "email2" => "Other Email", "rating" => "Rating", "sic_code" => "SIC Code", "annual_revenue" => "Annual Revenue", "billing_address_street" => "Billing Address Street", "billing_address_city" => "Billing Address City", "billing_address_state" => "Billing Address State", "billing_address_postalcode" => "Billing Address Postalcode", "billing_address_country" => "Billing Address Country", "shipping_address_street" => "Shipping Address Street", "shipping_address_city" => "Shipping Address City", "shipping_address_state" => "Shipping Address State", "shipping_address_postalcode" => "Shipping Address Postalcode", "shipping_address_country" => "Shipping Address Country", "description" => "Description");
    $focus = 0;
    $content = '';
    $bean = $beanList[$type];
    require_once $beanFiles[$bean];
    $focus = new $bean();
    $searchFields = array();
    $db = DBManagerFactory::getInstance();
    if ($records) {
        $records = explode(',', $records);
        $records = "'" . implode("','", $records) . "'";
        $where = "{$focus->table_name}.id in ({$records})";
    } elseif (isset($_REQUEST['all'])) {
        $where = '';
    } else {
        if (!empty($_REQUEST['current_post'])) {
            $ret_array = generateSearchWhere($type, $_REQUEST['current_post']);
            $where = $ret_array['where'];
            $searchFields = $ret_array['searchFields'];
        } else {
            $where = '';
        }
    }
    $order_by = "";
    if ($focus->bean_implements('ACL')) {
        if (!ACLController::checkAccess($focus->module_dir, 'export', true)) {
            ACLController::displayNoAccess();
            sugar_die('');
        }
        if (ACLController::requireOwner($focus->module_dir, 'export')) {
            if (!empty($where)) {
                $where .= ' AND ';
            }
            $where .= $focus->getOwnerWhere($current_user->id);
        }
    }
    // Export entire list was broken because the where clause already has "where" in it
    // and when the query is built, it has a "where" as well, so the query was ill-formed.
    // Eliminating the "where" here so that the query can be constructed correctly.
    if ($members == true) {
        $query = $focus->create_export_members_query($records);
    } else {
        $beginWhere = substr(trim($where), 0, 5);
        if ($beginWhere == "where") {
            $where = substr(trim($where), 5, strlen($where));
        }
        $ret_array = create_export_query_relate_link_patch($type, $searchFields, $where);
        if (!empty($ret_array['join'])) {
            $query = $focus->create_export_query($order_by, $ret_array['where'], $ret_array['join']);
        } else {
            $query = $focus->create_export_query($order_by, $ret_array['where']);
        }
    }
    $result = $db->query($query, true, $app_strings['ERR_EXPORT_TYPE'] . $type . ": <BR>." . $query);
    $fields_array = $db->getFieldsArray($result, true);
    // setup the "header" line with proper delimiters
    $header = implode("\"" . getDelimiter() . "\"", array_values($fields_array));
    if ($members) {
        $header = str_replace('"ea_deleted"' . getDelimiter() . '"ear_deleted"' . getDelimiter() . '"primary_address"' . getDelimiter() . '', '', $header);
    }
    $header = "\"" . $header;
    $header .= "\"\r\n";
    $content .= $header;
    $pre_id = '';
    while ($val = $db->fetchByAssoc($result, -1, false)) {
        $new_arr = array();
        if ($members) {
            if ($pre_id == $val['id']) {
                continue;
            }
            if ($val['ea_deleted'] == 1 || $val['ear_deleted'] == 1) {
                $val['primary_email_address'] = '';
            }
            unset($val['ea_deleted']);
            unset($val['ear_deleted']);
            unset($val['primary_address']);
        }
        $pre_id = $val['id'];
        $vals = array_values($val);
        foreach ($vals as $key => $value) {
            //getting content values depending on their types
            $fieldType = $focus->field_name_map[$fields_array[$key]]['type'];
            if (isset($fieldType)) {
                switch ($fieldType) {
                    //if our value is a currency field, then apply the users locale
                    case 'currency':
                        require_once 'modules/Currencies/Currency.php';
                        $value = currency_format_number($value, array('currency_symbol' => false));
                        break;
                        //if our value is a datetime field, then apply the users locale
                    //if our value is a datetime field, then apply the users locale
                    case 'datetime':
                    case 'datetimecombo':
                        $value = $timedate->to_display_date_time($value);
                        $value = preg_replace('/([pm|PM|am|AM]+)/', ' \\1', $value);
                        break;
                        //kbrill Bug #16296
                    //kbrill Bug #16296
                    case 'date':
                        $value = $timedate->to_display_date($value, false);
                        break;
                        // Bug 32463 - Properly have multienum field translated into something useful for the client
                    // Bug 32463 - Properly have multienum field translated into something useful for the client
                    case 'multienum':
                        $value = str_replace("^", "", $value);
                        if (isset($focus->field_name_map[$fields_array[$key]]['options']) && isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']])) {
                            $valueArray = explode(",", $value);
                            foreach ($valueArray as $multikey => $multivalue) {
                                if (isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$multivalue])) {
                                    $valueArray[$multikey] = $app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$multivalue];
                                }
                            }
                            $value = implode(",", $valueArray);
                        }
                        break;
                }
            }
            array_push($new_arr, preg_replace("/\"/", "\"\"", $value));
        }
        $line = implode("\"" . getDelimiter() . "\"", $new_arr);
        $line = "\"" . $line;
        $line .= "\"\r\n";
        $content .= $line;
    }
    return $content;
}
Example #21
0
/**
 * builds up a delimited string for export
 * @param string type the bean-type to export
 * @param array records an array of records if coming directly from a query
 * @return string delimited string for export
 */
function export($type, $records = null, $members = false, $sample = false)
{
    global $locale;
    global $beanList;
    global $beanFiles;
    global $current_user;
    global $app_strings;
    global $app_list_strings;
    global $timedate;
    global $mod_strings;
    global $current_language;
    $sampleRecordNum = 5;
    $contact_fields = array("id" => "Contact ID", "lead_source" => "Lead Source", "date_entered" => "Date Entered", "date_modified" => "Date Modified", "first_name" => "First Name", "last_name" => "Last Name", "salutation" => "Salutation", "birthdate" => "Lead Source", "do_not_call" => "Do Not Call", "email_opt_out" => "Email Opt Out", "title" => "Title", "department" => "Department", "birthdate" => "Birthdate", "do_not_call" => "Do Not Call", "phone_home" => "Phone (Home)", "phone_mobile" => "Phone (Mobile)", "phone_work" => "Phone (Work)", "phone_other" => "Phone (Other)", "phone_fax" => "Fax", "email1" => "Email", "email2" => "Email (Other)", "assistant" => "Assistant", "assistant_phone" => "Assistant Phone", "primary_address_street" => "Primary Address Street", "primary_address_city" => "Primary Address City", "primary_address_state" => "Primary Address State", "primary_address_postalcode" => "Primary Address Postalcode", "primary_address_country" => "Primary Address Country", "alt_address_street" => "Other Address Street", "alt_address_city" => "Other Address City", "alt_address_state" => "Other Address State", "alt_address_postalcode" => "Other Address Postalcode", "alt_address_country" => "Other Address Country", "description" => "Description");
    $account_fields = array("id" => "Account ID", "name" => "Account Name", "website" => "Website", "industry" => "Industry", "account_type" => "Type", "ticker_symbol" => "Ticker Symbol", "employees" => "Employees", "ownership" => "Ownership", "phone_office" => "Phone", "phone_fax" => "Fax", "phone_alternate" => "Other Phone", "email1" => "Email", "email2" => "Other Email", "rating" => "Rating", "sic_code" => "SIC Code", "annual_revenue" => "Annual Revenue", "billing_address_street" => "Billing Address Street", "billing_address_city" => "Billing Address City", "billing_address_state" => "Billing Address State", "billing_address_postalcode" => "Billing Address Postalcode", "billing_address_country" => "Billing Address Country", "shipping_address_street" => "Shipping Address Street", "shipping_address_city" => "Shipping Address City", "shipping_address_state" => "Shipping Address State", "shipping_address_postalcode" => "Shipping Address Postalcode", "shipping_address_country" => "Shipping Address Country", "description" => "Description");
    //Array of fields that should not be exported, and are only used for logic
    $remove_from_members = array("ea_deleted", "ear_deleted", "primary_address");
    $focus = 0;
    $bean = $beanList[$type];
    require_once $beanFiles[$bean];
    $focus = new $bean();
    $searchFields = array();
    $db = DBManagerFactory::getInstance();
    if ($records) {
        $records = explode(',', $records);
        $records = "'" . implode("','", $records) . "'";
        $where = "{$focus->table_name}.id in ({$records})";
    } elseif (isset($_REQUEST['all'])) {
        $where = '';
    } else {
        if (!empty($_REQUEST['current_post'])) {
            $ret_array = generateSearchWhere($type, $_REQUEST['current_post']);
            $where = $ret_array['where'];
            $searchFields = $ret_array['searchFields'];
        } else {
            $where = '';
        }
    }
    $order_by = "";
    if ($focus->bean_implements('ACL')) {
        if (!ACLController::checkAccess($focus->module_dir, 'export', true)) {
            ACLController::displayNoAccess();
            sugar_die('');
        }
        if (ACLController::requireOwner($focus->module_dir, 'export')) {
            if (!empty($where)) {
                $where .= ' AND ';
            }
            $where .= $focus->getOwnerWhere($current_user->id);
        }
        /* BEGIN - SECURITY GROUPS */
        if (ACLController::requireSecurityGroup($focus->module_dir, 'export')) {
            require_once 'modules/SecurityGroups/SecurityGroup.php';
            global $current_user;
            $owner_where = $focus->getOwnerWhere($current_user->id);
            $group_where = SecurityGroup::getGroupWhere($focus->table_name, $focus->module_dir, $current_user->id);
            if (!empty($owner_where)) {
                if (empty($where)) {
                    $where = " (" . $owner_where . " or " . $group_where . ")";
                } else {
                    $where .= " AND (" . $owner_where . " or " . $group_where . ")";
                }
            } else {
                if (!empty($where)) {
                    $where .= ' AND ';
                }
                $where .= $group_where;
            }
        }
        /* END - SECURITY GROUPS */
    }
    // Export entire list was broken because the where clause already has "where" in it
    // and when the query is built, it has a "where" as well, so the query was ill-formed.
    // Eliminating the "where" here so that the query can be constructed correctly.
    if ($members == true) {
        $query = $focus->create_export_members_query($records);
    } else {
        $beginWhere = substr(trim($where), 0, 5);
        if ($beginWhere == "where") {
            $where = substr(trim($where), 5, strlen($where));
        }
        $query = $focus->create_export_query($order_by, $where);
    }
    $result = '';
    $populate = false;
    if ($sample) {
        $result = $db->limitQuery($query, 0, $sampleRecordNum, true, $app_strings['ERR_EXPORT_TYPE'] . $type . ": <BR>." . $query);
        if ($focus->_get_num_rows_in_query($query) < 1) {
            $populate = true;
        }
    } else {
        $result = $db->query($query, true, $app_strings['ERR_EXPORT_TYPE'] . $type . ": <BR>." . $query);
    }
    $fields_array = $db->getFieldsArray($result, true);
    //set up the order on the header row
    $fields_array = get_field_order_mapping($focus->module_dir, $fields_array);
    //set up labels to be used for the header row
    $field_labels = array();
    foreach ($fields_array as $key => $dbname) {
        //Remove fields that are only used for logic
        if ($members && in_array($dbname, $remove_from_members)) {
            continue;
        }
        //default to the db name of label does not exist
        $field_labels[$key] = translateForExport($dbname, $focus);
    }
    $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    if ($locale->getExportCharset() == 'UTF-8' && !preg_match('/macintosh|mac os x|mac_powerpc/i', $user_agent)) {
        //Bug 55520 - add BOM to the exporting CSV so any symbols are displayed correctly in Excel
        $BOM = "";
        $content = $BOM;
    } else {
        $content = '';
    }
    // setup the "header" line with proper delimiters
    $content .= "\"" . implode("\"" . getDelimiter() . "\"", array_values($field_labels)) . "\"\r\n";
    $pre_id = '';
    if ($populate) {
        //this is a sample request with no data, so create fake datarows
        $content .= returnFakeDataRow($focus, $fields_array, $sampleRecordNum);
    } else {
        $records = array();
        //process retrieved record
        while ($val = $db->fetchByAssoc($result, false)) {
            //order the values in the record array
            $val = get_field_order_mapping($focus->module_dir, $val);
            $new_arr = array();
            if ($members) {
                if ($pre_id == $val['id']) {
                    continue;
                }
                if ($val['ea_deleted'] == 1 || $val['ear_deleted'] == 1) {
                    $val['primary_email_address'] = '';
                }
                unset($val['ea_deleted']);
                unset($val['ear_deleted']);
                unset($val['primary_address']);
            }
            $pre_id = $val['id'];
            foreach ($val as $key => $value) {
                //getting content values depending on their types
                $fieldNameMapKey = $fields_array[$key];
                if (isset($focus->field_name_map[$fieldNameMapKey]) && $focus->field_name_map[$fieldNameMapKey]['type']) {
                    $fieldType = $focus->field_name_map[$fieldNameMapKey]['type'];
                    switch ($fieldType) {
                        //if our value is a currency field, then apply the users locale
                        case 'currency':
                            require_once 'modules/Currencies/Currency.php';
                            $value = currency_format_number($value);
                            break;
                            //if our value is a datetime field, then apply the users locale
                        //if our value is a datetime field, then apply the users locale
                        case 'datetime':
                        case 'datetimecombo':
                            $value = $timedate->to_display_date_time($db->fromConvert($value, 'datetime'));
                            $value = preg_replace('/([pm|PM|am|AM]+)/', ' \\1', $value);
                            break;
                            //kbrill Bug #16296
                        //kbrill Bug #16296
                        case 'date':
                            $value = $timedate->to_display_date($db->fromConvert($value, 'date'), false);
                            break;
                            // Bug 32463 - Properly have multienum field translated into something useful for the client
                        // Bug 32463 - Properly have multienum field translated into something useful for the client
                        case 'multienum':
                            $value = str_replace("^", "", $value);
                            if (isset($focus->field_name_map[$fields_array[$key]]['options']) && isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']])) {
                                $valueArray = explode(",", $value);
                                foreach ($valueArray as $multikey => $multivalue) {
                                    if (isset($app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$multivalue])) {
                                        $valueArray[$multikey] = $app_list_strings[$focus->field_name_map[$fields_array[$key]]['options']][$multivalue];
                                    }
                                }
                                $value = implode(",", $valueArray);
                            }
                            break;
                    }
                }
                // Keep as $key => $value for post-processing
                $new_arr[$key] = preg_replace("/\"/", "\"\"", $value);
            }
            // Use Bean ID as key for records
            $records[$pre_id] = $new_arr;
        }
        // Check if we're going to export non-primary emails
        if ($focus->hasEmails() && in_array('email_addresses_non_primary', $fields_array)) {
            // $records keys are bean ids
            $keys = array_keys($records);
            // Split the ids array into chunks of size 100
            $chunks = array_chunk($keys, 100);
            foreach ($chunks as $chunk) {
                // Pick all the non-primary mails for the chunk
                $query = "\n                      SELECT eabr.bean_id, ea.email_address\n                      FROM email_addr_bean_rel eabr\n                      LEFT JOIN email_addresses ea ON ea.id = eabr.email_address_id\n                      WHERE eabr.bean_module = '{$focus->module_dir}'\n                      AND eabr.primary_address = '0'\n                      AND eabr.bean_id IN ('" . implode("', '", $chunk) . "')\n                      AND eabr.deleted != '1'\n                      ORDER BY eabr.bean_id, eabr.reply_to_address, eabr.primary_address DESC\n                    ";
                $result = $db->query($query, true, $app_strings['ERR_EXPORT_TYPE'] . $type . ": <BR>." . $query);
                while ($val = $db->fetchByAssoc($result, false)) {
                    if (empty($records[$val['bean_id']]['email_addresses_non_primary'])) {
                        $records[$val['bean_id']]['email_addresses_non_primary'] = $val['email_address'];
                    } else {
                        // No custom non-primary mail delimeter yet, use semi-colon
                        $records[$val['bean_id']]['email_addresses_non_primary'] .= ';' . $val['email_address'];
                    }
                }
            }
        }
        foreach ($records as $record) {
            $line = implode("\"" . getDelimiter() . "\"", $record);
            $line = "\"" . $line;
            $line .= "\"\r\n";
            $content .= $line;
        }
    }
    return $content;
}
 function fill_in_additional_detail_fields()
 {
     $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
     $this->created_by_name = get_assigned_user_name($this->created_by);
     $this->modified_by_name = get_assigned_user_name($this->modified_user_id);
     // Collin fixed to use currency_format_number, but suppress currency symbol as it is
     // already rendered from the template files
     require_once 'modules/Currencies/Currency.php';
     $this->budget = currency_format_number($this->budget, array('currency_symbol' => false));
     $this->expected_cost = currency_format_number($this->expected_cost, array('currency_symbol' => false));
     $this->actual_cost = currency_format_number($this->actual_cost, array('currency_symbol' => false));
     $this->expected_revenue = currency_format_number($this->expected_revenue, array('currency_symbol' => false));
 }
function get_name_value_list($value, $returnDomValue = false)
{
    global $app_list_strings;
    $list = array();
    if (!empty($value->field_defs)) {
        if (isset($value->assigned_user_name)) {
            $list['assigned_user_name'] = get_name_value('assigned_user_name', $value->assigned_user_name);
        }
        if (isset($value->modified_by_name)) {
            $list['modified_by_name'] = get_name_value('modified_by_name', $value->modified_by_name);
        }
        if (isset($value->created_by_name)) {
            $list['created_by_name'] = get_name_value('created_by_name', $value->created_by_name);
        }
        foreach ($value->field_defs as $var) {
            if (isset($var['source']) && ($var['source'] != 'db' && $var['source'] != 'custom_fields') && $var['name'] != 'email1' && $var['name'] != 'email2' && (!isset($var['type']) || $var['type'] != 'relate')) {
                if ($value->module_dir == 'Emails' && ($var['name'] == 'description' || $var['name'] == 'description_html' || $var['name'] == 'from_addr_name' || $var['name'] == 'reply_to_addr' || $var['name'] == 'to_addrs_names' || $var['name'] == 'cc_addrs_names' || $var['name'] == 'bcc_addrs_names' || $var['name'] == 'raw_source')) {
                } else {
                    continue;
                }
            }
            if (isset($value->{$var}['name'])) {
                $val = $value->{$var}['name'];
                $type = $var['type'];
                if (strcmp($type, 'date') == 0) {
                    $val = substr($val, 0, 10);
                } elseif (strcmp($type, 'enum') == 0 && !empty($var['options']) && $returnDomValue) {
                    $val = $app_list_strings[$var['options']][$val];
                } elseif (strcmp($type, 'currency') == 0) {
                    $params = array('currency_symbol' => false);
                    $val = currency_format_number($val, $params);
                }
                $list[$var['name']] = get_name_value($var['name'], $val);
            }
        }
    }
    return $list;
}
Example #24
0
/**
 * Enter description here...
 *
 * @param String $session -- Session ID returned by a previous call to login.
 * @param unknown_type $file_name
 * @param unknown_type $fields
 * @return unknown
 */
function get_mailmerge_document2($session, $file_name, $fields)
{
    global $beanList, $beanFiles, $app_list_strings, $app_strings;
    $error = new SoapError();
    if (!validate_authenticated($session)) {
        $GLOBALS['log']->error('invalid_login');
        $error->set_error('invalid_login');
        return array('result' => '', 'error' => $error->get_soap_array());
    }
    if (!preg_match('/^sugardata[\\.\\d\\s]+\\.php$/', $file_name)) {
        $GLOBALS['log']->error($app_strings['ERR_NO_SUCH_FILE'] . " ({$file_name})");
        $error->set_error('no_records');
        return array('result' => '', 'error' => $error->get_soap_array());
    }
    $html = '';
    $file_name = sugar_cached('MergedDocuments/') . pathinfo($file_name, PATHINFO_BASENAME);
    $master_fields = array();
    $related_fields = array();
    if (file_exists($file_name)) {
        include $file_name;
        $class1 = $merge_array['master_module'];
        $beanL = $beanList[$class1];
        $bean1 = $beanFiles[$beanL];
        require_once $bean1;
        $seed1 = new $beanL();
        if (!empty($merge_array['related_module'])) {
            $class2 = $merge_array['related_module'];
            $beanR = $beanList[$class2];
            $bean2 = $beanFiles[$beanR];
            require_once $bean2;
            $seed2 = new $beanR();
        }
        //parse fields
        //$token1 = strtolower($class1);
        if ($class1 == 'Prospects') {
            $class1 = 'CampaignProspects';
        }
        foreach ($fields as $field) {
            $pos = strpos(strtolower($field), strtolower($class1));
            $pos2 = strpos(strtolower($field), strtolower($class2));
            if ($pos !== false) {
                $fieldName = str_replace(strtolower($class1) . '_', '', strtolower($field));
                array_push($master_fields, $fieldName);
            } else {
                if ($pos2 !== false) {
                    $fieldName = str_replace(strtolower($class2) . '_', '', strtolower($field));
                    array_push($related_fields, $fieldName);
                }
            }
        }
        $html = '<html ' . get_language_header() . '><body><table border = 1><tr>';
        foreach ($master_fields as $master_field) {
            $html .= '<td>' . $class1 . '_' . $master_field . '</td>';
        }
        foreach ($related_fields as $related_field) {
            $html .= '<td>' . $class2 . '_' . $related_field . '</td>';
        }
        $html .= '</tr>';
        $ids = $merge_array['ids'];
        $resultIds = array();
        $is_prospect_merge = $seed1->object_name == 'Prospect';
        if ($is_prospect_merge) {
            $pSeed = $seed1;
        }
        foreach ($ids as $key => $value) {
            if ($is_prospect_merge) {
                $seed1 = $pSeed->retrieveTarget($key);
            } else {
                $seed1->retrieve($key);
            }
            $resultIds[] = array('name' => $seed1->module_name, 'value' => $key);
            $html .= '<tr>';
            foreach ($master_fields as $master_field) {
                if (isset($seed1->{$master_field})) {
                    if ($seed1->field_name_map[$master_field]['type'] == 'enum') {
                        //pull in the translated dom
                        $html .= '<td>' . $app_list_strings[$seed1->field_name_map[$master_field]['options']][$seed1->{$master_field}] . '</td>';
                    } else {
                        if ($seed1->field_name_map[$master_field]['type'] == 'multienum') {
                            if (isset($app_list_strings[$seed1->field_name_map[$master_field]['options']])) {
                                $items = unencodeMultienum($seed1->{$master_field});
                                $output = array();
                                foreach ($items as $item) {
                                    if (!empty($app_list_strings[$seed1->field_name_map[$master_field]['options']][$item])) {
                                        array_push($output, $app_list_strings[$seed1->field_name_map[$master_field]['options']][$item]);
                                    }
                                }
                                // foreach
                                $encoded_output = encodeMultienumValue($output);
                                $html .= "<td>{$encoded_output}</td>";
                            }
                        } else {
                            if ($seed1->field_name_map[$master_field]['type'] == 'currency') {
                                $amount_field = $seed1->{$master_field};
                                $params = array('currency_symbol' => false);
                                $amount_field = currency_format_number($amount_field, $params);
                                $html .= '<td>' . $amount_field . '</td>';
                            } else {
                                $html .= '<td>' . $seed1->{$master_field} . '</td>';
                            }
                        }
                    }
                } else {
                    $html .= '<td></td>';
                }
            }
            if (isset($value) && !empty($value)) {
                $resultIds[] = array('name' => $seed2->module_name, 'value' => $value);
                $seed2->retrieve($value);
                foreach ($related_fields as $related_field) {
                    if (isset($seed2->{$related_field})) {
                        if ($seed2->field_name_map[$related_field]['type'] == 'enum') {
                            //pull in the translated dom
                            $html .= '<td>' . $app_list_strings[$seed2->field_name_map[$related_field]['options']][$seed2->{$related_field}] . '</td>';
                        } else {
                            if ($seed2->field_name_map[$related_field]['type'] == 'currency') {
                                $amount_field = $seed2->{$related_field};
                                $params = array('currency_symbol' => false);
                                $amount_field = currency_format_number($amount_field, $params);
                                $html .= '<td>' . $amount_field . '</td>';
                            } else {
                                $html .= '<td>' . $seed2->{$related_field} . '</td>';
                            }
                        }
                    } else {
                        $html .= '<td></td>';
                    }
                }
            }
            $html .= '</tr>';
        }
        $html .= "</table></body></html>";
    }
    $result = base64_encode($html);
    return array('html' => $result, 'name_value_list' => $resultIds, 'error' => $error);
}
Example #25
0
 /**
  * Convenience method to convert raw value into appropriate type format
  * @param string $type
  * @param string $value
  * @return string
  */
 function _convertToType($type, $value)
 {
     switch ($type) {
         case 'currency':
             return currency_format_number($value);
         default:
             return $value;
     }
 }
Example #26
0
 function parse_template_bean($string, $bean_name, &$focus)
 {
     global $app_strings, $module;
     $repl_arr = array();
     foreach ($focus->field_defs as $field_def) {
         if ($field_def['type'] == 'enum' && isset($field_def['options'])) {
             $translated = translate($field_def['options'], $bean_name, $focus->{$field_def}['name']);
             if (isset($translated) && !is_array($translated)) {
                 $repl_arr[strtolower($focus->module_dir) . "_" . $field_def['name']] = $translated;
             } else {
                 // unset enum field, make sure we have a match string to replace with ""
                 $repl_arr[strtolower($focus->module_dir) . "_" . $field_def['name']] = '';
             }
         } elseif ($field_def['type'] == 'currency') {
             //Custom kiem tra kieu currency
             $repl_arr[strtolower($focus->module_dir) . "_" . $field_def['name']] = number_format($focus->{$field_def}['name'], '2', '.', '');
         } else {
             $repl_arr[strtolower($focus->module_dir) . "_" . $field_def['name']] = $focus->{$field_def}['name'];
         }
     }
     // end foreach()
     krsort($repl_arr);
     reset($repl_arr);
     foreach ($repl_arr as $name => $value) {
         if (strpos($name, 'amt') > 0 || strpos($name, 'amount') > 0 || strpos($name, 'price') > 0) {
             $value = currency_format_number($value, $params = array('currency_symbol' => false));
         } else {
             if (strpos($name, 'product_discount') > 0) {
                 if ($value != '' && $value != '0.00') {
                     if ($repl_arr[aos_products_quotes_discount] == 'Percentage') {
                         $sep = get_number_seperators();
                         $value = trim(trim(currency_format_number($value, $params = array('currency_symbol' => false)), '0'), $sep[1]) . $app_strings['LBL_PERCENTAGE_SYMBOL'];
                     } else {
                         $value = currency_format_number($value, $params = array('currency_symbol' => false));
                     }
                 } else {
                     $value = '';
                 }
             }
         }
         if ($name === 'aos_products_quotes_vat' || strpos($name, 'pct') > 0 || strpos($name, 'percent') > 0 || strpos($name, 'percentage') > 0) {
             $sep = get_number_seperators();
             $value = trim(trim(currency_format_number($value, $params = array('currency_symbol' => false)), '0'), $sep[1]) . $app_strings['LBL_PERCENTAGE_SYMBOL'];
         }
         // Kiem tra kieu ngay
         $fieldsname = explode('_', $name, 2);
         if (strpos($fieldsname[1], 'date') > 0 || strpos($fieldsname[1], 'expiration') > 0) {
             if ($value != '') {
                 $dt = explode(' ', $value);
                 $value = $dt[0];
             }
         }
         if ($value != '' && is_string($value)) {
             $string = str_replace("\${$name}", $value, $string);
         } else {
             if (strpos($name, 'address') > 0) {
                 $string = str_replace("\${$name}<br />", '', $string);
                 $string = str_replace("\${$name} <br />", '', $string);
                 $string = str_replace("\${$name}", '', $string);
             } else {
                 $string = str_replace("\${$name}", '&nbsp;', $string);
             }
         }
     }
     return $string;
 }
 /**
  * Creates PIE CHART image of opportunities by lead_source.
  * param $datax- the sales stage data to display in the x-axis
  * param $datay- the sum of opportunity amounts for each opportunity in each sales stage
  * to display in the y-axis
  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
  * All Rights Reserved..
  * Contributor(s): ______________________________________..
  */
 function gen_xml($legends = array('foo', 'bar'), $user_id = array('1'), $cache_file_name = 'a_file', $refresh = true, $current_module_strings)
 {
     global $app_strings, $charset, $lang, $pieChartColors, $current_user;
     require_once 'modules/Currencies/Currency.php';
     $kDelim = $current_user->getPreference('num_grp_sep');
     if (!file_exists($cache_file_name) || $refresh == true) {
         $GLOBALS['log']->debug("starting pipeline chart");
         $GLOBALS['log']->debug("legends is:");
         $GLOBALS['log']->debug($legends);
         $GLOBALS['log']->debug("user_id is: ");
         $GLOBALS['log']->debug($user_id);
         $GLOBALS['log']->debug("cache_file_name is: {$cache_file_name}");
         $opp = new Opportunity();
         //Now do the db queries
         //query for opportunity data that matches $legends and $user
         $where = "";
         //build the where clause for the query that matches $user
         $count = count($user_id);
         $id = array();
         if ($count > 0 && !empty($user_id)) {
             foreach ($user_id as $the_id) {
                 $id[] = "'" . $the_id . "'";
             }
             $ids = join(",", $id);
             $where .= "opportunities.assigned_user_id IN ({$ids}) ";
         }
         if (!empty($where)) {
             $where .= 'AND';
         }
         //build the where clause for the query that matches $datax
         $count = count($legends);
         $legendItem = array();
         if ($count > 0 && !empty($legends)) {
             foreach ($legends as $key => $value) {
                 $legendItem[] = "'" . $key . "'";
             }
             $legendItems = join(",", $legendItem);
             $where .= " opportunities.lead_source IN\t({$legendItems}) ";
         }
         $query = "SELECT lead_source,sum(amount_usdollar/1000) as total,count(*) as opp_count FROM opportunities ";
         $query .= "WHERE " . $where . " AND opportunities.deleted=0 ";
         $query .= "GROUP BY lead_source ORDER BY total DESC";
         //build pipeline by lead source data
         $total = 0;
         $div = 1;
         global $sugar_config;
         $symbol = $sugar_config['default_currency_symbol'];
         global $current_user;
         if ($current_user->getPreference('currency')) {
             $currency = new Currency();
             $currency->retrieve($current_user->getPreference('currency'));
             $div = $currency->conversion_rate;
             $symbol = $currency->symbol;
         }
         $subtitle = $current_module_strings['LBL_OPP_SIZE'] . ' ' . $symbol . '1' . $current_module_strings['LBL_OPP_THOUSANDS'];
         $fileContents = '';
         $fileContents .= '     <pie defaultAltText="' . $current_module_strings['LBL_ROLLOVER_WEDGE_DETAILS'] . '" legendStatus="on">' . "\n";
         $result = $opp->db->query($query) or sugar_die("Error selecting sugarbean: " . mysql_error());
         $leadSourceArr = array();
         while ($row = $opp->db->fetchByAssoc($result, -1, false)) {
             if ($row['lead_source'] == '') {
                 $leadSource = $current_module_strings['NTC_NO_LEGENDS'];
             } else {
                 $leadSource = $row['lead_source'];
             }
             if ($row['total'] * $div <= 100) {
                 $sum = round($row['total'] * $div, 2);
             } else {
                 $sum = round($row['total'] * $div);
             }
             $leadSourceArr[$leadSource]['opp_count'] = $row['opp_count'];
             $leadSourceArr[$leadSource]['sum'] = $sum;
         }
         $i = 0;
         foreach ($legends as $lead_source_key => $translation) {
             if ($lead_source_key == '') {
                 $lead_source_key = $current_module_strings['NTC_NO_LEGENDS'];
                 $translation = $current_module_strings['NTC_NO_LEGENDS'];
             }
             if (!isset($leadSourceArr[$lead_source_key])) {
                 $leadSourceArr[$lead_source_key] = $lead_source_key;
                 $leadSourceArr[$lead_source_key]['sum'] = 0;
             }
             $color = generate_graphcolor($lead_source_key, $i);
             $fileContents .= '          <wedge title="' . $translation . '" kDelim="' . $kDelim . '" value="' . $leadSourceArr[$lead_source_key]['sum'] . '" color="' . $color . '" labelText="' . currency_format_number($leadSourceArr[$lead_source_key]['sum'], array('currency_symbol' => true)) . '" url="index.php?module=Opportunities&action=index&lead_source=' . urlencode($lead_source_key) . '&query=true&searchFormTab=advanced_search" altText="' . format_number($leadSourceArr[$lead_source_key]['opp_count'], 0, 0) . ' ' . $current_module_strings['LBL_OPPS_IN_LEAD_SOURCE'] . ' ' . $translation . '"/>' . "\n";
             if (isset($leadSourceArr[$lead_source_key])) {
                 $total += $leadSourceArr[$lead_source_key]['sum'];
             }
             $i++;
         }
         $fileContents .= '     </pie>' . "\n";
         $fileContents .= '     <graphInfo>' . "\n";
         $fileContents .= '          <![CDATA[]]>' . "\n";
         $fileContents .= '     </graphInfo>' . "\n";
         $fileContents .= '     <chartColors ';
         foreach ($pieChartColors as $key => $value) {
             $fileContents .= ' ' . $key . '=' . '"' . $value . '" ';
         }
         $fileContents .= ' />' . "\n";
         $fileContents .= '</graphData>' . "\n";
         $total = round($total, 2);
         $title = $current_module_strings['LBL_TOTAL_PIPELINE'] . currency_format_number($total, array('currency_symbol' => true)) . $app_strings['LBL_THOUSANDS_SYMBOL'];
         $fileContents = '<graphData title="' . $title . '" subtitle="' . $subtitle . '">' . "\n" . $fileContents;
         $GLOBALS['log']->debug("total is: {$total}");
         if ($total == 0) {
             return $current_module_strings['ERR_NO_OPPS'];
         }
         save_xml_file($cache_file_name, $fileContents);
     }
     $return = create_chart('pieF', $cache_file_name);
     return $return;
 }
Example #28
0
if (unformat_number($focus->impressions) > 0) {
    $cost_per_impression = unformat_number($focus->actual_cost) / unformat_number($focus->impressions);
} else {
    $cost_per_impression = format_number(0);
}
$smarty->assign("COST_PER_IMPRESSION", currency_format_number($cost_per_impression));
if (empty($camp_data1['click_thru_link'])) {
    $camp_data1['click_thru_link'] = 0;
}
$click_thru_links = $camp_data1['click_thru_link'];
if ($click_thru_links > 0) {
    $cost_per_click_thru = unformat_number($focus->actual_cost) / unformat_number($click_thru_links);
} else {
    $cost_per_click_thru = format_number(0);
}
$smarty->assign("COST_PER_CLICK_THROUGH", currency_format_number($cost_per_click_thru));
$currency = new Currency();
if (isset($focus->currency_id) && !empty($focus->currency_id)) {
    $currency->retrieve($focus->currency_id);
    if ($currency->deleted != 1) {
        $smarty->assign("CURRENCY", $currency->iso4217 . ' ' . $currency->symbol);
    } else {
        $smarty->assign("CURRENCY", $currency->getDefaultISO4217() . ' ' . $currency->getDefaultCurrencySymbol());
    }
} else {
    $smarty->assign("CURRENCY", $currency->getDefaultISO4217() . ' ' . $currency->getDefaultCurrencySymbol());
}
global $current_user;
if (is_admin($current_user) && $_REQUEST['module'] != 'DynamicLayout' && !empty($_SESSION['editinplace'])) {
    $smarty->assign("ADMIN_EDIT", "<a href='index.php?action=index&module=DynamicLayout&from_action=" . $_REQUEST['action'] . "&from_module=" . $_REQUEST['module'] . "&record=" . $_REQUEST['record'] . "'>" . SugarThemeRegistry::current()->getImage("EditLayout", "border='0' align='bottom'", null, null, '.gif', $mod_strings['LBL_EDIT_LAYOUT']) . "</a>");
}
 /**
  * Creates opportunity pipeline image as a VERTICAL accumlated bar graph for multiple users.
  * param $datax- the month data to display in the x-axis
  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
  * All Rights Reserved..
  * Contributor(s): ______________________________________..
  */
 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)
 {
     global $app_strings, $app_list_strings, $charset, $lang, $barChartColors, $current_user;
     $kDelim = $current_user->getPreference('num_grp_sep');
     global $timedate;
     if (!file_exists($cache_file_name) || $refresh == true) {
         Log::debug("date_start is: {$date_start}");
         Log::debug("date_end is: {$date_end}");
         Log::debug("user_id is: ");
         Log::debug($user_id);
         Log::debug("cache_file_name is: {$cache_file_name}");
         $where = "";
         //build the where clause for the query that matches $user
         $count = count($user_id);
         $id = array();
         if ($count > 0) {
             foreach ($user_id as $the_id) {
                 $id[] = "'" . $the_id . "'";
             }
             $ids = join(",", $id);
             $where .= "opportunities.assigned_user_id IN ({$ids}) ";
         }
         // cn: adding user-pref date handling
         $dateStartDisplay = $timedate->asUserDate($timedate->fromString($date_start));
         $dateEndDisplay = $timedate->asUserDate($timedate->fromString($date_end));
         $opp = new Opportunity();
         //build the where clause for the query that matches $date_start and $date_end
         $where .= "AND opportunities.date_closed >= " . db_convert("'" . $date_start . "'", 'date') . " AND opportunities.date_closed <= " . db_convert("'" . $date_end . "'", 'date') . " AND opportunities.deleted=0";
         $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 ";
         $query .= "WHERE " . $where;
         $query .= " GROUP BY sales_stage," . db_convert('opportunities.date_closed', 'date_format', array("'%Y-%m'"), array("'YYYY-MM'")) . "ORDER BY m";
         //Now do the db queries
         //query for opportunity data that matches $datay and $user
         //_pp($query);
         $result = $opp->db->query($query, true);
         //build pipeline by sales stage data
         $total = 0;
         $div = 1;
         global $sugar_config;
         $symbol = $sugar_config['default_currency_symbol'];
         $other = $current_module_strings['LBL_LEAD_SOURCE_OTHER'];
         $rowTotalArr = array();
         $rowTotalArr[] = 0;
         global $current_user;
         $salesStages = array("Closed Lost" => $app_list_strings['sales_stage_dom']["Closed Lost"], "Closed Won" => $app_list_strings['sales_stage_dom']["Closed Won"], "Other" => $other);
         if ($current_user->getPreference('currency')) {
             $currency = new Currency();
             $currency->retrieve($current_user->getPreference('currency'));
             $div = $currency->conversion_rate;
             $symbol = $currency->symbol;
         }
         $months = array();
         $monthArr = array();
         while ($row = $opp->db->fetchByAssoc($result, false)) {
             if ($row['total'] * $div <= 100) {
                 $sum = round($row['total'] * $div, 2);
             } else {
                 $sum = round($row['total'] * $div);
             }
             if ($row['sales_stage'] == 'Closed Won' || $row['sales_stage'] == 'Closed Lost') {
                 $salesStage = $row['sales_stage'];
                 $salesStageT = $app_list_strings['sales_stage_dom'][$row['sales_stage']];
             } else {
                 $salesStage = "Other";
                 $salesStageT = $other;
             }
             $months[$row['m']] = $row['m'];
             if (!isset($monthArr[$row['m']]['row_total'])) {
                 $monthArr[$row['m']]['row_total'] = 0;
             }
             $monthArr[$row['m']][$salesStage]['opp_count'][] = $row['opp_count'];
             $monthArr[$row['m']][$salesStage]['total'][] = $sum;
             $monthArr[$row['m']]['outcome'][$salesStage] = $salesStageT;
             $monthArr[$row['m']]['row_total'] += $sum;
             $total += $sum;
         }
         $fileContents = '     <xData length="20">' . "\n";
         if (!empty($months)) {
             foreach ($months as $month) {
                 $rowTotalArr[] = $monthArr[$month]['row_total'];
                 if ($monthArr[$month]['row_total'] > 100) {
                     $monthArr[$month]['row_total'] = round($monthArr[$month]['row_total']);
                 }
                 $fileContents .= '          <dataRow title="' . $month . '" endLabel="' . currency_format_number($monthArr[$month]['row_total'], array('currency_symbol' => true)) . '">' . "\n";
                 arsort($salesStages);
                 foreach ($salesStages as $outcome => $outcome_translation) {
                     if (isset($monthArr[$month][$outcome])) {
                         $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";
                     }
                 }
                 $fileContents .= '          </dataRow>' . "\n";
             }
         } else {
             $fileContents .= '          <dataRow title="" endLabel="">' . "\n";
             $fileContents .= '               <bar id="" totalSize="0" altText="" url=""/>' . "\n";
             $fileContents .= '          </dataRow>' . "\n";
             $rowTotalArr[] = 1000;
         }
         $fileContents .= '     </xData>' . "\n";
         $max = get_max($rowTotalArr);
         $fileContents .= '     <yData min="0" max="' . $max . '" length="10" prefix="' . $symbol . '" suffix="" kDelim="' . $kDelim . '" defaultAltText="' . $current_module_strings['LBL_ROLLOVER_DETAILS'] . '"/>' . "\n";
         $fileContents .= '     <colorLegend status="on">' . "\n";
         $i = 0;
         asort($salesStages);
         foreach ($salesStages as $outcome => $outcome_translation) {
             $color = generate_graphcolor($outcome, $i);
             $fileContents .= '          <mapping id="' . $outcome . '" name="' . $outcome_translation . '" color="' . $color . '"/>' . "\n";
             $i++;
         }
         $fileContents .= '     </colorLegend>' . "\n";
         $fileContents .= '     <graphInfo>' . "\n";
         $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";
         $fileContents .= '     </graphInfo>' . "\n";
         $fileContents .= '     <chartColors ';
         foreach ($barChartColors as $key => $value) {
             $fileContents .= ' ' . $key . '=' . '"' . $value . '" ';
         }
         $fileContents .= ' />' . "\n";
         $fileContents .= '</graphData>' . "\n";
         $total = round($total, 2);
         $title = '<graphData title="' . $current_module_strings['LBL_TOTAL_PIPELINE'] . currency_format_number($total, array('currency_symbol' => true)) . $app_strings['LBL_THOUSANDS_SYMBOL'] . '">' . "\n";
         $fileContents = $title . $fileContents;
         //echo $fileContents;
         save_xml_file($cache_file_name, $fileContents);
     }
     $return = create_chart('vBarF', $cache_file_name);
     return $return;
 }
Example #30
0
 public function testcurrency_format_number()
 {
     $this->assertEquals('$100.00', currency_format_number(100));
     $this->assertEquals('$100.0', currency_format_number(100, array('round' => 1, 'decimals' => 1)));
 }