Example #1
0
 public function testLocationByPosition()
 {
     $Location = new Location();
     $Location->setPosition(49.9, 7.77);
     $Forecast = new Forecast(new Openweathermap(), $Location);
     $object = $Forecast->object();
     if ($object->isEmpty()) {
         $this->markTestSkipped('Openweathermap: Position "49,9, 7.77" was not available.');
     }
 }
 /**
  * Utility method to load Forecast Settings
  *
  * @param bool $reload      Forecast Reload the settings
  */
 protected static function loadForecastSettings($reload = false)
 {
     /* @var $admin Administration */
     if (empty(static::$settings) || $reload === true) {
         static::$settings = Forecast::getSettings($reload);
     }
 }
 /**
  * Returns itself when evaluating.
  */
 public function evaluate()
 {
     $value = $this->getParameters()->evaluate();
     // get the statuses
     $settings = Forecast::getSettings();
     if (in_array($value, $settings['sales_stage_lost'], true)) {
         return AbstractExpression::$TRUE;
     }
     return AbstractExpression::$FALSE;
 }
 /**
  * Returns the entire enumeration bare.
  */
 public function evaluate()
 {
     $params = $this->getParameters();
     $includeWon = $params[0]->evaluate();
     $includeLost = $params[1]->evaluate();
     $array = array_keys($GLOBALS['app_list_strings']['sales_stage_dom']);
     // get the statuses
     $settings = Forecast::getSettings();
     $keysToRemove = array();
     if ($includeWon == AbstractExpression::$FALSE) {
         $keysToRemove = array_merge($keysToRemove, $settings['sales_stage_won']);
     }
     if ($includeLost == AbstractExpression::$FALSE) {
         $keysToRemove = array_merge($keysToRemove, $settings['sales_stage_lost']);
     }
     return array_diff($array, $keysToRemove);
 }
 public function filterList(ServiceBase $api, array $args, $acl = 'list')
 {
     $forecastSettings = Forecast::getSettings();
     if ($forecastSettings['is_setup'] === 1 && !isset($args['use_generic_timeperiods'])) {
         return parent::filterList($api, $args, $acl);
     }
     // since forecast is not setup, we more than likely don't have timeperiods, so grab the default 3
     $tp = BeanFactory::getBean('TimePeriods');
     $data = array();
     $data['next_offset'] = -1;
     $data['records'] = array();
     $app_list_strings = return_app_list_strings_language($GLOBALS['current_language']);
     $options = $app_list_strings['generic_timeperiod_options'];
     foreach ($options as $duration => $name) {
         $data['records'][] = array_merge(array('id' => $duration, 'name' => $name), $tp->getGenericStartEndByDuration($duration));
     }
     return $data;
 }
<?php

$forecast = new Forecast();
$forecastData = $forecast->getData();
if (is_array($forecastData)) {
    $displayData = $forecastData;
} else {
    $msg_error = $forecastData;
}
Example #7
0
 /**
  * Save the updated product to the worksheet, this will create one if one does not exist
  * this will also update one if a draft version exists
  *
  * @return bool         True if the worksheet was saved/updated, false otherwise
  */
 protected function saveProductWorksheet()
 {
     $settings = Forecast::getSettings();
     if ($settings['is_setup'] && $settings['forecast_by'] === $this->module_name) {
         // save the a draft of each product
         /* @var $worksheet ForecastWorksheet */
         $worksheet = BeanFactory::getBean('ForecastWorksheets');
         $worksheet->saveRelatedProduct($this);
         return true;
     }
     return false;
 }
