/**
  * Set the Sales Status based on the associated RLI's sales_stage
  *
  * @param Opportunity $bean
  * @param string $event
  * @param array $args
  */
 public static function setSalesStatus(Opportunity $bean, $event, $args)
 {
     if (static::useRevenueLineItems() && $bean->ACLFieldAccess('sales_status', 'write')) {
         // we have a new bean so set the value to new and dump out
         if (empty($bean->fetched_row)) {
             $bean->sales_status = Opportunity::STATUS_NEW;
             return;
         }
         // Load forecast config so we have the sales_stage data.
         static::loadForecastSettings();
         // we don't have a new row, so figure out what we need to set it to
         $closed_won = static::$settings['sales_stage_won'];
         $closed_lost = static::$settings['sales_stage_lost'];
         $won_rlis = count($bean->get_linked_beans('revenuelineitems', 'RevenueLineItems', array(), 0, -1, 0, "sales_stage in ('" . join("', '", $closed_won) . "')"));
         $lost_rlis = count($bean->get_linked_beans('revenuelineitems', 'RevenueLineItems', array(), 0, -1, 0, "sales_stage in ('" . join("', '", $closed_lost) . "')"));
         $total_rlis = count($bean->get_linked_beans('revenuelineitems', 'RevenueLineItems'));
         if ($total_rlis > $won_rlis + $lost_rlis || $total_rlis === 0) {
             // still in progress
             $bean->sales_status = Opportunity::STATUS_IN_PROGRESS;
         } else {
             // they are equal so if the total lost == total rlis then it's closed lost,
             // otherwise it's always closed won
             if ($lost_rlis == $total_rlis) {
                 $bean->sales_status = Opportunity::STATUS_CLOSED_LOST;
             } else {
                 $bean->sales_status = Opportunity::STATUS_CLOSED_WON;
             }
         }
     }
 }
function CustomScheduler()
{
    global $sugar_config, $db;
    $timeDate = new TimeDate();
    $timeDateNow = $timeDate->getNow(true)->asDb();
    $days_offset = 15;
    $GLOBALS['log']->fatal("Checking Opportunities...");
    $query = "select opportunities.id from opportunities\n\twhere opportunities.sales_stage != 'Closed Won'\n\tand DATEDIFF(opportunities.date_modified,'" . $timeDateNow . "') < " . $days_offset . "\n\tand !opportunities.deleted";
    $GLOBALS['log']->fatal("Query: " . $query);
    $res = $db->query($query, true, 'Error: ');
    while ($row = $db->fetchByAssoc($res)) {
        $opportunity = new Opportunity();
        if (!is_null($opportunity->retrieve($row['id']))) {
            $user = new User();
            if (!is_null($user->retrieve($opportunity->assigned_user_id))) {
                $emailsTo = array();
                $emailSubject = "Opportunity Alert";
                $emailBody = "The following Opportunity has " . $days_offset . " days without changes.<br /><br />\n\t\t\t\tName: " . $opportunity->name . "<br />\n\t\t\t\tAccount: " . $opportunity->account_name . "<br />\n\t\t\t\tAmount: " . $opportunity->amount . "<br />\n\t\t\t\tSales Stage: " . $opportunity->sales_stage . "<br />\n\t\t\t\tDate Close: " . $opportunity->date_closed . "<br /><br />\n\t\t\t\tYou can see the opportunity here:<br />\n\t\t\t\t<a href=\"" . $sugar_config['site_url'] . "/index.php?module=Opportunities&action=DetailView&record=" . $opportunity->id . "\">" . $opportunity->name . "</a>";
                $emailsTo[] = $user->email1;
                SendEmail($emailsTo, $emailSubject, $emailBody);
            }
        }
    }
    $GLOBALS['log']->fatal("Opportunities checked");
    return true;
}
Exemple #3
0
 public function actionLoadOpportunitiesSampler()
 {
     if (!Group::isUserASuperAdministrator(Yii::app()->user->userModel)) {
         throw new NotSupportedException();
     }
     for ($i = 0; $i < 11; $i++) {
         $owner = Yii::app()->user->userModel;
         $name = 'Mass Delete ' . $i;
         $currencies = Currency::getAll();
         $currencyValue = new CurrencyValue();
         $currencyValue->value = 500.54;
         $currencyValue->currency = $currencies[0];
         $opportunity = new Opportunity();
         $opportunity->owner = $owner;
         $opportunity->name = $name;
         $opportunity->amount = $currencyValue;
         $opportunity->closeDate = '2011-01-01';
         //eventually fix to make correct format
         $opportunity->stage->value = 'Negotiating';
         $saved = $opportunity->save();
         if (!$saved) {
             throw new NotSupportedException();
         }
     }
 }
