Example #1
0
 public function fill_in_additional_detail_fields()
 {
     parent::fill_in_additional_detail_fields();
     if (empty($this->amount_usdollar) && !empty($this->amount)) {
         $this->amount_usdollar = SugarCurrency::convertWithRate($this->amount, $this->base_rate);
     }
 }
 /**
  * Returns the entire enumeration bare.
  */
 function evaluate()
 {
     $params = $this->getParameters();
     //This should be of relate type, which means an array of SugarBean objects
     $linkField = $params[0]->evaluate();
     $relfield = $params[1]->evaluate();
     if (empty($linkField)) {
         return "";
     }
     foreach ($linkField as $id => $bean) {
         if (!empty($bean->field_defs[$relfield]) && isset($bean->{$relfield})) {
             if (!empty($bean->field_defs[$relfield]['type'])) {
                 global $timedate;
                 if ($bean->field_defs[$relfield]['type'] == "date") {
                     $ret = $timedate->fromDbDate($bean->{$relfield});
                     if (!$ret) {
                         $ret = $timedate->fromUserDate($bean->{$relfield});
                     }
                     if ($ret) {
                         $ret->isDate = true;
                     }
                     return $ret;
                 }
                 if ($bean->field_defs[$relfield]['type'] == "datetime" || $bean->field_defs[$relfield]['type'] == "datetimecombo") {
                     $ret = $timedate->fromDb($bean->{$relfield});
                     if (!$ret) {
                         $ret = $timedate->fromUser($bean->{$relfield});
                     }
                     return $ret;
                 }
                 if ($bean->field_defs[$relfield]['type'] == "bool") {
                     require_once "include/Expressions/Expression/Boolean/BooleanExpression.php";
                     if ($bean->{$relfield}) {
                         return BooleanExpression::$TRUE;
                     } else {
                         return BooleanExpression::$FALSE;
                     }
                 }
                 //Currency values need to be converted to the current currency when the related value
                 //doesn't match this records currency
                 if ($bean->field_defs[$relfield]['type'] == "currency") {
                     if (!isset($this->context)) {
                         $this->setContext();
                     }
                     if (isset($this->context->base_rate) && isset($bean->base_rate) && $this->context->base_rate != $bean->base_rate) {
                         return SugarCurrency::convertWithRate($bean->{$relfield}, $bean->base_rate, $this->context->base_rate);
                     }
                 }
             }
             return $bean->{$relfield};
         }
     }
     return "";
 }
 /**
  * Ability only rollup specific values from related records when a field on the related record is equal to
  * something.
  *
  * @return string
  */
 public function evaluate()
 {
     $params = $this->getParameters();
     // This should be of relate type, which means an array of SugarBean objects
     $linkField = $params[0]->evaluate();
     $relfield = $params[1]->evaluate();
     $conditionalField = $params[2]->evaluate();
     $conditionalValues = $params[3]->evaluate();
     if (!is_array($conditionalValues)) {
         $conditionalValues = array($conditionalValues);
     }
     $ret = '0';
     if (!is_array($linkField) || empty($linkField)) {
         return $ret;
     }
     if (!isset($this->context)) {
         //If we don't have a context provided, we have to guess. This can be a large performance hit.
         $this->setContext();
     }
     $toRate = isset($this->context->base_rate) ? $this->context->base_rate : null;
     $checkedTypeForCurrency = false;
     $relFieldIsCurrency = false;
     foreach ($linkField as $bean) {
         if (!in_array($bean->{$conditionalField}, $conditionalValues)) {
             continue;
         }
         // only check the target field once to see if it's a currency field.
         if ($checkedTypeForCurrency === false) {
             $checkedTypeForCurrency = true;
             $relFieldIsCurrency = $this->isCurrencyField($bean, $relfield);
         }
         if (!empty($bean->{$relfield})) {
             $value = $bean->{$relfield};
             // if we have a currency field, it needs to convert the value into the rate of the row it's
             // being returned to.
             if ($relFieldIsCurrency) {
                 $value = SugarCurrency::convertWithRate($value, $bean->base_rate, $toRate);
             }
             $ret = SugarMath::init($ret)->add($value)->result();
         }
     }
     return $ret;
 }
Example #4
0
/**
 * @param Opportunity $focus        The Current Opportunity we are working with
 */
function perform_save($focus)
{
    global $app_list_strings, $timedate, $current_language;
    $app_list_strings = return_app_list_strings_language($current_language);
    /* @var $admin Administration */
    $admin = BeanFactory::getBean('Administration');
    $settings = $admin->getConfigForModule('Forecasts');
    // if any of the case fields are NULL or an empty string set it to the amount from the main opportunity
    if (is_null($focus->best_case) || strval($focus->best_case) === "") {
        $focus->best_case = $focus->amount;
    }
    if (is_null($focus->worst_case) || strval($focus->worst_case) === "") {
        $focus->worst_case = $focus->amount;
    }
    // Bug49495: amount may be a calculated field
    $focus->updateCalculatedFields();
    //Store the base currency value
    if (isset($focus->amount) && !number_empty($focus->amount)) {
        $focus->amount_usdollar = SugarCurrency::convertWithRate($focus->amount, $focus->base_rate);
    }
}
/// Users Popup
$popup_request_data = array('call_back_function' => 'set_return', 'form_name' => 'wizform', 'field_to_name_array' => array('id' => 'assigned_user_id', 'user_name' => 'assigned_user_name'));
$ss->assign('encoded_users_popup_request_data', $json->encode($popup_request_data));
$popup_request_data = array('call_back_function' => 'set_return', 'form_name' => 'wizform', 'field_to_name_array' => array('id' => 'team_id', 'name' => 'team_name'));
$ss->assign('encoded_team_popup_request_data', $json->encode($popup_request_data));
if (!empty($focus->budget)) {
    $focus->budget = SugarCurrency::formatAmountUserLocale($focus->budget, $focus->currency_id, false);
}
if (!empty($focus->actual_cost)) {
    $focus->actual_cost = SugarCurrency::formatAmountUserLocale($focus->actual_cost, $focus->currency_id, false);
}
if (!empty($focus->expected_cost)) {
    $focus->expected_cost = SugarCurrency::formatAmountUserLocale($focus->expected_cost, $focus->currency_id, false);
}
if (!empty($focus->expected_revenue)) {
    $focus->expected_revenue = SugarCurrency::formatAmountUserLocale($focus->expected_revenue, $focus->currency_id, false);
}
//set default values
$ss->assign("CALENDAR_LANG", "en");
$ss->assign("USER_DATEFORMAT", '(' . $timedate->get_user_date_format() . ')');
$ss->assign("CALENDAR_DATEFORMAT", $timedate->get_cal_date_format());
$ss->assign("CAMP_DATE_ENTERED", $focus->date_entered);
$ss->assign("CAMP_DATE_MODIFIED", $focus->date_modified);
$ss->assign("CAMP_CREATED_BY", $focus->created_by_name);
$ss->assign("CAMP_MODIFIED_BY", $focus->modified_by_name);
$ss->assign("ID", $focus->id);
$ss->assign("CAMP_TRACKER_TEXT", $focus->tracker_text);
$ss->assign("CAMP_START_DATE", $focus->start_date);
$ss->assign("CAMP_END_DATE", $focus->end_date);
$ss->assign("CAMP_BUDGET", $focus->budget);
$ss->assign("CAMP_ACTUAL_COST", $focus->actual_cost);
 /**
  * populateSeedData
  *
  * This is a static function to create Opportunities.
  *
  * @static
  * @param $records Integer value indicating the number of Opportunities to create
  * @param $app_list_strings Array of application language strings
  * @param $accounts Array of Account instances to randomly build data against
  * @param $timeperiods Array of Timeperiods to create timeperiod seed data off of
  * @param $users Array of User instances to randomly build data against
  * @return array Array of Opportunities created
  */
 public static function populateSeedData($records, $app_list_strings, $accounts, $users)
 {
     if (empty($accounts) || empty($app_list_strings) || (!is_int($records) || $records < 1) || empty($users)) {
         return array();
     }
     $opp_ids = array();
     $timedate = TimeDate::getInstance();
     // get the additional currencies from the table
     /* @var $currency Currency */
     $currency = SugarCurrency::getCurrencyByISO('EUR');
     while ($records-- > 0) {
         $key = array_rand($accounts);
         $account = $accounts[$key];
         /* @var $opp Opportunity */
         $opp = BeanFactory::getBean('Opportunities');
         //Create new opportunities
         $opp->team_id = $account->team_id;
         $opp->team_set_id = $account->team_set_id;
         $opp->assigned_user_id = $account->assigned_user_id;
         $opp->assigned_user_name = $account->assigned_user_name;
         // figure out which one to use
         $seed = rand(1, 15);
         if ($seed % 2 == 0) {
             $currency_id = $currency->id;
             $base_rate = $currency->conversion_rate;
         } else {
             // use the base rate
             $currency_id = '-99';
             $base_rate = '1.0';
         }
         $opp->base_rate = $base_rate;
         $opp->currency_id = $currency_id;
         $opp->name = $account->name;
         $opp->lead_source = array_rand($app_list_strings['lead_source_dom']);
         $opp->sales_stage = array_rand($app_list_strings['sales_stage_dom']);
         $opp->sales_status = 'New';
         // If the deal is already done, make the date closed occur in the past.
         $opp->date_closed = $opp->sales_stage == Opportunity::STAGE_CLOSED_WON || $opp->sales_stage == Opportunity::STAGE_CLOSED_WON ? self::createPastDate() : self::createDate();
         $opp->date_closed_timestamp = $timedate->fromDbDate($opp->date_closed)->getTimestamp();
         $opp->opportunity_type = array_rand($app_list_strings['opportunity_type_dom']);
         $amount = rand(1000, 7500);
         $opp->amount = $amount;
         $opp->probability = $app_list_strings['sales_probability_dom'][$opp->sales_stage];
         //Setup forecast seed data
         $opp->best_case = $opp->amount;
         $opp->worst_case = $opp->amount;
         $opp->commit_stage = $opp->probability >= 70 ? 'include' : 'exclude';
         $opp->id = create_guid();
         $opp->new_with_id = true;
         // set the acccount on the opps, just for saving to the worksheet table
         $opp->account_id = $account->id;
         $opp->account_name = $account->name;
         // save the opp again
         $opp->save();
         // save a draft worksheet for the new forecasts stuff
         /* @var $worksheet ForecastWorksheet */
         $worksheet = BeanFactory::getBean('ForecastWorksheets');
         $worksheet->saveRelatedOpportunity($opp);
         $opp_ids[] = $opp->id;
     }
     return $opp_ids;
 }
Example #7
0
 function getCurrencySymbol($user = null)
 {
     $currencyId = $this->getPrecedentPreference('currency', $user);
     $currencyId = $currencyId ? $currencyId : '-99';
     $currency = SugarCurrency::getCurrencyByID($currencyId);
     return $currency->symbol;
 }