Example #8
0
 /**
  * Handle setting the default worksheet_columns back into the db.
  *
  * @param String $forecast_by The Module that we are currently forecasting by
  */
 public function setDefaultWorksheetColumns($forecast_by)
 {
     SugarAutoLoader::load('modules/Forecasts/ForecastsDefaults.php');
     $edition = $forecast_by === 'RevenueLineItems' ? 'ent' : 'pro';
     $columns = ForecastsDefaults::getWorksheetColumns($edition);
     // we need to check the setting for best and worst
     $settings = Forecast::getSettings(true);
     if ($settings['show_worksheet_best'] != 1) {
         // remove best since it's include by default
         foreach ($columns as $i => $column) {
             if ($column === 'best_case') {
                 unset($columns[$i]);
                 break;
             }
         }
     }
     if ($settings['show_worksheet_worst'] == 1) {
         // add worse_Case since it's not include by default
         $columns[] = 'worst_case';
     }
     /* @var $admin Administration */
     $admin = BeanFactory::getBean('Administration');
     $admin->saveSetting('Forecasts', 'worksheet_columns', json_encode($columns), 'base');
     // update the metadata
     $this->updateConfigWorksheetColumnsMetadata($forecast_by);
     // now write out the correct list view
     $this->setWorksheetColumns('base', $columns, $forecast_by);
 }
 /**
  * Fix the Opportunity Data to have the correct data once we go back from having RLI's to only have Opps
  *
  * - Takes the lowest sales_stage from all the RLIs
  * - Takes the lowest date_closed from all the RLIs
  * - Sets commit_stage to empty
  * - Sets sales_status to empty
  *
  * This is all done via a Query since we delete all the RLI's and we didn't want to keep any of them around.
  *
  * @throws SugarQueryException
  */
 protected function setOpportunityDataFromRevenueLineItems()
 {
     // need to figure out the best way to roll this up before truncating the table.
     $app_list_strings = return_app_list_strings_language($GLOBALS['current_language']);
     // get the sales_stage from the RLI module
     /* @var $rli RevenueLineItem */
     $rli = BeanFactory::getBean('RevenueLineItems');
     $def = $rli->getFieldDefinition('sales_stage');
     $db = DBManagerFactory::getInstance();
     $list_value = array();
     // get the `options` param so we make sure if they customized it to use their custom version
     $sqlCase = '';
     $list = $def['options'];
     if (!empty($list) && isset($app_list_strings[$list])) {
         $i = 0;
         $order_by_arr = array();
         foreach ($app_list_strings[$list] as $key => $value) {
             $list_value[$i] = $key;
             if ($key == '') {
                 $order_by_arr[] = "WHEN (sales_stage='' OR sales_stage IS NULL) THEN " . $i++;
             } else {
                 $order_by_arr[] = "WHEN sales_stage=" . $db->quoted($key) . " THEN " . $i++;
             }
         }
         $sqlCase = "min(CASE " . implode("\n", $order_by_arr) . " ELSE {$i} END)";
     }
     $fcsettings = Forecast::getSettings();
     $stage_cases = array();
     $closed_stages = array_merge($fcsettings['sales_stage_won'], $fcsettings['sales_stage_lost']);
     foreach ($closed_stages as $stage) {
         $stage_cases[] = $db->quoted($stage);
     }
     $stage_cases = implode(',', $stage_cases);
     $sq = new SugarQuery();
     $sq->select(array('opportunity_id'))->fieldRaw($sqlCase, 'sales_stage')->fieldRaw($this->dateClosedMigration . '(CASE when sales_stage IN (' . $stage_cases . ') THEN date_closed END)', 'dc_closed')->fieldRaw($this->dateClosedMigration . '(CASE when sales_stage NOT IN (' . $stage_cases . ') THEN date_closed END)', 'dc_open')->fieldRaw($this->dateClosedMigration . '(CASE when sales_stage IN (' . $stage_cases . ') THEN date_closed_timestamp END)', 'dct_closed')->fieldRaw($this->dateClosedMigration . '(CASE when sales_stage NOT IN (' . $stage_cases . ') THEN date_closed_timestamp END)', 'dct_open');
     $sq->from($rli);
     $sq->groupBy('opportunity_id');
     $results = $sq->execute();
     foreach ($results as $result) {
         $sql = 'UPDATE opportunities SET date_closed = ' . $db->quoted(!empty($result['dc_open']) ? $result['dc_open'] : $result['dc_closed']) . ',
             date_closed_timestamp = ' . $db->quoted(!empty($result['dct_open']) ? $result['dct_open'] : $result['dct_closed']) . ',
             sales_stage = ' . $db->quoted($list_value[$result['sales_stage']]) . ',
             probability = ' . $db->quoted($app_list_strings['sales_probability_dom'][$list_value[$result['sales_stage']]]) . ',
             sales_status = ' . $db->quoted('') . ', commit_stage = ' . $db->quoted('') . '
             WHERE id = ' . $db->quoted($result['opportunity_id']);
         $db->query($sql);
     }
     if ($this->isForecastSetup()) {
         SugarAutoLoader::load('include/SugarQueue/jobs/SugarJobUpdateOpportunities.php');
         SugarJobUpdateOpportunities::updateOpportunitiesForForecasting();
     }
 }