Exemple #4
0
 /**
  * Tests that currency-related properties are filled in at model layer
  * even when opportunity currency is the default one.
  */
 public function testDefaultCurrencyFieldsArePopulated()
 {
     $opportunity = new Opportunity();
     // disable row level security just to simplify the test
     $opportunity->disable_row_level_security = true;
     $opportunity->retrieve($this->opportunity->id);
     $this->assertNotEmpty($opportunity->currency_name);
     $this->assertNotEmpty($opportunity->currency_symbol);
 }
 function addRealty(&$bean)
 {
     $bean->load_relationship("realty_contracts");
     $bean->realty_contracts->delete($bean->id);
     $opp = new Opportunity();
     $opp->retrieve($bean->opp_id);
     $realty_list = $opp->get_linked_beans('realty_opportunities', 'Opportunities');
     foreach ($realty_list as $realty) {
         $bean->realty_contracts->add($realty->id);
     }
 }
 function create(&$bean)
 {
     if ($bean->code_inc == '') {
         $relate_field = "contact_id";
         $opportunity = new Opportunity();
         $opportunity->name = "Сделка с клиентом " . $bean->last_name . " " . $bean->first_name . " от " . date("d.m.Y");
         $opportunity->{$relate_field} = $bean->id;
         $opportunity->assigned_user_id = $bean->assigned_user_id;
         $opportunity->type_of_realty = "client";
         $opportunity->save();
     }
 }
 function create(&$bean)
 {
     if (empty($_REQUEST['record'])) {
         global $current_user;
         $bean->assigned_user_id = $current_user->id;
         $relate_field = "account_id";
         $opportunity = new Opportunity();
         $opportunity->name = "Сделка с клиентом " . $bean->name . " от " . date("d.m.Y");
         $opportunity->{$relate_field} = $bean->id;
         $opportunity->assigned_user_id = $bean->assigned_user_id;
         $opportunity->type_of_realty = "client";
         $opportunity->save();
     }
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     UserTestHelper::createBasicUser('jim');
     AllPermissionsOptimizationUtil::rebuild();
     OpportunityTestHelper::createOpportunityStagesIfDoesNotExist();
     OpportunityTestHelper::createOpportunitySourcesIfDoesNotExist();
     $currencies = Currency::getAll();
     //Make opportunities for testing chart data.
     $currencyValue = new CurrencyValue();
     $currencyValue->value = 200;
     $currencyValue->currency = $currencies[0];
     $opportunity = new Opportunity();
     $opportunity->owner = $super;
     $opportunity->name = 'abc1';
     $opportunity->amount = $currencyValue;
     $opportunity->closeDate = '2011-01-01';
     $opportunity->stage->value = 'Negotiating';
     $opportunity->source->value = 'Outbound';
     assert($opportunity->save());
     // Not Coding Standard
     $currencyValue = new CurrencyValue();
     $currencyValue->value = 350;
     $currencyValue->currency = $currencies[0];
     $opportunity = new Opportunity();
     $opportunity->owner = $super;
     $opportunity->name = 'abc2';
     $opportunity->amount = $currencyValue;
     $opportunity->closeDate = '2011-01-01';
     $opportunity->stage->value = 'Negotiating';
     $opportunity->source->value = 'Trade Show';
     assert($opportunity->save());
     // Not Coding Standard
     $currencyValue = new CurrencyValue();
     $currencyValue->value = 100;
     $currencyValue->currency = $currencies[0];
     $opportunity = new Opportunity();
     $opportunity->owner = $super;
     $opportunity->name = 'abc2';
     $opportunity->amount = $currencyValue;
     $opportunity->closeDate = '2011-01-01';
     $opportunity->stage->value = 'Verbal';
     $opportunity->source->value = 'Trade Show';
     assert($opportunity->save());
     // Not Coding Standard
 }
 public function testSaveAndRetrievePortlet()
 {
     $user = UserTestHelper::createBasicUser('Billy');
     $opportunities = Opportunity::getByName('superOpp');
     $portlet = new Portlet();
     $portlet->column = 2;
     $portlet->position = 5;
     $portlet->layoutId = 'Test';
     $portlet->collapsed = true;
     $portlet->viewType = 'OpportunitiesForContactRelatedList';
     $portlet->serializedViewData = serialize(array('title' => 'Testing Title'));
     $portlet->user = $user;
     $this->assertTrue($portlet->save());
     $portlet = Portlet::getById($portlet->id);
     $params = array('controllerId' => 'test', 'relationModuleId' => 'test', 'relationModel' => $opportunities[0], 'redirectUrl' => 'someRedirect');
     $portlet->params = $params;
     $unserializedViewData = unserialize($portlet->serializedViewData);
     $this->assertEquals(2, $portlet->column);
     $this->assertEquals(5, $portlet->position);
     $this->assertEquals('Testing Title', $portlet->getTitle());
     $this->assertEquals(false, $portlet->isEditable());
     $this->assertEquals('Test', $portlet->layoutId);
     //$this->assertEquals(true,                  $portlet->collapsed); //reenable once working
     $this->assertEquals('OpportunitiesForContactRelatedList', $portlet->viewType);
     $this->assertEquals($user->id, $portlet->user->id);
     $view = $portlet->getView();
 }