Example #8
0
 /**
  * Implements a generic insert and update logic for any SugarBean
  * This method only works for subclasses that implement the same variable names.
  * This method uses the presence of an id field that is not null to signify and update.
  * The id field should not be set otherwise.
  *
  * @param boolean $check_notify Optional, default false, if set to true assignee of the record is notified via email.
  * @todo Add support for field type validation and encoding of parameters.
  */
 function save($check_notify = false)
 {
     $this->in_save = true;
     // cn: SECURITY - strip XSS potential vectors
     $this->cleanBean();
     // This is used so custom/3rd-party code can be upgraded with fewer issues, this will be removed in a future release
     $this->fixUpFormatting();
     global $timedate;
     global $current_user, $action;
     $isUpdate = true;
     if (empty($this->id) || !empty($this->new_with_id)) {
         $isUpdate = false;
     }
     if (empty($this->date_modified) || $this->update_date_modified) {
         $this->date_modified = $GLOBALS['timedate']->nowDb();
     }
     $this->_checkOptimisticLocking($action, $isUpdate);
     if (!empty($this->modified_by_name)) {
         $this->old_modified_by_name = $this->modified_by_name;
     }
     if ($this->update_modified_by) {
         $this->modified_user_id = 1;
         if (!empty($current_user)) {
             $this->modified_user_id = $current_user->id;
             $this->modified_by_name = $current_user->user_name;
         }
     }
     if ($this->deleted != 1) {
         $this->deleted = 0;
     }
     if (!$isUpdate) {
         if (empty($this->date_entered)) {
             $this->date_entered = $this->date_modified;
         }
         if ($this->set_created_by == true) {
             // created by should always be this user
             $this->created_by = isset($current_user) ? $current_user->id : "";
         }
         if ($this->new_with_id == false) {
             $this->id = create_guid();
         }
     }
     // if the module has a team_id field and no team_id is specified, set team_id as the current_user's default team
     // currently, the default_team is only enforced in the presentation layer-- this enforces it at the data layer as well
     $usedDefaultTeam = false;
     if (empty($this->team_id) && isset($this->field_defs['team_id']) && isset($current_user)) {
         $this->team_id = $current_user->team_id;
         $usedDefaultTeam = true;
     }
     // if this bean has a currency_id and base_rate, verify that base_rate is set to the correct amount
     if (isset($this->field_defs['currency_id']) && isset($this->field_defs['base_rate'])) {
         SugarCurrency::verifyCurrencyBaseRateSet($this, $isUpdate);
     }
     require_once "data/BeanFactory.php";
     BeanFactory::registerBean($this);
     if (!static::inOperation('saving_related') && static::enterOperation('updating_relationships')) {
         // let subclasses save related field changes
         $this->save_relationship_changes($isUpdate);
         static::leaveOperation('updating_relationships');
     }
     $this->updateCalculatedFields();
     if ($isUpdate && !$this->update_date_entered) {
         unset($this->date_entered);
     }
     // call the custom business logic
     $custom_logic_arguments = array('check_notify' => $check_notify, 'isUpdate' => $isUpdate);
     $this->call_custom_logic("before_save", $custom_logic_arguments);
     unset($custom_logic_arguments);
     if (isset($this->custom_fields)) {
         $this->custom_fields->bean = $this;
         $this->custom_fields->save($isUpdate);
     }
     //rrs new functionality to check if the team_id is set and the team_set_id is not set,
     //then see what we can do about saving to team_set_id. It is important for this code block to be below
     //the 'before_save' custom logic hook as that is where workflow is called.
     if (isset($this->field_defs['team_id'])) {
         if (empty($this->teams)) {
             $this->load_relationship('teams');
         }
         if (!empty($this->teams)) {
             //we do not need to the TeamSetLink to update the bean's table here
             //since it will be handled below.
             $this->teams->save(false, $usedDefaultTeam);
         }
     }
     // use the db independent query generator
     $this->preprocess_fields_on_save();
     $dataChanges = $this->db->getDataChanges($this);
     //construct the SQL to create the audit record if auditing is enabled.
     $auditDataChanges = array();
     if ($this->is_AuditEnabled()) {
         if ($isUpdate && !isset($this->fetched_row)) {
             $GLOBALS['log']->debug('Auditing: Retrieve was not called, audit record will not be created.');
         } else {
             $auditFields = $this->getAuditEnabledFieldDefinitions();
             $auditDataChanges = array_intersect_key($dataChanges, $auditFields);
         }
     }
     $this->_sendNotifications($check_notify);
     if ($isUpdate) {
         $this->db->update($this);
     } elseif ($this->db->insert($this)) {
         //Now that the record has been saved, we don't want to insert again on further saves
         $this->new_with_id = false;
     }
     if (!empty($auditDataChanges) && is_array($auditDataChanges)) {
         foreach ($auditDataChanges as $change) {
             $this->db->save_audit_records($this, $change);
         }
     }
     $this->updateRelatedCalcFields();
     // populate fetched row with newest changes in the bean
     foreach ($dataChanges as $change) {
         $this->fetched_row[$change['field_name']] = $change['after'];
     }
     // the reason we need to skip this is so that any RelatedBeans that are targeted to be saved
     // after the delete happens, wait to be saved till them.
     if (!static::inOperation('delete')) {
         SugarRelationship::resaveRelatedBeans();
     }
     //rrs - bug 7908
     $this->process_workflow_alerts();
     //rrs
     //If we aren't in setup mode and we have a current user and module, then we track
     if (isset($GLOBALS['current_user']) && isset($this->module_dir)) {
         $this->track_view($current_user->id, $this->module_dir, 'save');
     }
     $this->call_custom_logic('after_save', array('isUpdate' => $isUpdate, 'dataChanges' => $dataChanges));
     $this->in_save = false;
     return $this->id;
 }
Example #9
0
/**
 * Retrieve a list of beans.  This is the primary method for getting list of SugarBeans from Sugar using the SOAP API.
 *
 * @param String $session -- Session ID returned by a previous call to login.
 * @param String $module_name -- The name of the module to return records from.  This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
 * @param String $query -- SQL where clause without the word 'where'
 * @param String $order_by -- SQL order by clause without the phrase 'order by'
 * @param String $offset -- The record offset to start from.
 * @param Array  $select_fields -- A list of the fields to be included in the results. This optional parameter allows for only needed fields to be retrieved.
 * @param String $max_results -- The maximum number of records to return.  The default is the sugar configuration value for 'list_max_entries_per_page'
 * @param Number $deleted -- false if deleted records should not be include, true if deleted records should be included.
 * @return Array 'result_count' -- The number of records returned
 *               'next_offset' -- The start of the next page (This will always be the previous offset plus the number of rows returned.  It does not indicate if there is additional data unless you calculate that the next_offset happens to be closer than it should be.
 *               'field_list' -- The vardef information on the selected fields.
 *                      Array -- 'field'=>  'name' -- the name of the field
 *                                          'type' -- the data type of the field
 *                                          'label' -- the translation key for the label of the field
 *                                          'required' -- Is the field required?
 *                                          'options' -- Possible values for a drop down field
 *               'entry_list' -- The records that were retrieved
 *               'error' -- The SOAP error, if any
 */