Example #10
0
 /**
  * @param  \SimpleXMLElement $xml
  * @return Forecast[]
  */
 public static function getForecastsFromXml(\SimpleXMLElement $xml)
 {
     $forecasts = array();
     foreach ($xml->forecast->tabular->time as $forecast) {
         try {
             $forecasts[] = Forecast::getForecastFromXml($forecast);
         } catch (\RuntimeException $e) {
             // Skip those we cant create..
         }
     }
     return $forecasts;
 }
 /**
  * Forecast Override since we have custom logic that needs to be ran
  *
  * {@inheritdoc}
  */
 public function forecastsConfigSave(ServiceBase $api, array $args)
 {
     //acl check, only allow if they are module admin
     if (!$api->user->isAdmin() && !$api->user->isDeveloperForModule('Forecasts')) {
         // No create access so we construct an error message and throw the exception
         $failed_module_strings = return_module_language($GLOBALS['current_language'], 'forecasts');
         $moduleName = $failed_module_strings['LBL_MODULE_NAME'];
         $args = null;
         if (!empty($moduleName)) {
             $args = array('moduleName' => $moduleName);
         }
         throw new SugarApiExceptionNotAuthorized($GLOBALS['app_strings']['EXCEPTION_CHANGE_MODULE_CONFIG_NOT_AUTHORIZED'], $args);
     }
     $admin = BeanFactory::getBean('Administration');
     //track what settings have changed to determine if timeperiods need rebuilt
     $prior_forecasts_settings = $admin->getConfigForModule('Forecasts', $api->platform);
     //If this is a first time setup, default prior settings for timeperiods to 0 so we may correctly recalculate
     //how many timeperiods to build forward and backward.  If we don't do this we would need the defaults to be 0
     if (empty($prior_forecasts_settings['is_setup'])) {
         $prior_forecasts_settings['timeperiod_shown_forward'] = 0;
         $prior_forecasts_settings['timeperiod_shown_backward'] = 0;
     }
     $upgraded = 0;
     if (!empty($prior_forecasts_settings['is_upgrade'])) {
         $db = DBManagerFactory::getInstance();
         // check if we need to upgrade opportunities when coming from version below 6.7.x.
         $upgraded = $db->getOne("SELECT count(id) AS total FROM upgrade_history\n                    WHERE type = 'patch' AND status = 'installed' AND version LIKE '6.7.%'");
         if ($upgraded == 1) {
             //TODO-sfa remove this once the ability to map buckets when they get changed is implemented (SFA-215).
             $args['has_commits'] = true;
         }
     }
     if (isset($args['show_custom_buckets_options'])) {
         $json = getJSONobj();
         $_args = array('dropdown_lang' => isset($_SESSION['authenticated_user_language']) ? $_SESSION['authenticated_user_language'] : $GLOBALS['current_language'], 'dropdown_name' => 'commit_stage_custom_dom', 'view_package' => 'studio', 'list_value' => $json->encode($args['show_custom_buckets_options']), 'skip_sync' => true);
         $_REQUEST['view_package'] = 'studio';
         require_once 'modules/ModuleBuilder/parsers/parser.dropdown.php';
         $parser = new ParserDropDown();
         $parser->saveDropDown($_args);
         unset($args['show_custom_buckets_options']);
     }
     // we do the double check here since the front ent will send one one value if the input is empty
     if (empty($args['worksheet_columns']) || empty($args['worksheet_columns'][0])) {
         // set the defaults
         $args['worksheet_columns'] = array('commit_stage', 'parent_name', 'likely_case');
         if ($args['show_worksheet_best'] == 1) {
             $args['worksheet_columns'][] = 'best_case';
         }
         if ($args['show_worksheet_worst'] == 1) {
             $args['worksheet_columns'][] = 'worst_case';
         }
     }
     //reload the settings to get the current settings
     $current_forecasts_settings = parent::configSave($api, $args);
     // setting are saved, reload the setting in the ForecastBean just in case.
     Forecast::getSettings(true);
     // now that we have saved the setting, we need to sync all the data if
     // this is being upgraded or the forecast was not setup before.
     if ($upgraded || empty($prior_forecasts_settings['is_setup'])) {
         if ($args['forecast_by'] === 'Opportunities') {
             SugarAutoLoader::load('include/SugarQueue/jobs/SugarJobUpdateOpportunities.php');
             SugarJobUpdateOpportunities::updateOpportunitiesForForecasting();
         } else {
             SugarAutoLoader::load('include/SugarQueue/jobs/SugarJobUpdateRevenueLineItems.php');
             SugarJobUpdateRevenueLineItems::scheduleRevenueLineItemUpdateJobs();
         }
     }
     // did this change?
     if ($prior_forecasts_settings['worksheet_columns'] !== $args['worksheet_columns']) {
         $this->setWorksheetColumns($api, $args['worksheet_columns'], $current_forecasts_settings['forecast_by']);
     }
     //if primary settings for timeperiods have changed, then rebuild them
     if ($this->timePeriodSettingsChanged($prior_forecasts_settings, $current_forecasts_settings)) {
         $timePeriod = TimePeriod::getByType($current_forecasts_settings['timeperiod_interval']);
         $timePeriod->rebuildForecastingTimePeriods($prior_forecasts_settings, $current_forecasts_settings);
     }
     return $current_forecasts_settings;
 }