Exemple #10
0
 public function testLoad()
 {
     $this->assertEquals(2, Group::getCount());
     $this->assertEquals(0, Role::getCount());
     $this->assertEquals(0, Account::getCount());
     $this->assertEquals(0, Contact::getCount());
     $this->assertEquals(0, Opportunity::getCount());
     $this->assertEquals(0, Meeting::getCount());
     $this->assertEquals(0, Note::getCount());
     $this->assertEquals(0, Task::getCount());
     $this->assertEquals(1, User::getCount());
     $this->assertEquals(0, ProductCatalog::getCount());
     $this->assertEquals(0, ProductCategory::getCount());
     $this->assertEquals(0, ProductTemplate::getCount());
     $this->assertEquals(0, Product::getCount());
     $messageLogger = new MessageLogger();
     DemoDataUtil::unsetLoadedModules();
     DemoDataUtil::load($messageLogger, 3);
     $this->assertEquals(8, Group::getCount());
     $this->assertEquals(3, Role::getCount());
     $this->assertEquals(3, Account::getCount());
     $this->assertEquals(16, Contact::getCount());
     $this->assertEquals(6, Opportunity::getCount());
     $this->assertEquals(18, Meeting::getCount());
     $this->assertEquals(12, Note::getCount());
     $this->assertEquals(9, Task::getCount());
     $this->assertEquals(10, User::getCount());
     $this->assertEquals(1, ProductCatalog::getCount());
     $this->assertEquals(6, ProductCategory::getCount());
     $this->assertEquals(32, ProductTemplate::getCount());
     $this->assertEquals(59, Product::getCount());
 }
 public function run()
 {
     if (!$this->toFlavor('ent') && !$this->toFlavor('ult') || !version_compare($this->from_version, '7.0', '<')) {
         return;
     }
     $settings = Opportunity::getSettings();
     if ($settings['opps_view_by'] !== 'RevenueLineItems') {
         $this->log('Not using Revenue Line Items; Skipping Upgrade Script');
         return;
     }
     // get the get_widget helper and the StandardField Helper
     require_once 'modules/DynamicFields/FieldCases.php';
     require_once 'modules/ModuleBuilder/parsers/StandardField.php';
     // we are working with opportunities
     $module = 'Opportunities';
     $bean = BeanFactory::getBean('Opportunities');
     // the field set we need
     $fields = array('best_case', 'amount', 'worst_case', 'date_closed');
     // loop over each field
     foreach ($fields as $field) {
         // get the field defs
         $field_defs = $bean->getFieldDefinition($field);
         // load the field type up
         $f = get_widget($field_defs['type']);
         // populate the row from the vardefs that were loaded
         $f->populateFromRow($field_defs);
         // lets make sure that the calculated is true
         $f->calculated = true;
         // now lets save, since these are OOB field, we use StandardField
         $df = new StandardField($module);
         $df->setup($bean);
         $f->module = $bean;
         $f->save($df);
     }
 }
 function handleSave()
 {
     $out = "<script>ajaxStatus.flashStatus(SUGAR.language.get('app_strings', 'LBL_REQUEST_PROCESSED'), 2000);</script>";
     if (!empty($_REQUEST['relationships'])) {
         $out .= $this->removeCustomRelationships();
     }
     if (!empty($_REQUEST['fields'])) {
         $out .= $this->removeCustomFields();
     }
     if (!empty($_REQUEST['layouts'])) {
         $out .= $this->removeCustomLayouts();
     }
     if (!empty($_REQUEST['labels'])) {
         $out .= $this->removeCustomLabels();
     }
     if (!empty($_REQUEST['extensions'])) {
         $out .= $this->removeCustomExtensions();
     }
     if ($this->module === 'Opportunities') {
         $opp_settings = Opportunity::getSettings();
         if ($opp_settings['opps_view_by'] == 'RevenueLineItems') {
             require_once 'modules/Opportunities/include/OpportunityWithRevenueLineItem.php';
             $opp_setup = new OpportunityWithRevenueLineItem();
             $opp_setup->doMetadataConvert();
             $out .= 'Enabling Opportunities with RevenueLineItems<br />';
         }
     }
     $out .= "Complete!";
     $ajax = new AjaxCompose();
     $ajax->addCrumb(translate('LBL_STUDIO'), 'ModuleBuilder.main("studio")');
     $ajax->addCrumb(translate($this->module), 'ModuleBuilder.getContent("module=ModuleBuilder&action=wizard&view_module=' . $this->module . '")');
     $ajax->addCrumb("Reset " . translate($this->module), '');
     $ajax->addSection('center', "Reset " . translate($this->module), $out);
     echo $ajax->getJavascript();
 }
 /**
  * Upgrade Task to Run
  */
 public function run()
 {
     if (version_compare($this->from_version, '7.0.0', '<') && ($this->toFlavor('ent') || $this->toFlavor('ult'))) {
         $settings = Opportunity::getSettings();
         if ($settings['opps_view_by'] !== 'RevenueLineItems') {
             $this->log('Not using Revenue Line Items; Skipping Upgrade Script');
             return;
         }
         $filename = 'custom/Extension/modules/Opportunities/Ext/Vardefs/sugarfield_date_closed.php';
         if (!is_file($filename)) {
             return;
         }
         require $filename;
         if (!empty($dictionary['Opportunity']['fields'])) {
             $fileString = file_get_contents($filename);
             // PAT-584, need to set the field Expected Close Date to false when upgrade because:
             // In 6.7, the field Expected Close Date is Required and no formula associated out of box.
             // In 7, the field Expected Close Date is Not Required and there's a formula associated out of box.
             // So use steps from PAT-584, it results in a Required field with a formula associated.
             if (isset($dictionary['Opportunity']['fields']['date_closed']['required']) && $dictionary['Opportunity']['fields']['date_closed']['required'] == true) {
                 $this->log("Change Opportunity field date_closed to not required");
                 $fileString = preg_replace('/(\\$dictionary\\[\'Opportunity\'\\]\\[\'fields\'\\]\\[\'date_closed\'\\]\\[\'required\'\\]\\s*=\\s*)true\\s*;/', '${1}false;', $fileString);
                 sugar_file_put_contents_atomic($filename, $fileString);
             }
         }
     }
 }