function get_entry_list($session, $module_name, $query, $order_by, $offset, $select_fields, $max_results, $deleted)
{
    $error = new SoapError();
    if (!validate_authenticated($session)) {
        $error->set_error('invalid_login');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    $using_cp = false;
    if ($module_name == 'CampaignProspects') {
        $module_name = 'Prospects';
        $using_cp = true;
    }
    global $current_user;
    if (!check_modules_access($current_user, $module_name, 'read')) {
        $error->set_error('no_access');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    // If the maximum number of entries per page was specified, override the configuration value.
    if ($max_results > 0) {
        global $sugar_config;
        $sugar_config['list_max_entries_per_page'] = $max_results;
    }
    $seed = BeanFactory::getBean($module_name);
    if (empty($seed)) {
        $error->set_error('no_module');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    if (!($seed->ACLAccess('Export') && $seed->ACLAccess('list'))) {
        $error->set_error('no_access');
        return array('result_count' => -1, 'entry_list' => array(), 'error' => $error->get_soap_array());
    }
    require_once 'include/SugarSQLValidate.php';
    $valid = new SugarSQLValidate();
    if (!$valid->validateQueryClauses($query, $order_by)) {
        $GLOBALS['log']->error("Bad query: {$query} {$order_by}");
        $error->set_error('no_access');
        return array('result_count' => -1, 'error' => $error->get_soap_array());
    }
    if ($query == '') {
        $where = '';
    }
    if ($offset == '' || $offset == -1) {
        $offset = 0;
    }
    if ($using_cp) {
        $response = $seed->retrieveTargetList($query, $select_fields, $offset, -1, -1, $deleted);
    } else {
        $response = $seed->get_list($order_by, $query, $offset, -1, -1, $deleted, true, $select_fields);
    }
    $list = $response['list'];
    $output_list = array();
    $isEmailModule = false;
    if ($module_name == 'Emails') {
        $isEmailModule = true;
    }
    // retrieve the vardef information on the bean's fields.
    $field_list = array();
    require_once 'modules/Currencies/Currency.php';
    $currencies = array();
    foreach ($list as $value) {
        if (isset($value->emailAddress)) {
            $value->emailAddress->handleLegacyRetrieve($value);
        }
        if ($isEmailModule) {
            $value->retrieveEmailText();
        }
        $value->fill_in_additional_detail_fields();
        // bug 55129 - populate currency from user settings
        if (property_exists($value, 'currency_id')) {
            if (!isset($currencies[$value->currency_id])) {
                $currencies[$value->currency_id] = SugarCurrency::getCurrencyByID($value->currency_id);
            }
            $row_currency = $currencies[$value->currency_id];
            // walk through all currency-related fields
            foreach ($value->field_defs as $temp_field) {
                if (isset($temp_field['type']) && 'relate' == $temp_field['type'] && isset($temp_field['module']) && 'Currencies' == $temp_field['module'] && isset($temp_field['id_name']) && 'currency_id' == $temp_field['id_name']) {
                    // populate related properties manually
                    $temp_property = $temp_field['name'];
                    $currency_property = $temp_field['rname'];
                    $value->{$temp_property} = $row_currency->{$currency_property};
                }
            }
        }
        // end of bug 55129
        $output_list[] = get_return_value($value, $module_name);
        if (empty($field_list)) {
            $field_list = get_field_list($value);
        }
    }
    // Filter the search results to only include the requested fields.
    $output_list = filter_return_list($output_list, $select_fields, $module_name);
    // Filter the list of fields to only include information on the requested fields.
    $field_list = filter_return_list($field_list, $select_fields, $module_name);
    // Calculate the offset for the start of the next page
    $next_offset = $offset + sizeof($output_list);
    return array('result_count' => sizeof($output_list), 'next_offset' => $next_offset, 'field_list' => $field_list, 'entry_list' => $output_list, 'error' => $error->get_soap_array());
}
Example #10
0
 /**
  * Used by the dependency manager to pre-load all the related fields required
  * to load an entire view.
  */
 public function getRelatedValues($api, $args)
 {
     if (empty($args['module']) || empty($args['fields'])) {
         return;
     }
     $fields = json_decode(html_entity_decode($args['fields']), true);
     $focus = $this->loadBean($api, $args);
     $ret = array();
     foreach ($fields as $rfDef) {
         if (!isset($rfDef['link']) || !isset($rfDef['type'])) {
             continue;
         }
         $link = $rfDef['link'];
         $type = $rfDef['type'];
         $rField = '';
         if (!isset($ret[$link])) {
             $ret[$link] = array();
         }
         if (empty($ret[$link][$type])) {
             $ret[$link][$type] = array();
         }
         // count formulas don't have a relate attribute
         if (isset($rfDef['relate'])) {
             $rField = $rfDef['relate'];
         }
         switch ($type) {
             //The Related function is used for pulling a sing field from a related record
             case "related":
                 //Default it to a blank value
                 $ret[$link]['related'][$rfDef['relate']] = "";
                 //If we have neither a focus id nor a related record id, we can't retrieve anything
                 $relBean = null;
                 if (empty($rfDef['relId']) || empty($rfDef['relModule'])) {
                     //If the relationship is invalid, just move onto another field
                     if (!$focus->load_relationship($link)) {
                         break;
                     }
                     $beans = $focus->{$link}->getBeans(array("enforce_teams" => true));
                     //No related beans means no value
                     if (empty($beans)) {
                         break;
                     }
                     //Grab the first bean on the list
                     reset($beans);
                     $relBean = current($beans);
                 } else {
                     $relBean = BeanFactory::getBean($rfDef['relModule'], $rfDef['relId']);
                 }
                 //If we found a bean and the current user has access to the related field, grab a value from it
                 if (!empty($relBean) && ACLField::hasAccess($rfDef['relate'], $relBean->module_dir, $GLOBALS['current_user']->id, true)) {
                     $validFields = FormulaHelper::cleanFields($relBean->field_defs, false, true, true);
                     if (isset($validFields[$rfDef['relate']])) {
                         $ret[$link]['relId'] = $relBean->id;
                         $ret[$link]['related'][$rfDef['relate']] = FormulaHelper::getFieldValue($relBean, $rfDef['relate']);
                     }
                 }
                 break;
             case "count":
                 if ($focus->load_relationship($link)) {
                     $ret[$link][$type] = count($focus->{$link}->get());
                 } else {
                     $ret[$link][$type] = 0;
                 }
                 break;
             case "rollupSum":
             case "rollupAve":
             case "rollupMin":
             case "rollupMax":
                 //If we are going to calculate one rollup, calculate all the rollups since there is so little cost
                 if ($focus->load_relationship($link)) {
                     $relBeans = $focus->{$link}->getBeans(array("enforce_teams" => true));
                     $sum = 0;
                     $count = 0;
                     $min = false;
                     $max = false;
                     if (!empty($relBeans)) {
                         //Check if the related record vardef has banned this field from formulas
                         $relBean = reset($relBeans);
                         $validFields = FormulaHelper::cleanFields($relBean->field_defs, false, true, true);
                         if (!isset($validFields[$rField])) {
                             $ret[$link][$type][$rField] = 0;
                             break;
                         }
                     }
                     foreach ($relBeans as $bean) {
                         if (isset($bean->{$rField}) && is_numeric($bean->{$rField}) && ACLField::hasAccess($rField, $bean->module_dir, $GLOBALS['current_user']->id, true)) {
                             $count++;
                             $sum += floatval($bean->{$rField});
                             if ($min === false || $bean->{$rField} < $min) {
                                 $min = floatval($bean->{$rField});
                             }
                             if ($max === false || $bean->{$rField} > $max) {
                                 $max = floatval($bean->{$rField});
                             }
                         }
                     }
                     if ($type == "rollupSum") {
                         $ret[$link][$type][$rField] = $sum;
                     }
                     if ($type == "rollupAve") {
                         $ret[$link][$type][$rField] = $count == 0 ? 0 : $sum / $count;
                     }
                     if ($type == "rollupMin") {
                         $ret[$link][$type][$rField] = $min;
                     }
                     if ($type == "rollupMax") {
                         $ret[$link][$type][$rField] = $max;
                     }
                 } else {
                     $ret[$link][$type][$rField] = 0;
                 }
                 break;
             case "rollupCurrencySum":
                 $ret[$link][$type][$rField] = 0;
                 if ($focus->load_relationship($link)) {
                     $toRate = isset($focus->base_rate) ? $focus->base_rate : null;
                     $relBeans = $focus->{$link}->getBeans(array("enforce_teams" => true));
                     $sum = 0;
                     foreach ($relBeans as $bean) {
                         if (!empty($bean->{$rField}) && is_numeric($bean->{$rField}) && ACLField::hasAccess($rField, $bean->module_dir, $GLOBALS['current_user']->id, true)) {
                             $sum = SugarMath::init($sum)->add(SugarCurrency::convertWithRate($bean->{$rField}, $bean->base_rate, $toRate))->result();
                         }
                     }
                     $ret[$link][$type][$rField] = $sum;
                 }
                 break;
         }
     }
     return $ret;
 }
 /**
  * @param string $data The job data set for this particular Scheduled Job instance
  * @return boolean true if the run succeeded; false otherwise
  */
 public function run($data)
 {
     $settings = Opportunity::getSettings();
     if (isset($settings['opps_view_by']) && $settings['opps_view_by'] !== 'Opportunities') {
         $GLOBALS['log']->fatal("Opportunity are being used with Revenue Line Items. " . __CLASS__ . " should not be running");
         return false;
     }
     $args = json_decode(html_entity_decode($data), true);
     $this->job->runnable_ran = true;
     $labels = $args['labels'];
     $data = $args['chunk'];
     $currencies = array();
     Activity::disable();
     // disable the fts index as well
     /* @var $ftsSearch SugarSearchEngineElastic */
     $ftsSearch = SugarSearchEngineFactory::getInstance();
     $ftsSearch->setForceAsyncIndex(true);
     foreach ($data as $opp_id => $rli_data) {
         /* @var $opp Opportunity */
         $opp = BeanFactory::getBean('Opportunities', $opp_id);
         /* @var $note Note */
         $note = BeanFactory::getBean('Notes');
         $note->parent_id = $opp_id;
         $note->parent_type = 'Opportunities';
         $note->assigned_user_id = $opp->assigned_user_id;
         $note->created_by = $opp->created_by;
         $note->name = 'Previous Associated Revenue Line Items';
         $desc = '';
         foreach ($rli_data as $rli) {
             $desc .= $rli['name'] . "\n";
             foreach ($rli as $field => $value) {
                 if (isset($labels[$field])) {
                     if ($field === 'currency_id') {
                         if (!isset($currencies[$value])) {
                             $currencies[$value] = SugarCurrency::getCurrencyByID($value);
                         }
                         $desc .= " - " . $labels[$field] . ": " . $currencies[$value]->name . "\n";
                     } elseif ($field !== 'name' && $field !== 'opportunity_id') {
                         $desc .= " - " . $labels[$field] . ": " . $value . "\n";
                     }
                 }
             }
             $desc .= "\n\n";
         }
         $note->description = trim($desc);
         $note->save();
     }
     // set it back to the default value from the config.
     $ftsSearch->setForceAsyncIndex(SugarConfig::getInstance()->get('search_engine.force_async_index', false));
     Activity::enable();
     $this->job->succeedJob();
     $this->notifyAssignedUser();
     return true;
 }
Example #12
0
 /**
  * @param ServiceBase $api
  * @param array $args
  * @return array
  * @throws SugarApiExceptionInvalidParameter
  * @throws SugarApiExceptionNotAuthorized
  * @throws SugarApiExceptionNotFound
  */
 public function pipeline(ServiceBase $api, $args)
 {
     // if not in the allowed module list, then we throw a 404 not found
     if (!in_array($args['module'], $this->allowedModules)) {
         throw new SugarApiExceptionNotFound();
     }
     // make sure we can view the module first
     // since we don't have a proper record just make an empty one
     $args['record'] = '';
     /* @var $seed Opportunity|Product|RevenueLineItem */
     $seed = $this->loadBean($api, $args, 'view');
     if (!$seed->ACLAccess('view')) {
         throw new SugarApiExceptionNotAuthorized();
     }
     $tp = $this->getTimeperiod($args['timeperiod_id']);
     // check the type param
     if (!isset($args['type']) || $args['type'] != 'user' && $args['type'] != 'group') {
         $args['type'] = 'user';
     }
     $settings = $this->getForecastSettings();
     // get sales_stages to ignore
     $ignore_stages = array_merge($settings['sales_stage_won'], $settings['sales_stage_lost']);
     // get the amount field here
     $amount_field = $this->moduleAmountField[$seed->module_name];
     $sq = $this->buildQuery($api, $seed, $tp, $amount_field, $args['type']);
     // run the query
     $rows = $sq->execute();
     // data storage
     $data = array();
     // keep track of the total for later user
     $total = SugarMath::init('0', 0);
     foreach ($rows as $row) {
         // if the sales stage is one we need to ignore, the just continue to the next record
         if (in_array($row['sales_stage'], $ignore_stages)) {
             continue;
         }
         // if we have not seen this sales stage before, set the value to zero (0)
         if (!isset($data[$row['sales_stage']])) {
             $data[$row['sales_stage']] = array('count' => 0, 'total' => '0');
         }
         // if customers have made amount not required, it saves to the DB as NULL
         // make sure we set it to 0 for the math ahead
         if (empty($row['amount'])) {
             $row['amount'] = 0;
         }
         // convert to the base currency
         $base_amount = SugarCurrency::convertWithRate($row[$amount_field], $row['base_rate']);
         // add the new value into what was already there
         $data[$row['sales_stage']]['total'] = SugarMath::init($data[$row['sales_stage']]['total'], 0)->add($base_amount)->result();
         $data[$row['sales_stage']]['count']++;
         // add to the total
         $total->add($base_amount);
     }
     // get the default currency
     /* @var $currency Currency */
     $currency = SugarCurrency::getBaseCurrency();
     // setup for return format
     $return_data = array();
     $series = 0;
     $previous_value = SugarMath::init('0', 0);
     foreach ($data as $key => $item) {
         $value = $item['total'];
         // set up each return key
         $return_data[] = array('key' => $key, 'count' => $item['count'], 'values' => array(array('series' => $series++, 'label' => SugarCurrency::formatAmount($value, $currency->id, 0), 'value' => intval($value), 'x' => 0, 'y' => intval($value), 'y0' => intval($previous_value->result()))));
         // save the previous value for use in the next item in the series
         $previous_value->add($value);
     }
     // actually return the formatted data
     $mod_strings = return_module_language($GLOBALS['current_language'], $seed->module_name);
     //return the total from the SugarMath Object.
     $total = $total->result();
     return array('properties' => array('title' => $mod_strings['LBL_PIPELINE_TOTAL_IS'] . SugarCurrency::formatAmount($total, $currency->id), 'total' => $total, 'scale' => 1000, 'units' => $currency->symbol), 'data' => $return_data);
 }
Example #13
0
if (empty($focus->id)) {
    // bug 14323, add this to create products firsts, and create the quotes at last,
    // so the workflow can manipulate the products.
    $focus->id = create_guid();
    $focus->new_with_id = true;
}
//remove the relate id element if this is a duplicate
if (isset($_REQUEST['duplicateSave']) && isset($_REQUEST['relate_id'])) {
    //this is a 'create duplicate' quote, keeping the relate_id in focus will assign the quote product bundles
    //to the original quote, not the new duplicate one, so we will unset the element
    unset($_REQUEST['relate_id']);
}
// since the ProductBundles and Products get the BaseRate from the Quote
// make sure it's set correctly before we do any of that processing.
// This will ensure that SugarLogic doesn't do weird conversion.
SugarCurrency::verifyCurrencyBaseRateSet($focus, !$focus->new_with_id);
global $beanFiles;
require_once $beanFiles['Product'];
$GLOBALS['log']->debug("Saving associated products");
$i = 0;
if (isset($_POST['product_count'])) {
    $product_count = $_POST['product_count'];
}
//totals keys is a list of tables for the products bundles
if (isset($_REQUEST['total'])) {
    $total_keys = array_keys($_REQUEST['total']);
} else {
    $total_keys = array();
}
$product_bundels = array();
for ($k = 0; $k < sizeof($total_keys); $k++) {
 /**
  * This method emulates the Forecast Manager Worksheet calculateTotals method.
  *
  * @param string $userId
  * @param string $timeperiodId
  * @param boolean $useDraftRecords
  * @return array|bool            Return calculated totals or boolean false if timeperiod is not valid
  */
 public function worksheetTotals($userId, $timeperiodId, $useDraftRecords = false)
 {
     /* @var $tp TimePeriod */
     $tp = BeanFactory::getBean('TimePeriods', $timeperiodId);
     if (empty($tp->id)) {
         // timeperiod not found
         return false;
     }
     $return = array("quota" => '0', "best_case" => '0', "best_adjusted" => '0', "likely_case" => '0', "likely_adjusted" => '0', "worst_case" => '0', "worst_adjusted" => '0', "included_opp_count" => 0, "pipeline_opp_count" => 0, "pipeline_amount" => '0', "closed_amount" => '0');
     global $current_user;
     require_once 'include/SugarQuery/SugarQuery.php';
     $sq = new SugarQuery();
     $bean_obj = BeanFactory::getBean($this->module_name);
     $sq->select(array($bean_obj->getTableName() . '.*'));
     $sq->from($bean_obj)->where()->equals('timeperiod_id', $tp->id)->equals('assigned_user_id', $userId)->equals('draft', $current_user->id == $userId || $useDraftRecords === true ? 1 : 0)->equals('deleted', 0);
     $results = $sq->execute();
     foreach ($results as $row) {
         $return['quota'] = SugarMath::init($return['quota'], 6)->add(SugarCurrency::convertWithRate($row['quota'], $row['base_rate']))->result();
         $return['best_case'] = SugarMath::init($return['best_case'], 6)->add(SugarCurrency::convertWithRate($row['best_case'], $row['base_rate']))->result();
         $return['best_adjusted'] = SugarMath::init($return['best_adjusted'], 6)->add(SugarCurrency::convertWithRate($row['best_case_adjusted'], $row['base_rate']))->result();
         $return['likely_case'] = SugarMath::init($return['likely_case'], 6)->add(SugarCurrency::convertWithRate($row['likely_case'], $row['base_rate']))->result();
         $return['likely_adjusted'] = SugarMath::init($return['likely_adjusted'], 6)->add(SugarCurrency::convertWithRate($row['likely_case_adjusted'], $row['base_rate']))->result();
         $return['worst_case'] = SugarMath::init($return['worst_case'], 6)->add(SugarCurrency::convertWithRate($row['worst_case'], $row['base_rate']))->result();
         $return['worst_adjusted'] = SugarMath::init($return['worst_adjusted'], 6)->add(SugarCurrency::convertWithRate($row['worst_case_adjusted'], $row['base_rate']))->result();
         $return['closed_amount'] = SugarMath::init($return['closed_amount'], 6)->add(SugarCurrency::convertWithRate($row['closed_amount'], $row['base_rate']))->result();
         $return['included_opp_count'] += $row['opp_count'];
         $return['pipeline_opp_count'] += $row['pipeline_opp_count'];
         $return['pipeline_amount'] = SugarMath::init($return['pipeline_amount'], 6)->add($row['pipeline_amount'])->result();
     }
     return $return;
 }
Example #15
0
 public function save($check_notify = false)
 {
     // set the currency for the forecast to always be the base currency
     // since the committed end point only sends the data as the base currency format
     if (empty($this->currency_id)) {
         // use user preferences for currency
         $currency = SugarCurrency::getBaseCurrency();
         $this->currency_id = $currency->id;
     } else {
         $currency = SugarCurrency::getCurrencyByID($this->currency_id);
     }
     $this->base_rate = $currency->conversion_rate;
     parent::save($check_notify);
 }
 /**
  * Updates currency values for Product Bundles and Quotes based on the Products table
  */
 public function fixQuoteAndProductBundleValues()
 {
     // Collect all quote, product_bundle and products data
     $sql = "\n            SELECT\n            PBQ.quote_id AS quote_id,\n            PBQ.bundle_id AS bundle_id,\n            Q.currency_id AS currency_id,\n            PB.shipping as shipping,\n            P.quantity AS quantity,\n            P.discount_price AS discount_price,\n            P.discount_amount AS discount_amount,\n            P.discount_select AS discount_select,\n            T.value AS tax_value,\n            P.tax_class AS tax_class\n            FROM\n            quotes Q LEFT JOIN taxrates T ON Q.taxrate_id = T.id,\n            product_bundles PB,\n            product_bundle_quote PBQ,\n            product_bundle_product PBP,\n            products P\n            WHERE\n            Q.id = PBQ.quote_id\n            AND PBQ.bundle_id = PB.id\n            AND PBQ.bundle_id = PBP.bundle_id\n            AND PBP.product_id = P.id\n        ";
     $bundles = array();
     $quotes = array();
     $result = $this->db->query($sql);
     while ($row = $this->db->fetchByAssoc($result)) {
         if (empty($bundles[$row['bundle_id']])) {
             $bundles[$row['bundle_id']] = array('tax' => 0, 'subtotal' => 0, 'deal_tot' => 0, 'new_sub' => 0);
         }
         $subtotal = $row['quantity'] * $row['discount_price'];
         if ($row['discount_select'] != 1) {
             $deal_tot = $row['quantity'] * $row['discount_amount'];
         } else {
             $deal_tot = $row['quantity'] * ($row['discount_amount'] * $row['discount_price'] / 100);
         }
         $new_sub = $subtotal - $deal_tot;
         // Calculate the aggregate fields
         $bundles[$row['bundle_id']]['subtotal'] += $subtotal;
         $bundles[$row['bundle_id']]['deal_tot'] += $deal_tot;
         $bundles[$row['bundle_id']]['new_sub'] += $new_sub;
         // If field is taxable, add tax for it
         if ($row['tax_class'] == 'Taxable') {
             $bundles[$row['bundle_id']]['tax'] += $row['tax_value'] * $new_sub / 100;
         }
         $bundles[$row['bundle_id']]['shipping'] = $row['shipping'];
         $bundles[$row['bundle_id']]['currency_id'] = $row['currency_id'];
         $bundles[$row['bundle_id']]['quote_id'] = $row['quote_id'];
         $quotes[$row['quote_id']] = array('tax' => 0, 'subtotal' => 0, 'deal_tot' => 0, 'new_sub' => 0, 'shipping' => 0, 'total' => 0, 'tax_usdollar' => 0, 'subtotal_usdollar' => 0, 'deal_tot_usdollar' => 0, 'new_sub_usdollar' => 0, 'shipping_usdollar' => 0, 'total_usdollar' => 0);
     }
     // Build total and _usdollar fields
     foreach ($bundles as $id => $value) {
         $bundles[$id]['total'] = $value['tax'] + $value['new_sub'] + $value['shipping'];
         $bundles[$id]['tax_usdollar'] = SugarCurrency::convertAmountToBase($value['tax'], $value['currency_id']);
         $bundles[$id]['subtotal_usdollar'] = SugarCurrency::convertAmountToBase($value['subtotal'], $value['currency_id']);
         $bundles[$id]['deal_tot_usdollar'] = SugarCurrency::convertAmountToBase($value['deal_tot'], $value['currency_id']);
         $bundles[$id]['new_sub_usdollar'] = SugarCurrency::convertAmountToBase($value['new_sub'], $value['currency_id']);
         $bundles[$id]['shipping_usdollar'] = SugarCurrency::convertAmountToBase($bundles[$id]['shipping'], $value['currency_id']);
         $bundles[$id]['total_usdollar'] = SugarCurrency::convertAmountToBase($bundles[$id]['total'], $value['currency_id']);
     }
     // Cycle through the bundles and update the values for them
     foreach ($bundles as $id => $values) {
         $quoteId = $values['quote_id'];
         unset($values['currency_id']);
         unset($values['quote_id']);
         // Build the fields to be updated
         $sqlFields = array();
         foreach ($values as $fieldId => $fieldValue) {
             $sqlFields[] = "{$fieldId} = '{$fieldValue}'";
             // Fill in quote values
             $quotes[$quoteId][$fieldId] += $fieldValue;
         }
         // Update the product_bundle values
         $sql = "UPDATE product_bundles SET " . implode(', ', $sqlFields) . " WHERE id = '{$id}'";
         $this->db->query($sql);
     }
     // Cycle through the quotes and update the values for them
     foreach ($quotes as $id => $values) {
         // Build the fields to be updated
         $sqlFields = array();
         foreach ($values as $fieldId => $fieldValue) {
             $sqlFields[] = "{$fieldId} = '{$fieldValue}'";
         }
         // Update the product_bundle values
         $sql = "UPDATE quotes SET " . implode(', ', $sqlFields) . " WHERE id = '{$id}'";
         $this->db->query($sql);
     }
 }
Example #17
0
 /**
  * Handle the mapping of the fields from the product template to the product
  */
 protected function mapFieldsFromProductTemplate()
 {
     if (!empty($this->product_template_id) && $this->fetched_row['product_template_id'] != $this->product_template_id) {
         /* @var $pt ProductTemplate */
         $pt = BeanFactory::getBean('ProductTemplates', $this->product_template_id);
         $this->category_id = $pt->category_id;
         $this->mft_part_num = $pt->mft_part_num;
         $this->list_price = SugarCurrency::convertAmount($pt->list_price, $pt->currency_id, $this->currency_id);
         $this->cost_price = SugarCurrency::convertAmount($pt->cost_price, $pt->currency_id, $this->currency_id);
         $this->discount_price = SugarCurrency::convertAmount($pt->discount_price, $pt->currency_id, $this->currency_id);
         // discount_price = unit price on the front end...
         $this->list_usdollar = $pt->list_usdollar;
         $this->cost_usdollar = $pt->cost_usdollar;
         $this->discount_usdollar = $pt->discount_usdollar;
         $this->tax_class = $pt->tax_class;
         $this->weight = $pt->weight;
     }
 }
Example #18
0
 /**
  * @see SugarView::display()
  */
 public function display()
 {
     require_once 'modules/Quotes/Layouts.php';
     require_once 'include/EditView/EditView2.php';
     global $beanFiles;
     require_once $beanFiles['Quote'];
     require_once $beanFiles['TaxRate'];
     require_once $beanFiles['Shipper'];
     global $mod_strings;
     global $app_strings;
     global $app_list_strings;
     global $current_user;
     global $timedate;
     global $locale;
     $original_quote = BeanFactory::getBean('Quotes');
     if ($this->ev->isDuplicate) {
         $this->bean->id = "";
         $this->bean->quote_num = "";
         $original_quote->retrieve($_REQUEST['record']);
     }
     //needed when creating a new quote only with a default account value passed in
     if (empty($this->bean->id) && !$this->ev->isDuplicate) {
         $this->bean->quote_num = '';
         $this->bean->total = '0.00';
         $this->bean->shipping = '0.00';
         $this->bean->tax = '0.00';
         $this->bean->subtotal = '0.00';
         if (isset($_REQUEST['opportunity_name'])) {
             $this->bean->opportunity_name = $_REQUEST['opportunity_name'];
         }
         if (isset($_REQUEST['opportunity_id'])) {
             $this->bean->opportunity_id = $_REQUEST['opportunity_id'];
         }
         if (isset($_REQUEST['account_name'])) {
             $this->bean->billing_account_name = $_REQUEST['account_name'];
             $this->bean->shipping_account_name = $_REQUEST['account_name'];
         }
         if (isset($_REQUEST['account_id'])) {
             $this->bean->billing_account_id = $_REQUEST['account_id'];
             $this->bean->shipping_account_id = $_REQUEST['account_id'];
             require_once $beanFiles['Account'];
             $account = BeanFactory::getBean('Accounts', $this->bean->shipping_account_id);
             $this->bean->shipping_address_street = $account->shipping_address_street;
             $this->bean->shipping_address_city = $account->shipping_address_city;
             $this->bean->shipping_address_state = $account->shipping_address_state;
             $this->bean->shipping_address_country = $account->shipping_address_country;
             $this->bean->shipping_address_postalcode = $account->shipping_address_postalcode;
             $this->bean->billing_address_street = $account->billing_address_street;
             $this->bean->billing_address_city = $account->billing_address_city;
             $this->bean->billing_address_state = $account->billing_address_state;
             $this->bean->billing_address_country = $account->billing_address_country;
             $this->bean->billing_address_postalcode = $account->billing_address_postalcode;
         }
         if (isset($_REQUEST['contact_id'])) {
             $this->bean->contact_id = $_REQUEST['contact_id'];
             require_once $beanFiles['Contact'];
             $contact = BeanFactory::getBean('Contacts', $this->bean->contact_id);
             $this->bean->billing_contact_name = $locale->formatName($contact);
             $this->bean->billing_contact_id = $contact->id;
             $this->bean->shipping_contact_name = $locale->formatName($contact);
             $this->bean->shipping_contact_id = $contact->id;
             $this->bean->shipping_address_street = $contact->primary_address_street;
             $this->bean->shipping_address_city = $contact->primary_address_city;
             $this->bean->shipping_address_state = $contact->primary_address_state;
             $this->bean->shipping_address_country = $contact->primary_address_country;
             $this->bean->shipping_address_postalcode = $contact->primary_address_postalcode;
         }
         if (isset($_REQUEST['date_quote_expected_closed'])) {
             $this->bean->date_quote_expected_closed = $_REQUEST['date_quote_expected_closed'];
         }
         if (isset($_REQUEST['currency_id'])) {
             $this->bean->currency_id = $_REQUEST['currency_id'];
         }
     }
     $currency = BeanFactory::getBean('Currencies', $this->bean->currency_id);
     // Set the number grouping and decimal separators
     $seps = get_number_seperators();
     $dec_sep = $seps[1];
     $num_grp_sep = $seps[0];
     $this->ss->assign('NUM_GRP_SEP', $num_grp_sep);
     $this->ss->assign('DEC_SEP', $dec_sep);
     $significantDigits = $locale->getPrecedentPreference('default_currency_significant_digits', $current_user);
     $this->ss->assign('PRECISION', $significantDigits);
     if ((is_admin($current_user) || is_admin_for_module($GLOBALS['current_user'], 'Quotes')) && $_REQUEST['module'] != 'DynamicLayout' && !empty($_SESSION['editinplace'])) {
         $record = '';
         if (!empty($_REQUEST['record'])) {
             $record = $_REQUEST['record'];
         }
         $this->ss->assign('ADMIN_EDIT', "<a href='index.php?action=index&module=DynamicLayout&from_action=" . $_REQUEST['action'] . "&from_module=" . $_REQUEST['module'] . "&record=" . $record . "'>" . SugarThemeRegistry::current()->getImage("EditLayout", "border='0' align='bottom'", null, null, '.gif', $mod_strings['LBL_EDITLAYOUT']) . "</a>");
     }
     $this->ss->assign('QUOTE_STAGE_OPTIONS', get_select_options_with_id($app_list_strings['quote_stage_dom'], $this->bean->quote_stage));
     $this->ss->assign('DEFAULT_PRODUCT_STATUS', $app_list_strings['product_status_quote_key']);
     if (isset($this->bean->subtotal)) {
         $this->ss->assign('SUBTOTAL', $this->bean->subtotal);
     } else {
         $this->ss->assign('SUBTOTAL', "0.00");
     }
     if (isset($this->bean->tax)) {
         $this->ss->assign('TAX', $this->bean->tax);
     } else {
         $this->ss->assign('TAX', "0.00");
     }
     if (isset($this->bean->shipping)) {
         $this->ss->assign("SHIPPING", $this->bean->shipping);
     } else {
         $this->ss->assign('SHIPPING', "0.00");
     }
     if (isset($this->bean->deal_tot)) {
         $this->ss->assign('DEAL_TOT', $this->bean->deal_tot);
     } else {
         $this->ss->assign('DEAL_TOT', "0.00");
     }
     if (isset($this->bean->new_sub)) {
         $this->ss->assign('NEW_SUB', $this->bean->new_sub);
     } else {
         $this->ss->assign('NEW_SUB', "0.00");
     }
     if (isset($this->bean->total)) {
         $this->ss->assign('TOTAL', $this->bean->total);
     } else {
         $this->ss->assign('TOTAL', "0.00");
     }
     if (isset($this->bean->subtotal_usdollar)) {
         $this->ss->assign('SUBTOTAL_USDOLLAR', $this->bean->subtotal_usdollar);
     } else {
         $this->ss->assign('SUBTOTAL_USDOLLAR', "0.00");
     }
     if (isset($this->bean->tax_usdollar)) {
         $this->ss->assign('TAX_USDOLLAR', $this->bean->tax_usdollar);
     } else {
         $this->ss->assign('TAX_USDOLLAR', "0.00");
     }
     if (isset($this->bean->shipping_usdollar)) {
         $this->ss->assign('SHIPPING_USDOLLAR', $this->bean->shipping_usdollar);
     } else {
         $this->ss->assign('SHIPPING_USDOLLAR', "0.00");
     }
     if (isset($this->bean->total_usdollar)) {
         $this->ss->assign('TOTAL_USDOLLAR', $this->bean->total_usdollar);
     } else {
         $this->ss->assign('TOTAL_USDOLLAR', "0.00");
     }
     $this->ss->assign('USER_DATEFORMAT', '(' . $timedate->get_user_date_format() . ')');
     $this->ss->assign('CALENDAR_DATEFORMAT', $timedate->get_cal_date_format());
     $taxrate = BeanFactory::getBean('TaxRates');
     $this->ss->assign('TAXRATE_OPTIONS', get_select_options_with_id($taxrate->get_taxrates(false), $this->bean->taxrate_id));
     if (empty($this->bean->taxrate_value)) {
         $this->ss->assign('TAXRATE_VALUE', $taxrate->get_default_taxrate_value() / 100);
     } else {
         $this->ss->assign('TAXRATE_VALUE', $this->bean->taxrate_value / 100);
     }
     $shipper = BeanFactory::getBean('Shippers');
     $this->ss->assign('SHIPPER_OPTIONS', get_select_options_with_id($shipper->get_shippers(true), $this->bean->shipper_id));
     if (empty($this->bean->assigned_user_id) && empty($this->bean->id)) {
         $this->bean->assigned_user_id = $current_user->id;
     }
     if (empty($this->bean->assigned_name) && empty($this->bean->id)) {
         $this->bean->assigned_user_name = $current_user->user_name;
     }
     $this->ss->assign('ASSIGNED_USER_OPTIONS', get_select_options_with_id(get_user_array(TRUE, 'Active', $this->bean->assigned_user_id), $this->bean->assigned_user_id));
     $this->ss->assign('ASSIGNED_USER_NAME', $this->bean->assigned_user_name);
     $this->ss->assign('ASSIGNED_USER_ID', $this->bean->assigned_user_id);
     if (!empty($this->bean->calc_grand_total) && $this->bean->calc_grand_total == 1) {
         $this->ss->assign('CALC_GRAND_TOTAL_CHECKED', 'checked');
     }
     if (!empty($this->bean->show_line_nums) && $this->bean->show_line_nums == 1) {
         $this->ss->assign('SHOW_LINE_NUMS_CHECKED', 'checked');
     }
     // Set Currency values and currency javascript
     require_once 'modules/Currencies/ListCurrency.php';
     $currency = new ListCurrency();
     $base_rate = '1.00';
     if (isset($this->bean->currency_id) && !empty($this->bean->currency_id)) {
         $curid = $this->bean->currency_id;
     } elseif (isset($_REQUEST['currency_id']) && !empty($_REQUEST['currency_id'])) {
         $curid = $_REQUEST['currency_id'];
     } elseif (empty($this->bean->id)) {
         $curid = $current_user->getPreference('currency');
         if (empty($curid)) {
             $curid = -99;
         }
     } else {
         $curid = -99;
     }
     if ($this->bean->isClosed()) {
         $base_rate = $this->bean->base_rate;
     } else {
         $base_rate = null;
     }
     $selectCurrency = $currency->getSelectOptions($curid, $base_rate);
     $this->ss->assign("CURRENCY", $selectCurrency);
     $this->ss->assign('CURRENCY_JAVASCRIPT', $currency->getJavascript());
     if ($this->bean->fetched_row['date_quote_expected_closed'] == '1970-01-01' || $this->bean->fetched_row['date_quote_expected_closed'] == '0001-01-01') {
         $this->bean->date_quote_expected_closed = '';
     }
     $add_row = array();
     if (!empty($this->bean->id)) {
         $this->bean->load_relationship('product_bundles');
         $product_bundle_list = $this->bean->product_bundles->getBeans();
         usort($product_bundle_list, array('ProductBundle', 'compareProductBundlesByIndex'));
         $quote_currency_id = $this->bean->currency_id;
         $quote_base_rate = $this->bean->base_rate;
         $convert_format = function ($value, $prod_currency, $prod_base_rate) use($quote_currency_id, $quote_base_rate) {
             if ($prod_currency !== $quote_currency_id) {
                 $value = SugarCurrency::convertWithRate($value, $prod_base_rate, $quote_base_rate);
             }
             return SugarCurrency::formatAmountUserLocale($value, $quote_currency_id, false);
         };
         if (is_array($product_bundle_list)) {
             foreach ($product_bundle_list as $product_bundle) {
                 $bundle_list = $product_bundle->get_product_bundle_line_items();
                 $add_row[] = "quotesManager.addTable('{$product_bundle->id}','{$product_bundle->bundle_stage}', '{$product_bundle->name}', '" . format_money($product_bundle->shipping, FALSE) . "' );\n";
                 if (is_array($bundle_list)) {
                     while (list($key, $line_item) = each($bundle_list)) {
                         if ($line_item->object_name == "Product") {
                             /* @var $line_item Product */
                             $tax_class_name = isset($line_item->tax_class) ? $line_item->tax_class : "";
                             $encoded_name = js_escape(br2nl($line_item->name));
                             $add_row[] = "quotesManager.addRow('{$line_item->id}','" . format_number($line_item->quantity, $significantDigits, $significantDigits) . "','{$line_item->product_template_id}','{$encoded_name}'" . ", '" . $convert_format($line_item->cost_price, $line_item->currency_id, $line_item->base_rate) . "'" . ", '" . $convert_format($line_item->list_price, $line_item->currency_id, $line_item->base_rate) . "'" . ", '" . $convert_format($line_item->discount_price, $line_item->currency_id, $line_item->base_rate) . "'" . ", '', '', '{$line_item->pricing_factor}', '{$line_item->tax_class}', '{$tax_class_name}', '{$line_item->mft_part_num}', '{$product_bundle->id}', '{$product_bundle->bundle_stage}', '{$product_bundle->name}', '" . format_number($product_bundle->shipping) . "', '" . js_escape(br2nl($line_item->description)) . "', '" . $line_item->type_id . "'" . ", '" . format_number($line_item->discount_amount, $significantDigits, $significantDigits) . "'" . ", " . ($line_item->discount_select ? 1 : 0) . ", " . ($line_item->deal_calc ? 1 : 0) . ", '" . $line_item->status . "');\n";
                         } else {
                             if ($line_item->object_name == "ProductBundleNote") {
                                 /* @var $line_item ProductBundleNote */
                                 $encoded_description = js_escape(br2nl($line_item->description));
                                 //$encoded_description = html_entity_decode($encoded_description);
                                 $add_row[] = "quotesManager.addCommentRow('{$line_item->id}', '{$product_bundle->id}', '{$encoded_description}');\n";
                             }
                         }
                     }
                     //while
                 }
                 //if
             }
             //foreach
         }
     } else {
         // this else part is to create a new product_bundle for the duplicate quote
         $original_quote->load_relationship('product_bundles');
         $product_bundle_list = $original_quote->product_bundles->getBeans();
         usort($product_bundle_list, array('ProductBundle', 'compareProductBundlesByIndex'));
         if (is_array($product_bundle_list)) {
             foreach ($product_bundle_list as $product_bundle) {
                 $product_list = $product_bundle->get_products();
                 if (is_array($product_list)) {
                     foreach ($product_list as $line_item) {
                         $tax_class_name = isset($line_item->tax_class) ? $line_item->tax_class : "";
                         $add_row[] = "quotesManager.addRow('','{$line_item->quantity}','{$line_item->product_template_id}','{$line_item->name}'" . ", '" . format_number($line_item->cost_usdollar, $significantDigits, $significantDigits, array('convert' => true, 'currency_id' => $curid)) . "'" . ", '" . format_number($line_item->list_usdollar, $significantDigits, $significantDigits, array('convert' => true, 'currency_id' => $curid)) . "'" . ", '" . format_number($line_item->discount_usdollar, $significantDigits, $significantDigits, array('convert' => true, 'currency_id' => $curid)) . "'" . ", '', '', '{$line_item->pricing_factor}', '{$line_item->tax_class}', '{$tax_class_name}',\n\t\t\t\t\t\t\t\t'{$line_item->mft_part_num}', 'group_{$product_bundle->id}', '{$product_bundle->bundle_stage}', '{$product_bundle->name}', '" . format_money($product_bundle->shipping, FALSE) . "', '" . js_escape(br2nl($line_item->description)) . "', '" . $line_item->type_id . "','" . format_number($line_item->discount_amount_usdollar, $significantDigits, $significantDigits, array('convert' => !$line_item->discount_select, 'currency_id' => $curid)) . "'," . ($line_item->discount_select ? 1 : 0) . ",0, '" . $line_item->status . "');\n";
                     }
                     //foreach
                     if (empty($product_list)) {
                         $add_row[] = "quotesManager.addTable('group_{$product_bundle->id}','{$product_bundle->bundle_stage}', '{$product_bundle->name}' , ' " . format_money($product_bundle->shipping, FALSE) . "');\n";
                     }
                     //if
                     //bug 39573 - Comments are not duplicated in quotes
                     $bundle_list = $product_bundle->get_product_bundle_line_items();
                     if (is_array($bundle_list)) {
                         while (list($key, $line_item) = each($bundle_list)) {
                             if ($line_item->object_name == "ProductBundleNote") {
                                 $encoded_description = js_escape(br2nl($line_item->description));
                                 $add_row[] = "quotesManager.addCommentRow('{$line_item->id}', 'group_{$product_bundle->id}', '{$encoded_description}');\n";
                             }
                         }
                     }
                     //end bug 39573
                 }
                 //if
             }
         }
     }
     //if-else for !empty($this->bean->id)
     //Bug#53607: Create the javascript code to store the rendering function in a queue
     $add_row_js = 'var add_row_stack = [];';
     foreach ($add_row as $script_command) {
         $add_row_js .= "add_row_stack.push(function(){\n                {$script_command}\n            });";
     }
     //Bug#53607: Rather than executing all rendering row script once, it will keep in a queue.
     //           And it will render the specified number of rows every interval.
     $add_row_js .= "function add_rows_on_load() {\n            if(typeof add_row_stack != 'undefined' && add_row_stack.length > 0) {\n                //interval is in msec,\n                //size is the number of rows rendering every time\n                asyncLoading = true; // to indicate that the content is still loading\n                var _interval = 100,\n                    _size = 3,\n                    _exec = add_row_stack.splice(0, _size),\n                    _header_button = document.getElementById('SAVE_HEADER'),\n                    _footer_button = document.getElementById('SAVE_FOOTER');\n                if(_header_button) {\n                    _header_button.disabled = true;\n                }\n                if(_footer_button) {\n                    _footer_button.disabled = true;\n                }\n                for(idx in _exec) {\n                    _exec[idx]();\n                }\n                window.setTimeout(add_rows_on_load, _interval);\n            } else {\n                asyncLoading = false; // content is loaded\n                var _header_button = document.getElementById('SAVE_HEADER'),\n                    _footer_button = document.getElementById('SAVE_FOOTER');\n                if(_header_button) {\n                    _header_button.disabled = false;\n                }\n                if(_footer_button) {\n                    _footer_button.disabled = false;\n                }\n            }\n        }";
     $this->ss->assign("ADD_ROWS", $add_row_js);
     $setup_script = '';
     $taxclass = translate('tax_class_dom');
     foreach ($taxclass as $value => $name) {
         $setup_script .= "quotesManager.add_tax_class('{$name}', '{$value}');\n";
     }
     $this->ss->assign("SETUP_SCRIPT", $setup_script);
     $this->ss->assign('TAXRATE_JAVASCRIPT', $taxrate->get_taxrate_js());
     $this->ss->assign('CALCULATE_FUNCTION', '<script type="text/javascript">YAHOO.util.Event.onDOMReady(function(){quotesManager.calculate(document);});</script>');
     $this->ss->assign('NO_MATCH_VARIABLE', '<script type="text/javascript">sqs_no_match_text = "' . $app_strings['ERR_SQS_NO_MATCH'] . '";</script>');
     $str = "<script language=\"javascript\">\n\t\tYAHOO.util.Event.onAvailable('add_tables', add_rows_on_load);\n\t\t</script>";
     $this->ss->assign('SAVED_SEARCH_SELECTS', $str);
     parent::display();
     echo '<script>sqs_must_match = false;</script>';
 }
Example #19
0
 /**
  * Return the quota for the current user and time period
  *
  * @return mixed
  */
 protected function getUserQuota()
 {
     /* @var $quota_bean Quota */
     $quota_bean = BeanFactory::getBean('Quotas');
     $quota = $quota_bean->getRollupQuota($this->getArg('timeperiod_id'), $this->getArg('user_id'));
     return SugarCurrency::convertAmountToBase($quota['amount'], $quota['currency_id']);
 }
Example #20
0
 /**
  * Method for sorting the dataArray before we return it so that the tallest bar is always first and the
  * lowest bar is always last.
  *
  * @param array $a          The left side of the compare
  * @param array $b          The right side of the compare
  * @return int
  */
 protected function sortChartColumns($a, $b)
 {
     $sumA = 0;
     $sumB = 0;
     foreach ($this->dataset as $dataset) {
         $sumA += SugarCurrency::convertAmountToBase($a[$dataset . '_case_adjusted'], $a['currency_id']);
         $sumB += SugarCurrency::convertAmountToBase($b[$dataset . '_case_adjusted'], $b['currency_id']);
     }
     if (intval($sumA) > intval($sumB)) {
         return -1;
     } else {
         if (intval($sumA) < intval($sumB)) {
             return 1;
         } else {
             return 0;
         }
     }
 }
 /**
  * Returns the the conversion rate for the passed in currency
  */
 public function evaluate()
 {
     $id = $this->getParameters()->evaluate();
     $currency = SugarCurrency::getCurrencyByID($id);
     return $currency->conversion_rate;
 }
Example #22
0
$smarty->assign("STATUS", $app_list_strings['campaign_status_dom'][$focus->status]);
$smarty->assign("NAME", $focus->name);
$smarty->assign("TYPE", $app_list_strings['campaign_type_dom'][$focus->campaign_type]);
$smarty->assign("START_DATE", $focus->start_date);
$smarty->assign("END_DATE", $focus->end_date);
if (!empty($focus->budget)) {
    $smarty->assign("BUDGET", SugarCurrency::formatAmountUserLocale($focus->budget, $focus->currency_id));
}
if (!empty($focus->actual_cost)) {
    $smarty->assign("ACTUAL_COST", SugarCurrency::formatAmountUserLocale($focus->actual_cost, $focus->currency_id));
}
if (!empty($focus->expected_cost)) {
    $smarty->assign("EXPECTED_COST", SugarCurrency::formatAmountUserLocale($focus->expected_cost, $focus->currency_id));
}
if (!empty($focus->expected_revenue)) {
    $smarty->assign("EXPECTED_REVENUE", SugarCurrency::formatAmountUserLocale($focus->expected_revenue, $focus->currency_id));
}
$smarty->assign("OBJECTIVE", nl2br($focus->objective));
$smarty->assign("CONTENT", nl2br($focus->content));
$smarty->assign("DATE_MODIFIED", $focus->date_modified);
$smarty->assign("DATE_ENTERED", $focus->date_entered);
$smarty->assign("CREATED_BY", $focus->created_by_name);
$smarty->assign("MODIFIED_BY", $focus->modified_by_name);
$smarty->assign("TRACKER_URL", $sugar_config['site_url'] . '/campaign_tracker.php?track=' . $focus->tracker_key);
$smarty->assign("TRACKER_COUNT", intval($focus->tracker_count));
$smarty->assign("TRACKER_TEXT", $focus->tracker_text);
$smarty->assign("REFER_URL", $focus->refer_url);
if (isset($focus->campaign_type) && $focus->campaign_type == "Email" || $focus->campaign_type == "NewsLetter") {
    $smarty->assign("TRACK_DELETE_BUTTON", "<input title=\"{$mod_strings['LBL_TRACK_DELETE_BUTTON_TITLE']}\" class=\"button\" onclick=\"this.form.module.value='Campaigns'; this.form.action.value='Delete';this.form.return_module.value='Campaigns'; this.form.return_action.value='TrackDetailView';this.form.mode.value='Test';return confirm('{$mod_strings['LBL_TRACK_DELETE_CONFIRM']}');\" type=\"submit\" name=\"button\" value=\"  {$mod_strings['LBL_TRACK_DELETE_BUTTON_LABEL']}  \">");
}
$currency = BeanFactory::getBean('Currencies');
Example #23
0
 /**
  * convert amount from base currency
  *
  * @param  float $amount    currency amount in US Dollars
  * @param  int   $precision rounding precision scale
  * @return float  currency  value from US Dollar conversion
  */
 function convertFromBase($amount, $precision = 6)
 {
     $amount = $amount == null ? 0 : $amount;
     return SugarCurrency::convertWithRate(str_replace($this->symbol, '', $amount), 1.0, $this->conversion_rate, $precision);
 }
Example #24
0
 public function save($check_notify = false)
 {
     //if probability is empty, set it based on the sales stage
     if ($this->probability === '' && !empty($this->sales_stage)) {
         $this->mapProbabilityFromSalesStage();
     }
     //if the id is set (previously saved bean) and sales_status is still New, update to in progress
     if (isset($this->id) && !$this->new_with_id && $this->sales_status == Opportunity::STATUS_NEW) {
         $this->sales_status = Opportunity::STATUS_IN_PROGRESS;
     }
     // verify that base_rate is set to the correct amount, moved in from SugarBean
     // as we need this to run before perform_save (which does calculations with base_rate)
     if (isset($this->field_defs['currency_id']) && isset($this->field_defs['base_rate'])) {
         SugarCurrency::verifyCurrencyBaseRateSet($this);
     }
     SugarAutoLoader::requireWithCustom('modules/Opportunities/SaveOverload.php');
     perform_save($this);
     return parent::save($check_notify);
 }
 /**
  * Handles export field sanitizing for field type
  *
  * @param $value string value to be sanitized
  * @param $vardef array representing the vardef definition
  * @param $focus SugarBean object
  * @param $row Array of a row of data to be exported
  *
  * @return string sanitized value
  */
 public function exportSanitize($value, $vardef, $focus, $row = array())
 {
     // If $value is null, default to zero to prevent conversion errors.
     $value = is_null($value) ? 0 : $value;
     require_once 'include/SugarCurrency/SugarCurrency.php';
     if (isset($vardef['convertToBase']) && $vardef['convertToBase']) {
         // convert amount to base
         $baseRate = isset($row['base_rate']) ? $row['base_rate'] : $focus->base_rate;
         $value = SugarCurrency::convertWithRate($value, $baseRate);
         $currency_id = '-99';
     } elseif (isset($vardef['is_base_currency']) && $vardef['is_base_currency']) {
         $currency_id = '-99';
     } else {
         //If the row has a currency_id set, use that instead of the $focus->currency_id value
         $currency_id = isset($row['currency_id']) ? $row['currency_id'] : $focus->currency_id;
     }
     return SugarCurrency::formatAmountUserLocale($value, $currency_id);
 }
Example #26
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", SugarCurrency::formatAmountUserLocale($cost_per_impression, $focus->currency_id));
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", SugarCurrency::formatAmountUserLocale($cost_per_click_thru, $focus->currency_id));
$currency = BeanFactory::getBean('Currencies');
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>");
}
Example #27
0
function create_campaign_summary($focus)
{
    global $mod_strings, $app_strings;
    $fields = array();
    $fields[] = 'name';
    $fields[] = 'assigned_user_name';
    $fields[] = 'status';
    $fields[] = 'team_name';
    $fields[] = 'start_date';
    $fields[] = 'end_date';
    if ($focus->campaign_type == 'NewsLetter') {
        $fields[] = 'frequency';
    }
    $fields[] = 'content';
    $fields[] = 'budget';
    $fields[] = 'actual_cost';
    $fields[] = 'expected_revenue';
    $fields[] = 'expected_cost';
    $fields[] = 'impressions';
    $fields[] = 'objective';
    if (!empty($focus->budget)) {
        $focus->budget = SugarCurrency::formatAmountUserLocale($focus->budget, $focus->currency_id);
    }
    if (!empty($focus->actual_cost)) {
        $focus->actual_cost = SugarCurrency::formatAmountUserLocale($focus->actual_cost, $focus->currency_id);
    }
    if (!empty($focus->expected_cost)) {
        $focus->expected_cost = SugarCurrency::formatAmountUserLocale($focus->expected_cost, $focus->currency_id);
    }
    if (!empty($focus->expected_revenue)) {
        $focus->expected_revenue = SugarCurrency::formatAmountUserLocale($focus->expected_revenue, $focus->currency_id);
    }
    //create edit view status and input buttons
    $cmp_input = '';
    //create edit campaign button
    $cmp_input = "<input id='wiz_next_button' name='SUBMIT'  ";
    $cmp_input .= "onclick=\"this.form.return_module.value='Campaigns';";
    $cmp_input .= "this.form.module.value='Campaigns';";
    $cmp_input .= "this.form.action.value='WizardNewsletter';";
    $cmp_input .= "this.form.return_action.value='WizardHome';";
    $cmp_input .= "this.form.direct_step.value='1';";
    $cmp_input .= "this.form.record.value='" . $focus->id . "';";
    $cmp_input .= "this.form.return_id.value='" . $focus->id . "';\" ";
    $cmp_input .= "class='button' value='" . $mod_strings['LBL_EDIT_EXISTING'] . "' type='submit'> ";
    //create view status button
    if ($focus->campaign_type == 'NewsLetter' || $focus->campaign_type == 'Email') {
        $cmp_input .= " <input id='wiz_status_button' name='SUBMIT'  ";
        $cmp_input .= "onclick=\"this.form.return_module.value='Campaigns';";
        $cmp_input .= "this.form.module.value='Campaigns';";
        $cmp_input .= "this.form.action.value='TrackDetailView';";
        $cmp_input .= "this.form.return_action.value='WizardHome';";
        $cmp_input .= "this.form.record.value='" . $focus->id . "';";
        $cmp_input .= "this.form.return_id.value='" . $focus->id . "';\" ";
        $cmp_input .= "class='button' value='" . $mod_strings['LBL_TRACK_BUTTON_TITLE'] . "' type='submit'>";
    }
    //create view roi button
    $cmp_input .= " <input id='wiz_status_button' name='SUBMIT'  ";
    $cmp_input .= "onclick=\"this.form.return_module.value='Campaigns';";
    $cmp_input .= "this.form.module.value='Campaigns';";
    $cmp_input .= "this.form.action.value='RoiDetailView';";
    $cmp_input .= "this.form.return_action.value='WizardHome';";
    $cmp_input .= "this.form.record.value='" . $focus->id . "';";
    $cmp_input .= "this.form.return_id.value='" . $focus->id . "';\" ";
    $cmp_input .= "class='button' value='" . $mod_strings['LBL_TRACK_ROI_BUTTON_LABEL'] . "' type='submit'>";
    //Create Campaign Header
    $cmpgn_tbl = "<p><table class='edit view' width='100%' border='0' cellspacing='0' cellpadding='0'>";
    $cmpgn_tbl .= "<tr><td class='dataField' align='left'><h4 class='dataLabel'> " . $mod_strings['LBL_LIST_CAMPAIGN_NAME'] . '  ' . $mod_strings['LBL_WIZ_NEWSLETTER_TITLE_SUMMARY'] . " </h4></td>";
    $cmpgn_tbl .= "<td align='right'>{$cmp_input}</td></tr>";
    $colorclass = '';
    foreach ($fields as $key) {
        if (!empty($focus->{$key}) && !empty($mod_strings[$focus->field_name_map[$key]['vname']])) {
            $cmpgn_tbl .= "<tr><td scope='row' width='15%'>" . $mod_strings[$focus->field_name_map[$key]['vname']] . "</td>\n";
            if ($key == 'team_name') {
                require_once 'modules/Teams/TeamSetManager.php';
                $cmpgn_tbl .= "<td scope='row'>" . TeamSetManager::getCommaDelimitedTeams($focus->team_set_id, $focus->team_id, true) . "</td></tr>\n";
            } else {
                $cmpgn_tbl .= "<td scope='row'>" . $focus->{$key} . "</td></tr>\n";
            }
        }
    }
    $cmpgn_tbl .= "</table></p>";
    return $cmpgn_tbl;
}
Example #28
0
 /**
  * Retrieve a user's quota using the rollup value, if available.  This method is useful for
  * fetching user quota data when you're unsure about whether or not the given user is a manager.
  * If you would like to force a direct quota, pass a false value to $should_rollup.
  *
  * @param $timeperiod_id String id of the TimePeriod to retrieve quota for
  * @param $user_id String value of the user id to retrieve.  If NULL, the $current_user is used
  * @param $should_rollup boolean value indicating whether or not the quota should be a rollup calculation; false by default
  *
  * @return array [currency_id => int, amount => number, formatted_amount => String]
  */
 public function getRollupQuota($timeperiod_id, $user_id = null, $should_rollup = false)
 {
     if (is_null($user_id)) {
         global $current_user;
         $user_id = $current_user->id;
     }
     // figure out the timeperiod
     // if we didn't find a time period, set the time period to be the current time period
     if (!is_guid($timeperiod_id) && is_numeric($timeperiod_id) && $timeperiod_id != 0) {
         // we have a timestamp, find timeperiod it belongs in
         $timeperiod_id = TimePeriod::getIdFromTimestamp($timeperiod_id);
     }
     if (!is_guid($timeperiod_id)) {
         $timeperiod_id = TimePeriod::getCurrentId();
     }
     $sq = new SugarQuery();
     $sq->select(array('quotas.currency_id', 'quotas.amount'));
     $sq->from(BeanFactory::getBean('Quotas'));
     $sq->where()->equals('user_id', $user_id)->equals('quota_type', $should_rollup ? 'Rollup' : 'Direct')->equals('timeperiod_id', $timeperiod_id);
     $sq->orderBy('date_modified', 'DESC');
     $sq->limit(1);
     // since there is only ever one row, just shift the value off the results
     $row = array_shift($sq->execute());
     if (empty($row)) {
         // This is to prevent return value of false when a given timeperiod has no quota.
         $row = array('currency_id' => -99, 'amount' => 0);
     }
     $row['formatted_amount'] = SugarCurrency::formatAmountUserLocale($row['amount'], $row['currency_id']);
     return $row;
 }
 /**
  * This method emulates the Forecast Rep Worksheet calculateTotals method.
  *
  * @param string $timeperiod_id
  * @param string $user_id
  * @param string|null $forecast_by
  * @param boolean $useDraftRecords
  * @return array|bool
  */
 public function worksheetTotals($timeperiod_id, $user_id, $forecast_by = null, $useDraftRecords = false)
 {
     /* @var $tp TimePeriod */
     $tp = BeanFactory::getBean('TimePeriods', $timeperiod_id);
     if (empty($tp->id)) {
         // timeperiod not found
         return false;
     }
     /* @var $admin Administration */
     $admin = BeanFactory::getBean('Administration');
     $settings = $admin->getConfigForModule('Forecasts');
     if (is_null($forecast_by)) {
         $forecast_by = $settings['forecast_by'];
     }
     // setup the return array
     $return = array('amount' => '0', 'best_case' => '0', 'worst_case' => '0', 'overall_amount' => '0', 'overall_best' => '0', 'overall_worst' => '0', 'timeperiod_id' => $tp->id, 'lost_count' => '0', 'lost_amount' => '0', 'lost_best' => '0', 'lost_worst' => '0', 'won_count' => '0', 'won_amount' => '0', 'won_best' => '0', 'won_worst' => '0', 'included_opp_count' => 0, 'total_opp_count' => 0, 'includedClosedCount' => 0, 'includedClosedAmount' => '0', 'includedClosedBest' => '0', 'includedClosedWorst' => '0', 'pipeline_amount' => '0', 'pipeline_opp_count' => 0, 'closed_amount' => '0', 'includedIdsInLikelyTotal' => array());
     global $current_user;
     $sq = new SugarQuery();
     $bean_obj = BeanFactory::getBean($this->module_name);
     $sq->select(array($bean_obj->getTableName() . '.*'));
     $sq->from($bean_obj)->where()->equals('assigned_user_id', $user_id)->equals('parent_type', $forecast_by)->equals('deleted', 0)->equals('draft', $current_user->id == $user_id || $useDraftRecords === true ? 1 : 0)->queryAnd()->gte('date_closed_timestamp', $tp->start_date_timestamp)->lte('date_closed_timestamp', $tp->end_date_timestamp);
     $results = $sq->execute();
     foreach ($results as $row) {
         // if customers have made likely_case, best_case, or worst_case not required,
         // it saves to the DB as NULL, make sure we set it to 0 for the math ahead
         if (empty($row['likely_case'])) {
             $row['likely_case'] = 0;
         }
         if (empty($row['best_case'])) {
             $row['best_case'] = 0;
         }
         if (empty($row['worst_case'])) {
             $row['worst_case'] = 0;
         }
         $worst_base = SugarCurrency::convertWithRate($row['worst_case'], $row['base_rate']);
         $amount_base = SugarCurrency::convertWithRate($row['likely_case'], $row['base_rate']);
         $best_base = SugarCurrency::convertWithRate($row['best_case'], $row['base_rate']);
         $closed = false;
         if (in_array($row['sales_stage'], $settings['sales_stage_won']) && in_array($row['commit_stage'], $settings['commit_stages_included'])) {
             $return['won_amount'] = SugarMath::init($return['won_amount'], 6)->add($amount_base)->result();
             $return['won_best'] = SugarMath::init($return['won_best'], 6)->add($best_base)->result();
             $return['won_worst'] = SugarMath::init($return['won_worst'], 6)->add($worst_base)->result();
             $return['won_count']++;
             $return['includedClosedCount']++;
             $return['includedClosedAmount'] = SugarMath::init($return['includedClosedAmount'], 6)->add($amount_base)->result();
             $closed = true;
         } elseif (in_array($row['sales_stage'], $settings['sales_stage_lost'])) {
             $return['lost_amount'] = SugarMath::init($return['lost_amount'], 6)->add($amount_base)->result();
             $return['lost_best'] = SugarMath::init($return['lost_best'], 6)->add($best_base)->result();
             $return['lost_worst'] = SugarMath::init($return['lost_worst'], 6)->add($worst_base)->result();
             $return['lost_count']++;
             $closed = true;
         }
         if (in_array($row['commit_stage'], $settings['commit_stages_included'])) {
             if (!$closed) {
                 $return['amount'] = SugarMath::init($return['amount'], 6)->add($amount_base)->result();
                 $return['best_case'] = SugarMath::init($return['best_case'], 6)->add($best_base)->result();
                 $return['worst_case'] = SugarMath::init($return['worst_case'], 6)->add($worst_base)->result();
                 // add RLI/Opp id to includedIds array
                 array_push($return['includedIdsInLikelyTotal'], $row['parent_id']);
             }
             $return['included_opp_count']++;
             if ($closed) {
                 $return['includedClosedBest'] = SugarMath::init($return['includedClosedBest'], 6)->add($best_base)->result();
                 $return['includedClosedWorst'] = SugarMath::init($return['includedClosedWorst'], 6)->add($worst_base)->result();
             }
         }
         $return['total_opp_count']++;
         $return['overall_amount'] = SugarMath::init($return['overall_amount'], 6)->add($amount_base)->result();
         $return['overall_best'] = SugarMath::init($return['overall_best'], 6)->add($best_base)->result();
         $return['overall_worst'] = SugarMath::init($return['overall_worst'], 6)->add($worst_base)->result();
     }
     // send back the totals
     return $return;
 }
Example #30
0
function get_display_text($temp_module, $field, $field_value, $adv_type = null, $ext1 = null, $context = null)
{
    global $app_list_strings, $current_user;
    if ($temp_module->field_defs[$field]['type'] == "relate") {
        //echo $field;
        //bug 23502, assigned user should be displayed as username here. But I don't know if created user, modified user or even other module should display names instead of ids.
        if ($temp_module->field_defs[$field]['name'] == 'assigned_user_id' && !empty($field_value) && !empty($context['for_action_display'])) {
            if ($adv_type != 'exist_user') {
                return get_username_by_id($field_value);
            } else {
                $target_type = "assigned_user_name";
            }
        } else {
            if (!empty($temp_module->field_defs[$field]['dbType'])) {
                $target_type = $temp_module->field_defs[$field]['dbType'];
            } else {
                return $field_value;
            }
        }
    } else {
        if (!empty($temp_module->field_defs[$field]['calculated']) && !empty($context['for_action_display'])) {
            //Cannot set the value of calculated fields.
            return false;
        } else {
            $target_type = $temp_module->field_defs[$field]['type'];
        }
    }
    //Land of the "one offs"
    //This is for meetings and calls, the reminder time
    if ($temp_module->field_defs[$field]['name'] == "reminder_time") {
        $target_type = "enum";
        $temp_module->field_defs[$field]['options'] = "reminder_time_options";
    }
    // handle currency_id field to display the actual currency name vs the id when in edit view.
    if ($target_type == 'currency_id' && !empty($field_value)) {
        $currency = SugarCurrency::getCurrencyByID($field_value);
        return $currency->name;
    }
    // display team name for team_id field
    if ($field == 'team_id' && !empty($field_value)) {
        $team = BeanFactory::getBean('Teams', $field_value, array('strict_retrieve' => true));
        if ($team) {
            return Team::getDisplayName($team->name, $team->name_2);
        }
    }
    if ($target_type == "assigned_user_name") {
        if ($adv_type == null) {
            $user_array = get_user_array(TRUE, "Active", $field_value, true);
            if (!isset($user_array[$field_value])) {
                return false;
            }
            return $user_array[$field_value];
        }
        if ($adv_type == "exist_user") {
            if ($ext1 == "Manager") {
                return "Manager of the " . $app_list_strings['wflow_adv_user_type_dom'][$field_value];
            } else {
                return $app_list_strings['wflow_adv_user_type_dom'][$field_value];
            }
        }
    }
    if ($adv_type == "datetime") {
        if (empty($field_value)) {
            $field_value = 0;
        }
        return $app_list_strings['tselect_type_dom'][$field_value] . " from " . $app_list_strings['wflow_action_datetime_type_dom'][$ext1];
    }
    if ($adv_type == "exist_team") {
        return $app_list_strings['wflow_adv_team_type_dom'][$field_value];
    }
    if ($adv_type == "value_calc") {
        return "existing value" . $app_list_strings['query_calc_oper_dom'][$ext1] . " by " . $field_value;
    }
    if ($adv_type == "enum_step") {
        return $app_list_strings['wflow_adv_enum_type_dom'][$ext1] . " " . $field_value . " step(s)";
    }
    //Used primarily for alert templates
    require_once 'include/SugarFields/SugarFieldHandler.php';
    $sugarField = SugarFieldHandler::getSugarField($target_type);
    $field_value = $sugarField->getEmailTemplateValue($field_value, $temp_module->field_defs[$field], $context);
    return $field_value;
    //end get_display_text
}