Example #12
0
 /**
  * Reset the forecast data.
  *
  * @param string $forecast_by What are we going to be forecasting by now
  */
 protected function resetForecastData($forecast_by)
 {
     $admin = BeanFactory::getBean('Administration');
     $admin->saveSetting('Forecasts', 'forecast_by', $forecast_by, 'base');
     SugarAutoLoader::load('modules/Forecasts/include/ForecastReset.php');
     $forecast_reset = new ForecastReset();
     $forecast_reset->truncateForecastData();
     $forecast_reset->setDefaultWorksheetColumns($forecast_by);
     // reload the settings
     Forecast::getSettings(true);
 }
Example #13
0
print_r($day1->getTemperature());
$day2 = new Forecast();
$day2->setTemperature($day2->getForecast(40.78, -79.95)->data->temperature[2]);
$day2->setTime($day2->getForecast(40.78, -79.95)->time->startPeriodName[2]);
print_r($day2->getTime());
print_r(": ");
print_r($day2->getTemperature());
$day3 = new Forecast();
$day3->setTemperature($day3->getForecast(40.78, -79.95)->data->temperature[3]);
$day3->setTime($day3->getForecast(40.78, -79.95)->time->startPeriodName[3]);
print_r($day3->getTime());
print_r(": ");
print_r($day3->getTemperature());
$day4 = new Forecast();
$day4->setTemperature($day4->getForecast(40.78, -79.95)->data->temperature[4]);
$day4->setTime($day4->getForecast(40.78, -79.95)->time->startPeriodName[4]);
print_r($day4->getTime());
print_r(": ");
print_r($day4->getTemperature());
$day5 = new Forecast();
$day5->setTemperature($day5->getForecast(40.78, -79.95)->data->temperature[5]);
$day5->setTime($day5->getForecast(40.78, -79.95)->time->startPeriodName[5]);
print_r($day5->getTime());
print_r(": ");
print_r($day5->getTemperature());
$day6 = new Forecast();
$day6->setTemperature($day6->getForecast(40.78, -79.95)->data->temperature[6]);
$day6->setTime($day6->getForecast(40.78, -79.95)->time->startPeriodName[6]);
print_r($day6->getTime());
print_r(": ");
print_r($day6->getTemperature());
 /**
  *@brief display a form for modifying or add a forecast
  *@return HTML code
  */
 public function form_item()
 {
     $forecast = new Forecast($this->cn, $this->f_id);
     $forecast->load();
     $str_name = $forecast->get_parameter('name');
     $str_start = $forecast->get_parameter('start_date');
     $str_end = $forecast->get_parameter('end_date');
     $r = "";
     $str_action = _("Elements");
     $cat = new Forecast_Cat($this->cn);
     $array = $cat->make_array($this->f_id);
     $periode = new Periode($this->cn);
     $aPeriode = $this->cn->make_array("select p_id,to_char(p_start,'MM.YYYY') as label from parm_periode\n                                  where p_start >= (select p_start from parm_periode where p_id={$str_start})\n                                   and p_end <= (select p_end from parm_periode where p_id={$str_end})\n\t\t\t\t   order by p_start");
     $aPeriode[] = array('value' => 0, 'label' => 'Mensuel');
     $value = $this->cn->get_array("select fi_id,fi_text,fi_account,fi_card,fc_id,fi_amount,fi_debit,fi_pid " . " from forecast_item " . " \twhere fc_id in (select fc_id from forecast_cat where f_id = \$1)", array($this->f_id));
     $max = count($value) < MAX_FORECAST_ITEM ? MAX_FORECAST_ITEM : count($value);
     $r .= HtmlInput::hidden('nbrow', $max);
     for ($i = 0; $i < $max; $i++) {
         if (isset($value[$i]['fi_id'])) {
             $r .= HtmlInput::hidden('fi_id' . $i, $value[$i]['fi_id']);
         }
         /* category*/
         $category = new ISelect();
         $category->name = 'an_cat' . $i;
         $category->value = $array;
         $category->selected = isset($value[$i]["fc_id"]) ? $value[$i]["fc_id"] : -1;
         $aCat[$i]['cat'] = $category->input();
         /* amount 	 */
         $amount = new INum('an_cat_amount' . $i);
         $amount->value = isset($value[$i]["fi_amount"]) ? $value[$i]["fi_amount"] : 0;
         $aCat[$i]['amount'] = $amount->input();
         /* Accounting*/
         $account = new IPoste('an_cat_acc' . $i);
         $account->set_attribute('ipopup', 'ipop_account');
         //            $account->set_attribute('label','an_label'.$i);
         $account->set_attribute('account', 'an_cat_acc' . $i);
         $account->set_attribute('bracket', 1);
         $account->set_attribute('no_overwrite', 1);
         $account->set_attribute('noquery', 1);
         $account->css_size = "85%";
         $account->value = isset($value[$i]["fi_account"]) ? $value[$i]["fi_account"] : "";
         $aCat[$i]['account'] = $account->input();
         /*Quick Code */
         $qc = new ICard('an_qc' . $i);
         // If double click call the javascript fill_ipopcard
         $qc->set_dblclick("fill_ipopcard(this);");
         // This attribute is mandatory, it is the name of the IPopup
         $qc->set_attribute('ipopup', 'ipopcard');
         // name of the field to update with the name of the card
         $qc->set_attribute('label', 'an_label' . $i);
         // Type of card : all
         $qc->set_attribute('typecard', 'all');
         $qc->set_attribute('jrn', 0);
         $qc->extra = 'all';
         // when value selected in the autcomplete
         $qc->set_function('fill_data');
         if (isset($value[$i]["fi_card"])) {
             $f = new Fiche($this->cn, $value[$i]["fi_card"]);
             $qc->value = $f->strAttribut(ATTR_DEF_QUICKCODE);
         }
         $aCat[$i]['qc'] = $qc->search() . $qc->input();
         /* Label */
         $label = new IText('an_label' . $i);
         $label->value = isset($value[$i]["fi_text"]) ? $value[$i]["fi_text"] : "";
         $aCat[$i]['name'] = $label->input();
         //Deb or Cred
         $deb = new ISelect('an_deb' . $i);
         $deb->selected = isset($value[$i]["fi_debit"]) ? $value[$i]["fi_debit"] : -1;
         $deb->value = array(array('value' => 'D', 'label' => _('Débit')), array('value' => 'C', 'label' => _('Crédit')));
         $aCat[$i]['deb'] = $deb->input();
         //Periode
         $isPeriode = new ISelect('month' . $i);
         $isPeriode->value = $aPeriode;
         $isPeriode->selected = isset($value[$i]["fi_pid"]) ? $value[$i]["fi_pid"] : 0;
         $aCat[$i]['per'] = $isPeriode->input();
     }
     $add_row = new IButton('add_row');
     $add_row->label = _('Ajouter une ligne');
     $add_row->javascript = 'for_add_row(\'fortable\')';
     $f_add_row = $add_row->input();
     ob_start();
     require_once NOALYSS_INCLUDE . '/template/forecast-detail.php';
     $r .= ob_get_contents();
     ob_end_clean();
     return $r;
 }