Exemple #14
0
 function populateSeedDataForSearchTest($user_id)
 {
     $results = array();
     $a1_id = create_guid();
     $a1 = new Account();
     $a1->id = $a1_id;
     $a1->new_with_id = TRUE;
     $a1->name = "UNIT TEST {$a1_id}";
     $a1->assigned_user_id = $user_id;
     $a1->save();
     $results[] = array('id' => $a1_id, 'fieldName' => 'name', 'fieldValue' => "UNIT TEST {$a1_id}");
     $a2_id = create_guid();
     $a2 = new Account();
     $a2->new_with_id = TRUE;
     $a2->id = $a2_id;
     $a2->name = "UNIT TEST {$a2_id}";
     $a2->assigned_user_id = 'unittest';
     $a2->save();
     $results[] = array('id' => $a2_id, 'fieldName' => 'name', 'fieldValue' => "UNIT TEST {$a2_id}");
     $c1_id = create_guid();
     $c1 = new Contact();
     $c1->id = $c1_id;
     $c1->new_with_id = TRUE;
     $c1->first_name = "UNIT TEST";
     $c1->last_name = "UNIT_TEST";
     $c1->assigned_user_id = $user_id;
     $c1->save();
     $results[] = array('id' => $c1_id, 'fieldName' => 'name', 'fieldValue' => $c1->first_name . ' ' . $c1->last_name);
     $op1_id = create_guid();
     $op1 = new Opportunity();
     $op1->new_with_id = TRUE;
     $op1->id = $op1_id;
     $op1->name = "UNIT TEST {$op1_id}";
     $op1->assigned_user_id = $user_id;
     $op1->save();
     $results[] = array('id' => $op1_id, 'fieldName' => 'name', 'fieldValue' => "UNIT TEST {$op1_id}");
     $op2_id = create_guid();
     $op2 = new Opportunity();
     $op2->new_with_id = TRUE;
     $op2->id = $op2_id;
     $op2->name = "UNIT TEST {$op2_id}";
     $op2->assigned_user_id = 'unittest';
     $op2->save();
     $results[] = array('id' => $op2_id, 'fieldName' => 'name', 'fieldValue' => "UNIT TEST {$op2_id}");
     $GLOBALS['db']->commit();
     return $results;
 }
Exemple #15
0
 public static function getNames()
 {
     $arr = Opportunity::model()->findAll();
     $names = array(0 => 'None');
     foreach ($arr as $opportunity) {
         $names[$opportunity->id] = $opportunity->name;
     }
     return $names;
 }
Exemple #16
0
 /**
  * main method that runs reminding process
  * @return boolean
  */
 public function process()
 {
     $admin = new Administration();
     $admin->retrieveSettings();
     $GLOBALS['log']->info('----->test');
     $opportunities = $this->getOpportunitiesForRemind();
     foreach ($opportunities as $id) {
         echo "----->id:{$id}";
         $recipients = $this->getRecipients($id);
         $bean = new Opportunity();
         $bean->retrieve($id);
         if ($this->sendReminders($bean, $admin, $recipients)) {
             $bean->date_remind = 0;
             $bean->save();
         }
     }
     return true;
 }
Exemple #17
0
 /**
  * Figure out which Opportunity Status Field To Use based on the `opps_view_by` setting
  *
  * @return string
  */
 protected function getOpportunityStatusField()
 {
     $status_field = 'sales_stage';
     // get the opp config
     $opp_config = Opportunity::getSettings();
     if ($opp_config['opps_view_by'] === 'RevenueLineItems') {
         $status_field = 'sales_status';
     }
     return $status_field;
 }
 /**
  * Test account attribute that is a hasOne relation off of Opportunity
  */
 public function testModifyingAHasOneModelRelationDoesNotCreateNewAttribute()
 {
     $opportunity = new Opportunity(false);
     $this->assertEquals(17, count($opportunity->getAttributes()));
     $validated = $opportunity->validate();
     $this->assertFalse($validated);
     $this->assertEquals(6, count($opportunity->getErrors()));
     $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName($opportunity, 'account');
     $this->assertFalse($attributeForm->isRequired);
     $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData();
     $adapter = new $modelAttributesAdapterClassName(new Opportunity());
     $attributeForm->isRequired = true;
     $adapter->setAttributeMetadataFromForm($attributeForm);
     $opportunity = new Opportunity(false);
     $this->assertEquals(17, count($opportunity->getAttributes()));
     $validated = $opportunity->validate();
     $this->assertFalse($validated);
     $this->assertEquals(7, count($opportunity->getErrors()));
 }
 private function _createOpportunity($id, $time, $account)
 {
     global $timedate;
     $name = 'SugarOpportunity';
     $opportunity = new Opportunity();
     if (!empty($id)) {
         $opportunity->new_with_id = true;
         $opportunity->id = $id;
     }
     $opportunity->name = $name . $time;
     $opportunity->amount = 10000;
     $opportunity->account_id = $account->id;
     $opportunity->account_name = $account->name;
     $opportunity->date_closed = $timedate->to_display_date_time(gmdate("Y-m-d H:i:s"));
     $opportunity->save();
     $GLOBALS['db']->commit();
     self::$_createdOpportunities[] = $opportunity;
     return $opportunity;
 }
 /**
  * @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;
 }
 /**
  * Opportunity Override since we have custom logic that needs to be ran
  *
  * {@inheritdoc}
  */
 public function configSave(ServiceBase $api, array $args)
 {
     //acl check, only allow if they are module admin
     if (!$api->user->isAdmin() && !$api->user->isDeveloperForModule('Opportunities')) {
         // No create access so we construct an error message and throw the exception
         $failed_module_strings = return_module_language($GLOBALS['current_language'], 'Opportunities');
         $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);
     }
     $prior_settings = Opportunity::getSettings();
     // figure out how we should rollup when going back to Opps only
     $date_rollup_type = 'latest';
     if (isset($args['opps_closedate_rollup'])) {
         $date_rollup_type = $args['opps_closedate_rollup'];
         unset($args['opps_closedate_rollup']);
     }
     $this->skipMetadataRefresh = true;
     $settings = parent::configSave($api, $args);
     // reload the settings in the opportunity bean
     Opportunity::getSettings(true);
     $hasChanged = $prior_settings['opps_view_by'] !== $settings['opps_view_by'];
     if ($hasChanged) {
         $max_execution_time = ini_get('max_execution_time');
         if ($max_execution_time != 0 && $max_execution_time < 300) {
             ini_set('max_execution_time', 300);
         }
         /* @var $converter OpportunityWithOutRevenueLineItem|OpportunityWithRevenueLineItem */
         switch ($settings['opps_view_by']) {
             case 'Opportunities':
                 require_once 'modules/Opportunities/include/OpportunityWithOutRevenueLineItem.php';
                 $converter = new OpportunityWithOutRevenueLineItem();
                 $converter->setDateClosedMigrationParam($date_rollup_type);
                 break;
             case 'RevenueLineItems':
                 require_once 'modules/Opportunities/include/OpportunityWithRevenueLineItem.php';
                 $converter = new OpportunityWithRevenueLineItem();
                 break;
         }
         // actually trigger the conversion here
         // do metadata first
         $converter->doMetadataConvert();
         // then do data
         $converter->doDataConvert();
         require_once 'modules/Home/UnifiedSearchAdvanced.php';
         register_shutdown_function(array('UnifiedSearchAdvanced', 'clearCache'));
         // we need to refresh the cache but do it in the shutdown for this process
         register_shutdown_function(array('MetaDataManager', 'refreshCache'));
     }
     return $settings;
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     $super = SecurityTestHelper::createSuperAdmin();
     Yii::app()->user->userModel = $super;
     $accountTableName = Account::getTableName();
     $contactTableName = Contact::getTableName();
     $opportunityTableName = Opportunity::getTableName();
     ExternalSystemIdUtil::addExternalIdColumnIfMissing($accountTableName);
     ExternalSystemIdUtil::addExternalIdColumnIfMissing($contactTableName);
     ExternalSystemIdUtil::addExternalIdColumnIfMissing($opportunityTableName);
 }