Example #15
0
 /**
  * Get the Forecast Config Values
  *
  * @codeCoverageIgnore
  * @return array
  */
 protected function getForecastConfig()
 {
     return Forecast::getSettings();
 }
<?php

if (isset($_POST['recordData'])) {
    $forecast = new Forecast();
    $result = $forecast->persistData();
    if ($result === false) {
        $msg_error = 'Une erreur est survenue lors de l\'enregistement.';
    } elseif (is_string($result)) {
        $msg_error = $result;
    } else {
        $msg_error = 'Enregistrement OK';
    }
}
Example #17
0
         $cn->commit();
         $sa = 'vw';
         // to avoid to restart the add of new anticipation
     } catch (Exception $e) {
         $cn->rollback();
         alert($e->getMessage());
         $correct = 1;
     }
 }
 /* Second step : we save the name and category
  * and propose the items we add the item */
 if ($correct == 2 || isset($_POST['step2'])) {
     try {
         $cn->start();
         /* Save forecast */
         $a = new Forecast($cn);
         $a->set_parameter('name', $_POST['an_name']);
         $a->set_parameter('start_date', $_POST['start_date']);
         $a->set_parameter('end_date', $_POST['end_date']);
         $a->save();
         $id = $a->get_parameter("id");
         /* save cat */
         for ($i = 0; $i < MAX_CAT; $i++) {
             if (strlen(trim($_POST['fr_cat' . $i])) != 0) {
                 $c = new Forecast_Cat($cn);
                 $c->set_parameter('order', $_POST['fr_order' . $i]);
                 $c->set_parameter('desc', $_POST['fr_cat' . $i]);
                 $c->set_parameter('forecast', $id);
                 $c->save();
             }
         }
Example #18
0
$requests = array(1, 10, 100);
$threads = array(1, 5, 10, 25, 50, 100);
$trials = 2;
$index = 0;
// count how many trials we did
echo "Of " . count($requests) * count($threads) * $trials . " trials, running:";
$results = array();
// $results['num_requests']['num_threads']['trial']
for ($i = 0; $i < count($requests); $i++) {
    for ($j = 0; $j < count($threads); $j++) {
        for ($k = 0; $k < $trials; $k++) {
            $index++;
            echo " {$index}";
            $sample = array_slice($this_day_in_history, 0, $requests[$i]);
            $start = microtime(true);
            $forecast = new Forecast($api_key, $threads[$j]);
            $responses = $forecast->getData($sample);
            $end = microtime(true);
            $results[$i][$j][$k] = $end - $start;
            // duration
            echo ";";
            sleep(20);
        }
    }
}
echo "<br />\n";
?>

<!--
<?php 
print_r($results);