Exemple #23
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);
    }
}
 public function run()
 {
     // get the opportunity settings
     $settings = Opportunity::getSettings();
     // if this key is not setup, then there is a 99.99% chance that it has never been set,
     // so it should be setup.
     if (!isset($settings['opps_view_by']) || empty($settings['opps_view_by'])) {
         SugarAutoLoader::load('modules/Opportunities/OpportunitiesDefaults.php');
         OpportunitiesDefaults::setupOpportunitiesSettings();
         // reload the settings now
         Opportunity::getSettings(true);
     }
 }
Exemple #25
0
 public function setUp()
 {
     SugarTestHelper::setUp('beanFiles');
     SugarTestHelper::setUp('beanList');
     SugarTestHelper::setUp('current_user');
     $this->account = SugarTestAccountUtilities::createAccount();
     $this->contact = SugarTestContactUtilities::createContact();
     $this->email = SugarTestEmailUtilities::createEmail();
     $this->opportunity = SugarTestOpportunityUtilities::createOpportunity('', $this->account);
     $this->contact->account_id = $this->account->id;
     $this->contact->save();
     $this->opportunity->load_relationship('contacts');
     $this->opportunity->contacts->add($this->contact);
     $this->email->parent_id = $this->contact->id;
     $this->email->parent_type = $this->contact->module_name;
     $this->email->save();
     if (isset($GLOBALS['app'])) {
         $this->application = $GLOBALS['app'];
     }
     $GLOBALS['app'] = new SugarApplication();
     $GLOBALS['app']->controller = new SugarController();
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     $super = SecurityTestHelper::createSuperAdmin();
     Yii::app()->user->userModel = $super;
     $accountTableName = Account::getTableName('Account');
     $contactTableName = Contact::getTableName('Contact');
     $opportunityTableName = Opportunity::getTableName('Opportunity');
     $columnName = ExternalSystemIdUtil::EXTERNAL_SYSTEM_ID_COLUMN_NAME;
     RedBeanColumnTypeOptimizer::externalIdColumn($accountTableName, $columnName);
     RedBeanColumnTypeOptimizer::externalIdColumn($contactTableName, $columnName);
     RedBeanColumnTypeOptimizer::externalIdColumn($opportunityTableName, $columnName);
 }
Exemple #27
0
 function display()
 {
     global $mod_strings, $app_strings, $app_list_strings, $sugar_config, $beanFiles, $current_user;
     $this->ss->assign("MOD", $mod_strings);
     $this->ss->assign("APP_LIST", $app_list_strings);
     // IF THE PROJECT IS CREATED FROM AN OPP
     if (isset($_REQUEST['CreateFromOpp']) && $_REQUEST['CreateFromOpp'] == 'true') {
         // CREATE DEFAULT PROJECT LINK WITH OPPORTUNITY
         require_once $beanFiles['Opportunity'];
         $link_opportunity = new Opportunity();
         $link_opportunity->retrieve($_REQUEST['return_id']);
         $this->bean->opportunities_id = $link_opportunity->id;
         $this->bean->opportunities_name = $link_opportunity->name;
         $this->bean->accounts_name = $link_opportunity->account_name;
         $this->bean->accounts_id = $link_opportunity->account_id;
         $this->bean->id = $this->bean->save();
         $_REQUEST['record'] = $this->bean->id;
     }
     // IF THE PROJECT IS CREATED FROM AN ACCOUNT
     if (isset($_REQUEST['CreateFromAcc']) && $_REQUEST['CreateFromAcc'] == 'true') {
         // CREATE DEFAULT PROJECT LINK WITH OPPORTUNITY
         require_once $beanFiles['Account'];
         $link_account = new Account();
         $link_account->retrieve($_REQUEST['return_id']);
         $this->bean->accounts_name = $link_account->name;
         $this->bean->accounts_id = $link_account->id;
         $this->bean->id = $this->bean->save();
         $_REQUEST['record'] = $this->bean->id;
     }
     // Build Stat url
     /*$edit_url = "";
       if (isset($current_user->tilkee_token_c) && !empty($current_user->tilkee_token_c) && !empty($this->bean->edit_url)) {
           $edit_url = $this->bean->edit_url.'&access_token='.$current_user->tilkee_token_c;
       }*/
     $this->ss->assign("EDIT_URL", $this->bean->edit_url);
     parent::display();
 }
 public function testImportDataAnalysisResults()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $import = new Import();
     $serializedData['importRulesType'] = 'Tasks';
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     $accountTableName = Account::getTableName('Account');
     $contactTableName = Contact::getTableName('Contact');
     $opportunityTableName = Opportunity::getTableName('Opportunity');
     $account1 = AccountTestHelper::createAccountByNameForOwner('account1', $super);
     $account2 = AccountTestHelper::createAccountByNameForOwner('account2', $super);
     $account3 = AccountTestHelper::createAccountByNameForOwner('account3', $super);
     $contact1 = ContactTestHelper::createContactByNameForOwner('contact1', $super);
     $contact2 = ContactTestHelper::createContactByNameForOwner('contact2', $super);
     $contact3 = ContactTestHelper::createContactByNameForOwner('contact3', $super);
     $opportunity1 = OpportunityTestHelper::createOpportunityByNameForOwner('opportunity1', $super);
     $opportunity2 = OpportunityTestHelper::createOpportunityByNameForOwner('opportunity2', $super);
     $opportunity3 = OpportunityTestHelper::createOpportunityByNameForOwner('opportunity3', $super);
     //Make models externally linked for testing.
     ImportTestHelper::updateModelsExternalId($account2, 'ACC');
     ImportTestHelper::updateModelsExternalId($contact2, 'CON');
     ImportTestHelper::updateModelsExternalId($opportunity2, 'OPP');
     ImportTestHelper::createTempTableByFileNameAndTableName('importAnalyzerTest.csv', $import->getTempTableName(), Yii::getPathOfAlias('application.modules.tasks.tests.unit.files'));
     R::exec("update " . $import->getTempTableName() . " set column_0 = " . $account3->id . " where id != 1 limit 3");
     R::exec("update " . $import->getTempTableName() . " set column_2 = " . $contact3->id . " where id != 1 limit 4");
     R::exec("update " . $import->getTempTableName() . " set column_4 = " . $opportunity3->id . " where id != 1 limit 5");
     $mappingData = array('column_0' => ImportMappingUtil::makeModelDerivedColumnMappingData('AccountDerived', IdValueTypeMappingRuleForm::ZURMO_MODEL_ID), 'column_1' => ImportMappingUtil::makeModelDerivedColumnMappingData('AccountDerived'), 'column_2' => ImportMappingUtil::makeModelDerivedColumnMappingData('ContactDerived', IdValueTypeMappingRuleForm::ZURMO_MODEL_ID), 'column_3' => ImportMappingUtil::makeModelDerivedColumnMappingData('ContactDerived'), 'column_4' => ImportMappingUtil::makeModelDerivedColumnMappingData('OpportunityDerived', IdValueTypeMappingRuleForm::ZURMO_MODEL_ID), 'column_5' => ImportMappingUtil::makeModelDerivedColumnMappingData('OpportunityDerived'));
     $serializedData = unserialize($import->serializedData);
     $serializedData['mappingData'] = $mappingData;
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     $importRules = ImportRulesUtil::makeImportRulesByType('Tasks');
     $config = array('pagination' => array('pageSize' => 2));
     //This test csv has a header row.
     $dataProvider = new ImportDataProvider($import->getTempTableName(), true, $config);
     //Run data analyzer
     $importDataAnalyzer = new ImportDataAnalyzer($importRules, $dataProvider);
     foreach ($mappingData as $columnName => $columnMappingData) {
         $importDataAnalyzer->analyzeByColumnNameAndColumnMappingData($columnName, $columnMappingData);
     }
     $messagesData = $importDataAnalyzer->getMessagesData();
     $compareData = array('column_0' => array(array('message' => '3 record(s) will be updated and 7 record(s) will be skipped during import.', 'sanitizerUtilType' => 'AccountDerivedIdValueType', 'moreAvailable' => false)), 'column_1' => array(array('message' => '3 record(s) will be updated and 7 record(s) will be skipped during import.', 'sanitizerUtilType' => 'AccountDerivedIdValueType', 'moreAvailable' => false)), 'column_2' => array(array('message' => '4 record(s) will be updated and 6 record(s) will be skipped during import.', 'sanitizerUtilType' => 'ContactDerivedIdValueType', 'moreAvailable' => false)), 'column_3' => array(array('message' => '3 record(s) will be updated and 7 record(s) will be skipped during import.', 'sanitizerUtilType' => 'ContactDerivedIdValueType', 'moreAvailable' => false)), 'column_4' => array(array('message' => '5 record(s) will be updated and 5 record(s) will be skipped during import.', 'sanitizerUtilType' => 'OpportunityDerivedIdValueType', 'moreAvailable' => false)), 'column_5' => array(array('message' => '3 record(s) will be updated and 7 record(s) will be skipped during import.', 'sanitizerUtilType' => 'OpportunityDerivedIdValueType', 'moreAvailable' => false)));
     $this->assertEquals($compareData, $messagesData);
     $importInstructionsData = $importDataAnalyzer->getImportInstructionsData();
     $compareInstructionsData = array();
     $this->assertEquals($compareInstructionsData, $importInstructionsData);
 }
 public function run()
 {
     // are we going to 7.6 or newer?
     // if we are and we are not using RLI's this can be skipped
     $settings = Opportunity::getSettings();
     if (version_compare($this->to_version, '7.6', '>=') && $settings['opps_view_by'] !== 'RevenueLineItems') {
         $this->log('Not using Revenue Line Items; Skipping Upgrade Script');
         return;
     }
     $q = "SELECT '' as id,\n                     rli.name,\n                     rli.id as parent_id,\n                     'RevenueLineItems' as parent_type,\n                     1 as draft\n                FROM revenue_line_items rli\n                LEFT JOIN forecast_worksheets fw\n                ON rli.id = fw.parent_id AND fw.parent_type = 'RevenueLineItems'\n                WHERE fw.id IS NULL";
     $this->log('Running Select SQL: ' . $q);
     $r = $this->db->query($q);
     $this->log('Found ' . $this->db->getRowCount($r) . ' RLIs to add to ForecastWorksheets');
     $this->insertRows($r);
 }
 /**
  * (non-PHPdoc)
  * @see GamificationRules::scoreOnSaveModel()
  */
 public function scoreOnSaveModel(CEvent $event)
 {
     parent::scoreOnSaveModel($event);
     if (array_key_exists('value', $event->sender->stage->originalAttributeValues) && $event->sender->stage->value == Opportunity::getStageClosedWonValue()) {
         $scoreType = static::SCORE_TYPE_WIN_OPPORTUNITY;
         $category = static::SCORE_CATEGORY_WIN_OPPORTUNITY;
         $gameScore = GameScore::resolveToGetByTypeAndPerson($scoreType, Yii::app()->user->userModel);
         $gameScore->addValue();
         $saved = $gameScore->save();
         if (!$saved) {
             throw new FailedToSaveModelException();
         }
         GamePointUtil::addPointsByPointData(Yii::app()->user->userModel, static::getPointTypeAndValueDataByCategory($category));
     }
 }