public function testUnlinkContactForAccount() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $simpleUser = User::getByUsername('simpleUser'); Yii::app()->user->userModel = $simpleUser; $simpleUser->setRight('AccountsModule', AccountsModule::RIGHT_ACCESS_ACCOUNTS); $simpleUser->setRight('AccountsModule', AccountsModule::RIGHT_CREATE_ACCOUNTS); $simpleUser->setRight('ContactsModule', ContactsModule::RIGHT_ACCESS_CONTACTS); $simpleUser->setRight('ContactsModule', ContactsModule::RIGHT_ACCESS_CONTACTS); $this->assertTrue($simpleUser->save()); $account = AccountTestHelper::createAccountByNameForOwner('simpleUserAccount', $simpleUser); $contact = ContactTestHelper::createContactWithAccountByNameForOwner('simpleUserContact', $simpleUser, $account); $accounts = Account::getAll(); $this->assertEquals(1, count($accounts)); $contacts = Contact::getAll(); $this->assertEquals(1, count($contacts)); $superAccountId = self::getModelIdByModelNameAndName('Account', 'simpleUserAccount'); $this->setGetArray(array('id' => $superAccountId)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('accounts/default/details'); $contactId = self::getModelIdByModelNameAndName('Contact', 'simpleUserContact simpleUserContactson'); //unlinking the contact $this->setGetArray(array('id' => $contactId, 'relationModelClassName' => 'Account', 'relationModelId' => $superAccountId, 'relationModelRelationName' => 'contacts')); $content = $this->runControllerWithNoExceptionsAndGetContent('contacts/default/unlink', true); $accounts = Account::getAll(); $this->assertEquals(1, count($accounts)); $contacts = Contact::getAll(); $contactId = $contacts[0]->id; $contacts[0]->forget(); $contact = Contact::getById($contactId); $this->assertTrue($contact->account->id < 0); }
protected function resolveContactByPostRecipientData(array $recipientData) { if (isset($recipientData['contactId'])) { return Contact::getById(intval($recipientData['contactId'])); } return null; }
protected static function generateCampaignItems($campaign, $pageSize) { if ($pageSize == null) { $pageSize = self::DEFAULT_CAMPAIGNITEMS_TO_CREATE_PAGE_SIZE; } $contacts = array(); $quote = DatabaseCompatibilityUtil::getQuote(); $marketingListMemberTableName = RedBeanModel::getTableName('MarketingListMember'); $campaignItemTableName = RedBeanModel::getTableName('CampaignItem'); $sql = "select {$quote}{$marketingListMemberTableName}{$quote}.{$quote}contact_id{$quote} from {$quote}{$marketingListMemberTableName}{$quote}"; // Not Coding Standard $sql .= "left join {$quote}{$campaignItemTableName}{$quote} on "; $sql .= "{$quote}{$campaignItemTableName}{$quote}.{$quote}contact_id{$quote} "; $sql .= "= {$quote}{$marketingListMemberTableName}{$quote}.{$quote}contact_id{$quote}"; $sql .= "AND {$quote}{$campaignItemTableName}{$quote}.{$quote}campaign_id{$quote} = " . $campaign->id . " "; $sql .= "where {$quote}{$marketingListMemberTableName}{$quote}.{$quote}marketinglist_id{$quote} = " . $campaign->marketingList->id; $sql .= " and {$quote}{$campaignItemTableName}{$quote}.{$quote}id{$quote} is null limit " . $pageSize; $ids = R::getCol($sql); foreach ($ids as $contactId) { $contacts[] = Contact::getById((int) $contactId); } if (!empty($contacts)) { //todo: if the return value is false, then we might need to catch that since it didn't go well. CampaignItem::registerCampaignItemsByCampaign($campaign, $contacts); if (count($ids) < $pageSize) { return true; } } else { return true; } return false; }
public function deleteAction() { $contactObj = Contact::getById($this->getRequest()->getParam('id')); if ($this->getRequest()->isPost()) { $contactObj->delete(); $this->Member->log('Đặt hàng: ' . $contactObj->full_name . '(' . $this->getRequest()->getParam('id') . ')', 'Xóa đơn hàng'); My_Plugin_Libs::setSplash('Đơn hàng của: <b>' . $contactObj->full_name . '</b> đã xóa khỏi hệ thống.'); $this->_redirect($this->_helper->url('index', 'contact', 'admin')); } $this->view->Contact = $contactObj; }
public function actionCreateFromRelation($relationAttributeName, $relationModelId, $relationModuleId, $redirectUrl) { $opportunity = $this->resolveNewModelByRelationInformation(new Opportunity(), $relationAttributeName, (int) $relationModelId, $relationModuleId); if ($relationAttributeName == 'contacts') { $relationContact = Contact::getById((int) $relationModelId); if ($relationContact->account->id > 0) { $opportunity->account = $relationContact->account; } } $this->actionCreateByModel($opportunity, $redirectUrl); }
/** * Test sending an email that should go out as a processing that this job would typically do. * Also tests that item does not get trashed when deleting the WorkflowMessageInQueue. * Also tests that if there is more than one emailmessage against the workflow, that it does not send * to all of them * @depends testWorkflowMessageInQueueProperlySavesWithoutTrashingRelatedModelItem */ public function testRun() { Yii::app()->user->userModel = User::getByUsername('super'); $emailTemplate = new EmailTemplate(); $emailTemplate->name = 'the name'; $emailTemplate->modelClassName = 'Account'; $emailTemplate->type = 2; $emailTemplate->subject = 'subject'; $emailTemplate->textContent = 'sample text content'; $saved = $emailTemplate->save(); $this->assertTrue($saved); $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount()); $model = ContactTestHelper::createContactByNameForOwner('Jason', Yii::app()->user->userModel); $model->primaryEmail->emailAddress = '*****@*****.**'; $saved = $model->save(); $this->assertTrue($saved); $modelId = $model->id; $model->forget(); $model = Contact::getById($modelId); $trigger = array('attributeIndexOrDerivedType' => 'firstName', 'operator' => OperatorRules::TYPE_EQUALS, 'durationInterval' => '333'); $actions = array(array('type' => ActionForWorkflowForm::TYPE_UPDATE_SELF, ActionForWorkflowForm::ACTION_ATTRIBUTES => array('description' => array('shouldSetValue' => '1', 'type' => WorkflowActionAttributeForm::TYPE_STATIC, 'value' => 'some new description')))); $emailMessages = array(); $emailMessages[0]['emailTemplateId'] = $emailTemplate->id; $emailMessages[0]['sendFromType'] = EmailMessageForWorkflowForm::SEND_FROM_TYPE_DEFAULT; $emailMessages[0]['sendAfterDurationSeconds'] = '0'; $emailMessages[0][EmailMessageForWorkflowForm::EMAIL_MESSAGE_RECIPIENTS] = array(array('type' => WorkflowEmailMessageRecipientForm::TYPE_DYNAMIC_TRIGGERED_MODEL, 'audienceType' => EmailMessageRecipient::TYPE_TO)); $emailMessages[1]['emailTemplateId'] = $emailTemplate->id; $emailMessages[1]['sendFromType'] = EmailMessageForWorkflowForm::SEND_FROM_TYPE_DEFAULT; $emailMessages[1]['sendAfterDurationSeconds'] = '10000'; $emailMessages[1][EmailMessageForWorkflowForm::EMAIL_MESSAGE_RECIPIENTS] = array(array('type' => WorkflowEmailMessageRecipientForm::TYPE_DYNAMIC_TRIGGERED_MODEL, 'audienceType' => EmailMessageRecipient::TYPE_TO)); $savedWorkflow = new SavedWorkflow(); $savedWorkflow->name = 'some workflow'; $savedWorkflow->description = 'description'; $savedWorkflow->moduleClassName = 'ContactsModule'; $savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW_AND_EXISTING; $savedWorkflow->type = Workflow::TYPE_ON_SAVE; $data[ComponentForWorkflowForm::TYPE_TRIGGERS] = array($trigger); $data[ComponentForWorkflowForm::TYPE_ACTIONS] = $actions; $data[ComponentForWorkflowForm::TYPE_EMAIL_MESSAGES] = $emailMessages; $savedWorkflow->serializedData = serialize($data); $savedWorkflow->isActive = true; $saved = $savedWorkflow->save(); $this->assertTrue($saved); WorkflowTestHelper::createExpiredWorkflowMessageInQueue($model, $savedWorkflow, serialize(array($emailMessages[1]))); RedBeanModelsCache::forgetAll(true); //simulates page change, required to confirm Item does not get trashed $this->assertEquals(1, count(WorkflowMessageInQueue::getAll())); $job = new WorkflowMessageInQueueJob(); $this->assertTrue($job->run()); $this->assertEquals(0, count(WorkflowMessageInQueue::getAll())); RedBeanModelsCache::forgetAll(true); //simulates page change, required to confirm Item does not get trashed $this->assertEquals(1, Yii::app()->emailHelper->getQueuedCount()); }
public function deleteAction() { $contactObj = Contact::getById($this->getRequest()->getParam('id')); if ($contactObj) { if ($this->getRequest()->isPost()) { $contactObj->delete(); $this->Member->log('Delete: ' . $contactObj->contact_first_name . " " . $contactObj->contact_last_name . '(' . $this->getRequest()->getParam('id') . ')', 'Contact'); My_Plugin_Libs::setSplash('Contact by: <b>' . $contactObj->contact_first_name . " " . $contactObj->contact_last_name . '</b> have been delete.'); $this->_redirect($this->_helper->url('index', 'contact', 'admin')); } $this->view->Contact = $contactObj; } }
public function testSuperUserCreateMessageAndViewDetails() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); Yii::app()->emailHelper->outboundHost = 'temporaryForTesting'; $superContactId = self::getModelIdByModelNameAndName('Contact', 'superContact superContactson'); $contact = Contact::getById($superContactId); //Just going to compose without coming from any specific record $this->resetGetArray(); $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/createEmailMessage'); //Go to compose without the email address set but the contact set $this->setGetArray(array('relatedId' => $superContactId, 'relatedModelClassName' => 'Contact')); $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/createEmailMessage'); //Go to compose with the email address set and the contact set $this->setGetArray(array('toAddress' => '*****@*****.**', 'relatedId' => $superContactId, 'relatedModelClassName' => 'Contact')); $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/createEmailMessage'); //confirm there are no email messages currently $this->assertEquals(0, EmailMessage::getCount()); $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount()); $this->assertEquals(0, Yii::app()->emailHelper->getSentCount()); //Test create email with invalid form $createEmailMessageFormData = array('recipientsData' => array('to' => '*****@*****.**'), 'subject' => '', 'content' => ''); $this->setPostArray(array('ajax' => 'edit-form', 'CreateEmailMessageForm' => $createEmailMessageFormData)); $content = $this->runControllerWithExitExceptionAndGetContent('emailMessages/default/createEmailMessage'); //Confirm that error messages are displayed $this->assertContains(Zurmo::t('emailMessagesModule', 'Subject cannot be blank.'), $content); //Confirm that no email messages was sent $this->assertEquals(0, EmailMessage::getCount()); $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount()); $this->assertEquals(0, Yii::app()->emailHelper->getSentCount()); //Validate form $createEmailMessageFormData = array('recipientsData' => array('to' => '*****@*****.**'), 'subject' => 'test subject', 'content' => array('htmlContent' => '<p>html body content</p>')); $this->setGetArray(array('toAddress' => '*****@*****.**', 'relatedId' => $superContactId, 'relatedModelClassName' => 'Contact')); $this->setPostArray(array('ajax' => 'edit-form', 'CreateEmailMessageForm' => $createEmailMessageFormData)); $this->runControllerWithExitExceptionAndGetContent('emailMessages/default/createEmailMessage'); //create email message $this->setGetArray(array('toAddress' => '*****@*****.**', 'relatedId' => $superContactId, 'relatedModelClassName' => 'Contact')); $this->setPostArray(array('CreateEmailMessageForm' => $createEmailMessageFormData)); $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/createEmailMessage', true); //confirm there is one email $this->assertEquals(1, EmailMessage::getCount()); $this->assertEquals(1, Yii::app()->emailHelper->getQueuedCount()); $this->assertEquals(0, Yii::app()->emailHelper->getSentCount()); //To address must be the one in postArray $emailMessages = EmailMessage::getAll(); $this->assertEquals('*****@*****.**', $emailMessages[0]->recipients[0]->toAddress); //Test the default permission was setted $everyoneGroup = Group::getByName(Group::EVERYONE_GROUP_NAME); $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($emailMessages[0]); $readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables(); $this->assertEquals($everyoneGroup, $readWritePermitables[$everyoneGroup->getClassId('Permitable')]); }
public function testKanbanViewForContactDetails() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $superContactId = self::getModelIdByModelNameAndName('Contact', 'superContact superContactson'); $contact = Contact::getById($superContactId); $task = TaskTestHelper::createTaskWithOwnerAndRelatedItem('MyTask', $super, $contact, Task::STATUS_IN_PROGRESS); $taskNew = TaskTestHelper::createTaskWithOwnerAndRelatedItem('MyTask New', $super, $contact, Task::STATUS_NEW); $this->setGetArray(array('id' => $task->id, 'kanbanBoard' => '1')); $content = $this->runControllerWithNoExceptionsAndGetContent('contacts/default/details'); $matcher = array('tag' => 'h4', 'ancestor' => array('tag' => 'li', 'id' => 'items_' . $task->id, 'tag' => 'ul', 'id' => 'task-sortable-rows-3'), 'content' => 'MyTask'); $this->assertTag($matcher, $content); $matcher = array('tag' => 'h4', 'ancestor' => array('tag' => 'li', 'id' => 'items_' . $taskNew->id, 'tag' => 'ul', 'id' => 'task-sortable-rows-1'), 'content' => 'MyTask New'); $this->assertTag($matcher, $content); }
public function testSuperUserAllDefaultControllerActions() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $superAccountId = self::getModelIdByModelNameAndName('Account', 'superAccount'); $superAccountId2 = self::getModelIdByModelNameAndName('Account', 'superAccount2'); $superContactId = self::getModelIdByModelNameAndName('Contact', 'superContact superContactson'); $account = Account::getById($superAccountId); $account2 = Account::getById($superAccountId2); $contact = Contact::getById($superContactId); //confirm no existing activities exist $activities = Activity::getAll(); $this->assertEquals(0, count($activities)); //Test just going to the create from relation view. $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect')); $this->runControllerWithNoExceptionsAndGetContent('tasks/default/modalCreateFromRelation'); //add related task for account using createFromRelation action $activityItemPostData = array('Account' => array('id' => $superAccountId)); $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect')); $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Task' => array('name' => 'myTask'))); $this->runControllerWithNoExceptionsAndGetContent('tasks/default/modalSaveFromRelation'); //now test that the new task exists, and is related to the account. $tasks = Task::getAll(); $this->assertEquals(1, count($tasks)); $this->assertEquals('myTask', $tasks[0]->name); $this->assertEquals(1, $tasks[0]->activityItems->count()); $activityItem1 = $tasks[0]->activityItems->offsetGet(0); $this->assertEquals($account, $activityItem1); //test viewing the existing task in a details view $this->setGetArray(array('id' => $tasks[0]->id)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('tasks/default/modalDetails'); //test submitting the task on change $this->setGetArray(array('id' => $tasks[0]->id)); $this->setPostArray(array('Task' => array('name' => 'myTask', 'status' => Task::STATUS_IN_PROGRESS))); $this->runControllerWithNoExceptionsAndGetContent('tasks/default/modalDetails'); //Test just going to the copy from relation $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'id' => $tasks[0]->id)); $this->runControllerWithNoExceptionsAndGetContent('tasks/default/modalCopyFromRelation'); $tasks = Task::getAll(); $this->assertEquals(2, count($tasks)); $this->assertEquals('myTask', $tasks[1]->name); $this->assertEquals(1, $tasks[1]->activityItems->count()); //test removing a task. $this->setGetArray(array('id' => $tasks[0]->id)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('tasks/default/delete', true); //Confirm no more tasks exist. $tasks = Task::getAll(); $this->assertEquals(1, count($tasks)); }
public function validateSelectedContact($attribute, $params) { if ($this->selectContactOrEmailRadioButton == 1) { return true; } $contactId = $this->selectContactOrLeadSearchBox; if (!empty($contactId)) { try { $contact = Contact::getById((int) $contactId); if (empty($contact->primaryEmail->emailAddress)) { $this->addError($attribute, Zurmo::t('MarketingModule', 'Selected contact does not have a valid primary email address.')); return false; } return true; } catch (NotFoundException $e) { } } $this->addError($attribute, Zurmo::t('MarketingModule', 'Please select a valid contact.')); return true; }
public function testUnlinkContactForAccount() { $accounts = Account::getAll(); $this->assertEquals(1, count($accounts)); $contacts = Contact::getAll(); $this->assertEquals(2, count($contacts)); $superAccountId = self::getModelIdByModelNameAndName('Account', 'superAccount'); $this->setGetArray(array('id' => $superAccountId)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('accounts/default/details'); $contactId = self::getModelIdByModelNameAndName('Contact', 'superContact superContactson'); //unlinking the contact $this->setGetArray(array('id' => $contactId, 'relationModelClassName' => 'Account', 'relationModelId' => $superAccountId, 'relationModelRelationName' => 'contacts')); $content = $this->runControllerWithNoExceptionsAndGetContent('contacts/default/unlink', true); $accounts = Account::getAll(); $this->assertEquals(1, count($accounts)); $contacts = Contact::getAll(); $contactId = $contacts[0]->id; $contacts[0]->forget(); $contact = Contact::getById($contactId); $this->assertTrue($contact->account->id < 0); }
protected static function generateCampaignItems($campaign, $pageSize) { if ($pageSize == null) { $pageSize = self::DEFAULT_CAMPAIGNITEMS_TO_CREATE_PAGE_SIZE; } $contacts = array(); $quote = DatabaseCompatibilityUtil::getQuote(); $sql = "select {$quote}marketinglistmember{$quote}.{$quote}contact_id{$quote} from {$quote}marketinglistmember{$quote}\n left join {$quote}campaignitem{$quote} on {$quote}campaignitem{$quote}.{$quote}contact_id{$quote} " . "= {$quote}marketinglistmember{$quote}.{$quote}contact_id{$quote} " . "AND {$quote}campaignitem{$quote}.{$quote}campaign_id{$quote} = " . $campaign->id . " where {$quote}marketinglistmember{$quote}.{$quote}marketinglist_id{$quote} = " . $campaign->marketingList->id . " and {$quote}campaignitem{$quote}.{$quote}id{$quote} IS NULL limit " . $pageSize; $ids = R::getCol($sql); foreach ($ids as $contactId) { $contacts[] = Contact::getById((int) $contactId); } if (!empty($contacts)) { //todo: if the return value is false, then we might need to catch that since it didn't go well. CampaignItem::registerCampaignItemsByCampaign($campaign, $contacts); if (count($ids) < $pageSize) { return true; } } else { return true; } }
/** * @depends testGenerateCampaignItemsForDueCampaigns */ public function testGenerateCampaignItemsForDueCampaignsWithCustomBatchSize() { $contactIds = array(); $marketingListIds = array(); $campaignIds = array(); for ($index = 6; $index < 9; $index++) { $contact = ContactTestHelper::createContactByNameForOwner('campaignContact 0' . $index, $this->user); $contactIds[] = $contact->id; $contact->forgetAll(); } for ($index = 8; $index < 12; $index++) { $suffix = $index; if ($index < 10) { $suffix = "0{$suffix}"; } $marketingList = MarketingListTestHelper::createMarketingListByName('marketingList ' . $suffix); $marketingListId = $marketingList->id; $marketingListIds[] = $marketingListId; foreach ($contactIds as $contactId) { $contact = Contact::getById($contactId); $unsubscribed = rand(10, 20) % 2; MarketingListMemberTestHelper::createMarketingListMember($unsubscribed, $marketingList, $contact); } $marketingList->forgetAll(); $marketingList = MarketingList::getById($marketingListId); $campaignSuffix = substr($marketingList->name, -2); $campaign = CampaignTestHelper::createCampaign('campaign ' . $campaignSuffix, 'subject ' . $campaignSuffix, 'text ' . $campaignSuffix, 'html ' . $campaignSuffix, null, null, null, null, null, null, $marketingList); $this->assertNotNull($campaign); $campaignIds[] = $campaign->id; $campaign->forgetAll(); } foreach ($campaignIds as $campaignId) { $campaignItems = CampaignItem::getByProcessedAndCampaignId(0, $campaignId); $this->assertEmpty($campaignItems); } $this->assertTrue(CampaignItemsUtil::generateCampaignItemsForDueCampaigns(5)); foreach ($campaignIds as $index => $campaignId) { $campaign = Campaign::getById($campaignId); $campaignItems = CampaignItem::getByProcessedAndCampaignId(0, $campaignId); if ($index === 0) { $expectedCount = AutoresponderOrCampaignBatchSizeConfigUtil::getBatchSize(); $memberCount = count($campaign->marketingList->marketingListMembers); if ($memberCount < $expectedCount) { $expectedCount = $memberCount; } $this->assertNotEmpty($campaignItems); $this->assertCount($expectedCount, $campaignItems); $this->assertEquals(Campaign::STATUS_PROCESSING, $campaign->status); } else { $this->assertEmpty($campaignItems); $this->assertEquals(Campaign::STATUS_ACTIVE, $campaign->status); } } $this->assertTrue(CampaignItemsUtil::generateCampaignItemsForDueCampaigns()); foreach ($campaignIds as $index => $campaignId) { $campaign = Campaign::getById($campaignId); $campaignItems = CampaignItem::getByProcessedAndCampaignId(0, $campaignId); if ($index < 2) { $expectedCount = AutoresponderOrCampaignBatchSizeConfigUtil::getBatchSize(); $memberCount = count($campaign->marketingList->marketingListMembers); if ($memberCount < $expectedCount) { $expectedCount = $memberCount; } $this->assertNotEmpty($campaignItems); $this->assertCount($expectedCount, $campaignItems); $this->assertEquals(Campaign::STATUS_PROCESSING, $campaign->status); } else { $this->assertEmpty($campaignItems); $this->assertEquals(Campaign::STATUS_ACTIVE, $campaign->status); } } // TODO: @Shoaibi: Medium: Add tests for the other campaign type. }
/** * @deletes selected leads. */ public function testMassDeleteActionsForSelectedIds() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $leads = Contact::getAll(); $this->assertEquals(16, count($leads)); $superLeadId = self::getModelIdByModelNameAndName('Contact', 'superLead'); $superLeadId2 = self::getModelIdByModelNameAndName('Contact', 'superLead2 superLead2son'); $superLeadId3 = self::getModelIdByModelNameAndName('Contact', 'superLead3 superLead3son'); $superLeadId4 = self::getModelIdByModelNameAndName('Contact', 'myNewLead myNewLeadson'); $superLeadId5 = self::getModelIdByModelNameAndName('Contact', 'superLead5 superLead5son'); $superLeadId6 = self::getModelIdByModelNameAndName('Contact', 'superLead6 superLead6son'); $superLeadId7 = self::getModelIdByModelNameAndName('Contact', 'superLead7 superLead7son'); $superLeadId8 = self::getModelIdByModelNameAndName('Contact', 'superLead8 superLead8son'); $superLeadId9 = self::getModelIdByModelNameAndName('Contact', 'superLead9 superLead9son'); $superLeadId10 = self::getModelIdByModelNameAndName('Contact', 'superLead10 superLead10son'); $superLeadId11 = self::getModelIdByModelNameAndName('Contact', 'superLead11 superLead11son'); $superLeadId12 = self::getModelIdByModelNameAndName('Contact', 'superLead12 superLead12son'); $superLeadId13 = self::getModelIdByModelNameAndName('Contact', 'myClonedLead myClonedLeadson'); //Load Model MassDelete Views. //MassDelete view for single selected ids $this->setGetArray(array('selectedIds' => '5,6,7,8,9', 'selectAll' => '')); // Not Coding Standard $this->resetPostArray(); $content = $this->runControllerWithNoExceptionsAndGetContent('leads/default/massDelete'); $this->assertFalse(strpos($content, '<strong>5</strong> Leads selected for removal') === false); //MassDelete view for all result selected ids $this->setGetArray(array('selectAll' => '1')); $this->resetPostArray(); $content = $this->runControllerWithNoExceptionsAndGetContent('leads/default/massDelete'); $this->assertFalse(strpos($content, '<strong>12</strong> Leads selected for removal') === false); //MassDelete for selected Record Count $leads = Contact::getAll(); $this->assertEquals(16, count($leads)); //MassDelete for selected ids for paged scenario $lead1 = Contact::getById($superLeadId); $lead2 = Contact::getById($superLeadId2); $lead3 = Contact::getById($superLeadId3); $lead4 = Contact::getById($superLeadId4); $lead5 = Contact::getById($superLeadId5); $lead6 = Contact::getById($superLeadId6); $pageSize = Yii::app()->pagination->getForCurrentUserByType('massDeleteProgressPageSize'); $this->assertEquals(5, $pageSize); //MassDelete for selected ids for page 1 $this->setGetArray(array('selectedIds' => $superLeadId . ',' . $superLeadId2 . ',' . $superLeadId3 . ',' . $superLeadId4 . ',' . $superLeadId5 . ',' . $superLeadId6, 'selectAll' => '', 'massDelete' => '', 'Contact_page' => 1)); $this->setPostArray(array('selectedRecordCount' => 6)); $this->runControllerWithExitExceptionAndGetContent('leads/default/massDelete'); //MassDelete for selected Record Count $leads = Contact::getAll(); $this->assertEquals(11, count($leads)); //MassDelete for selected ids for page 2 $this->setGetArray(array('selectedIds' => $superLeadId . ',' . $superLeadId2 . ',' . $superLeadId3 . ',' . $superLeadId4 . ',' . $superLeadId5 . ',' . $superLeadId6 . ',' . $superLeadId13, 'selectAll' => '', 'massDelete' => '', 'Contact_page' => 2)); $this->setPostArray(array('selectedRecordCount' => 7)); $this->runControllerWithNoExceptionsAndGetContent('leads/default/massDeleteProgress'); //MassDelete for selected Record Count $leads = Contact::getAll(); $this->assertEquals(9, count($leads)); }
public function testSuperUserCopyAction() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $superAccountId = self::getModelIdByModelNameAndName('Account', 'superAccount'); $superContactId = self::getModelIdByModelNameAndName('Contact', 'superContact superContactson'); $account = Account::getById($superAccountId); $contact = Contact::getById($superContactId); $activityItemPostData = array('Account' => array('id' => $superAccountId), 'Contact' => array('id' => $superContactId)); $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect')); $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Task' => array('name' => 'myTask', 'description' => 'Some task description'))); $this->runControllerWithRedirectExceptionAndGetContent('tasks/default/createFromRelation'); $tasks = Task::getByName('myTask'); $this->assertCount(1, $tasks); $this->setGetArray(array('id' => $tasks[0]->id)); $this->resetPostArray(); $content = $this->runControllerWithNoExceptionsAndGetContent('tasks/default/copy'); $this->assertContains($tasks[0]->name, $content); $this->assertContains($tasks[0]->description, $content); $this->assertContains($account->name, $content); $this->assertContains($contact->getFullName(), $content); $taskCopy = new Task(); ActivityCopyModelUtil::copy($tasks[0], $taskCopy); $activityItemPostData = array(); foreach ($taskCopy->activityItems as $relatedModel) { $activityItemPostData[get_class($relatedModel)] = array('id' => $relatedModel->id); } $postArray = array('Task' => array('name' => $taskCopy->name, 'description' => $taskCopy->description), 'ActivityItemForm' => $activityItemPostData); $this->setPostArray($postArray); $this->setGetArray(array('id' => $tasks[0]->id)); $content = $this->runControllerWithRedirectExceptionAndGetContent('tasks/default/copy'); $tasks = Task::getByName('myTask'); $this->assertCount(2, $tasks); $this->assertEquals($tasks[0]->name, $tasks[1]->name); $this->assertEquals($tasks[0]->description, $tasks[1]->description); $this->assertEquals($tasks[0]->activityItems[0], $tasks[1]->activityItems[0]); $this->assertEquals($tasks[0]->activityItems[1], $tasks[1]->activityItems[1]); $tasks[0]->delete(); $tasks[1]->delete(); }
public function testForgettingAModelWithAddingAManyToManyRelation() { $super = User::getByUsername('super'); Yii::app()->user->userModel = $super; //Setup test data owned by the super user. $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super); $contact = ContactTestHelper::createContactWithAccountByNameForOwner('superContact', $super, $account); $contactId = $contact->id; OpportunityTestHelper::createOpportunityStagesIfDoesNotExist(); $opportunity = OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp', $super, $account); $opportunityId = $opportunity->id; //Model forgets ok. $contact->forget(); $contact = Contact::getById($contactId); $opportunity->contacts->add($contact); $opportunity->save(); //Still forgets ok, because we are forgetting both opportunity and contact. If we forget just contact, //it would break later when you try to look at $contact->oppportunities or $opportunity->contacts $contact->forget(); $opportunity->forget(); $contact = Contact::getById($contactId); $opportunity = Opportunity::getById($opportunityId); //Finds many-to-many relationships ok on both sides $this->assertEquals(1, $opportunity->contacts->count()); $this->assertEquals(1, $contact->opportunities->count()); $this->assertEquals($opportunity, $contact->opportunities[0]); $this->assertEquals($contact, $opportunity->contacts[0]); }
public function actionSendTestEmail($id, $contactId = null, $emailAddress = null, $useHtmlContent = 1) { $emailTemplate = EmailTemplate::getById(intval($id)); ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($emailTemplate); $htmlContent = $emailTemplate->htmlContent; if (!$useHtmlContent) { $htmlContent = EmailTemplateSerializedDataToHtmlUtil::resolveHtmlByEmailTemplateModel($emailTemplate, false); } $contact = null; if (isset($contactId)) { $contact = Contact::getById(intval($contactId)); } static::resolveEmailMessage($emailTemplate, $contact, $htmlContent, $emailAddress); }
/** * @depends testEditOfTheLeadUserForTheTagCloudFieldAfterRemovingAllTagsPlacedForLeadsModule */ public function testEditOfTheLeadUserForTheCustomFieldsPlacedForLeadsModule() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); //Retrieve the the super user id. $superUserId = $super->id; //Retrieve the lead id. $leadId = self::getModelIdByModelNameAndName('Contact', 'Sarah Williams Edit'); //Set the date and datetime variable values here. $date = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateFormatForInput(), time()); $dateAssert = date('Y-m-d'); $datetime = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateTimeFormatForInput(), time()); $datetimeAssert = date('Y-m-d H:i:') . "00"; $baseCurrency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode()); //Retrieve the Lead State (Status) Id based on the name. $leadState = ContactState::getByName('In Progress'); $leadStateId = $leadState[0]->id; $explicitReadWriteModelPermission = ExplicitReadWriteModelPermissionsUtil::MIXED_TYPE_EVERYONE_GROUP; //Edit and save the lead. $this->setGetArray(array('id' => $leadId)); $this->setPostArray(array('Contact' => array('title' => array('value' => 'Mrs.'), 'firstName' => 'Sarah', 'lastName' => 'Williams Edit', 'jobTitle' => 'Sales Director Edit', 'companyName' => 'ABC Telecom Edit', 'industry' => array('value' => 'Banking'), 'website' => 'http://www.companyedit.com', 'department' => 'Sales Edit', 'officePhone' => '739-742-3005', 'source' => array('value' => 'Inbound Call'), 'mobilePhone' => '285-300-8232', 'officeFax' => '255-454-1914', 'state' => array('id' => $leadStateId), 'owner' => array('id' => $superUserId), 'primaryEmail' => array('emailAddress' => '*****@*****.**', 'optOut' => '0', 'isInvalid' => '0'), 'secondaryEmail' => array('emailAddress' => '*****@*****.**', 'optOut' => '0', 'isInvalid' => '0'), 'primaryAddress' => array('street1' => '26378 South Arlington Ave', 'street2' => '', 'city' => 'San Jose', 'state' => 'CA', 'postalCode' => '95131', 'country' => 'USA'), 'secondaryAddress' => array('street1' => '1652 North Cedar Court', 'street2' => '', 'city' => 'Phoenix', 'state' => 'AZ', 'postalCode' => '85003', 'country' => 'USA'), 'explicitReadWriteModelPermissions' => array('type' => $explicitReadWriteModelPermission), 'description' => 'This is a Edit Description', 'checkboxCstm' => '0', 'currencyCstm' => array('value' => 40, 'currency' => array('id' => $baseCurrency->id)), 'dateCstm' => $date, 'datetimeCstm' => $datetime, 'decimalCstm' => '12', 'picklistCstm' => array('value' => 'b'), 'multiselectCstm' => array('values' => array('gg', 'hh')), 'tagcloudCstm' => array('values' => array('reading', 'surfing')), 'countrylistCstm' => array('value' => 'aaaa'), 'statelistCstm' => array('value' => 'aaa1'), 'citylistCstm' => array('value' => 'ab1'), 'integerCstm' => '11', 'phoneCstm' => '259-784-2069', 'radioCstm' => array('value' => 'e'), 'textCstm' => 'This is a test Edit Text', 'textareaCstm' => 'This is a test Edit TextArea', 'urlCstm' => 'http://wwww.abc-edit.com'), 'save' => 'Save')); $this->runControllerWithRedirectExceptionAndGetUrl('leads/default/edit'); //Check the details if they are saved properly for the custom fields after the edit. $lead = Contact::getById($leadId); //Retrieve the permission of the lead. $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($lead); $readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables(); $readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables(); $this->assertEquals($lead->title->value, 'Mrs.'); $this->assertEquals($lead->firstName, 'Sarah'); $this->assertEquals($lead->lastName, 'Williams Edit'); $this->assertEquals($lead->state->id, $leadStateId); $this->assertEquals($lead->jobTitle, 'Sales Director Edit'); $this->assertEquals($lead->companyName, 'ABC Telecom Edit'); $this->assertEquals($lead->industry->value, 'Banking'); $this->assertEquals($lead->website, 'http://www.companyedit.com'); $this->assertEquals($lead->department, 'Sales Edit'); $this->assertEquals($lead->officePhone, '739-742-3005'); $this->assertEquals($lead->source->value, 'Inbound Call'); $this->assertEquals($lead->mobilePhone, '285-300-8232'); $this->assertEquals($lead->officeFax, '255-454-1914'); $this->assertEquals($lead->primaryEmail->emailAddress, '*****@*****.**'); $this->assertEquals($lead->primaryEmail->optOut, '0'); $this->assertEquals($lead->primaryEmail->isInvalid, '0'); $this->assertEquals($lead->secondaryEmail->emailAddress, '*****@*****.**'); $this->assertEquals($lead->secondaryEmail->optOut, '0'); $this->assertEquals($lead->secondaryEmail->isInvalid, '0'); $this->assertEquals($lead->primaryAddress->street1, '26378 South Arlington Ave'); $this->assertEquals($lead->primaryAddress->street2, ''); $this->assertEquals($lead->primaryAddress->city, 'San Jose'); $this->assertEquals($lead->primaryAddress->state, 'CA'); $this->assertEquals($lead->primaryAddress->postalCode, '95131'); $this->assertEquals($lead->primaryAddress->country, 'USA'); $this->assertEquals($lead->secondaryAddress->street1, '1652 North Cedar Court'); $this->assertEquals($lead->secondaryAddress->street2, ''); $this->assertEquals($lead->secondaryAddress->city, 'Phoenix'); $this->assertEquals($lead->secondaryAddress->state, 'AZ'); $this->assertEquals($lead->secondaryAddress->postalCode, '85003'); $this->assertEquals($lead->secondaryAddress->country, 'USA'); $this->assertEquals(1, count($readWritePermitables)); $this->assertEquals(0, count($readOnlyPermitables)); $this->assertEquals($lead->description, 'This is a Edit Description'); $this->assertEquals($lead->checkboxCstm, '0'); $this->assertEquals($lead->currencyCstm->value, 40); $this->assertEquals($lead->currencyCstm->currency->id, $baseCurrency->id); $this->assertEquals($lead->dateCstm, $dateAssert); $this->assertEquals($lead->datetimeCstm, $datetimeAssert); $this->assertEquals($lead->decimalCstm, '12'); $this->assertEquals($lead->picklistCstm->value, 'b'); $this->assertEquals($lead->integerCstm, 11); $this->assertEquals($lead->phoneCstm, '259-784-2069'); $this->assertEquals($lead->radioCstm->value, 'e'); $this->assertEquals($lead->textCstm, 'This is a test Edit Text'); $this->assertEquals($lead->textareaCstm, 'This is a test Edit TextArea'); $this->assertEquals($lead->urlCstm, 'http://wwww.abc-edit.com'); $this->assertEquals($lead->countrylistCstm->value, 'aaaa'); $this->assertEquals($lead->statelistCstm->value, 'aaa1'); $this->assertEquals($lead->citylistCstm->value, 'ab1'); $this->assertContains('gg', $lead->multiselectCstm->values); $this->assertContains('hh', $lead->multiselectCstm->values); $this->assertContains('reading', $lead->tagcloudCstm->values); $this->assertContains('surfing', $lead->tagcloudCstm->values); $metadata = CalculatedDerivedAttributeMetadata::getByNameAndModelClassName('calcnumber', 'Contact'); $testCalculatedValue = CalculatedNumberUtil::calculateByFormulaAndModelAndResolveFormat($metadata->getFormula(), $lead); $this->assertEquals(23, $testCalculatedValue); }
public function testUserHasNoAccessToAccountsAndTriesToConvertWhenAccountIsOptional() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $belina = UserTestHelper::createBasicUser('belina'); $lead = LeadTestHelper::createLeadbyNameForOwner('BelinaLead1', $belina); $belina->setRight('LeadsModule', LeadsModule::RIGHT_CONVERT_LEADS, Right::ALLOW); $belina->setRight('LeadsModule', LeadsModule::RIGHT_ACCESS_LEADS, Right::ALLOW); $belina->setRight('ContactsModule', ContactsModule::RIGHT_CREATE_CONTACTS, Right::ALLOW); $belina->setRight('ContactsModule', ContactsModule::RIGHT_ACCESS_CONTACTS, Right::ALLOW); $this->assertTrue($belina->save()); $this->assertEquals(Right::DENY, $belina->getEffectiveRight('AccountsModule', AccountsModule::RIGHT_ACCESS_ACCOUNTS)); $this->assertEquals(Right::DENY, $belina->getEffectiveRight('OpportunitiesModule', OpportunitiesModule::RIGHT_ACCESS_OPPORTUNITIES)); $belina = $this->logoutCurrentUserLoginNewUserAndGetByUsername('belina'); //Now check that when belina tries to convert a lead, it will automatically make it an account. $convertToAccountSetting = LeadsModule::getConvertToAccountSetting(); $this->assertTrue($convertToAccountSetting == LeadsModule::CONVERT_NO_ACCOUNT || $convertToAccountSetting == LeadsModule::CONVERT_ACCOUNT_NOT_REQUIRED); $convertToOpportunitySetting = LeadsModule::getConvertToOpportunitySetting(); $this->assertTrue($convertToOpportunitySetting == LeadsModule::CONVERT_NO_OPPORTUNITY || $convertToOpportunitySetting == LeadsModule::CONVERT_OPPORTUNITY_NOT_REQUIRED); $oldStateValue = $lead->state->name; $this->setGetArray(array('id' => $lead->id)); $this->runControllerWithRedirectExceptionAndGetContent('leads/default/convert'); $this->setGetArray(array('id' => $lead->id)); $this->runControllerWithRedirectExceptionAndGetContent('leads/default/convertFinal'); $contact = Contact::getById($lead->id); $this->assertNotEquals($oldStateValue, $contact->state->name); }
/** * @depends testSuperUserDefaultPortletControllerActions */ public function testSuperUserDeleteAction() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $superOpportunityId4 = self::getModelIdByModelNameAndName('Opportunity', 'superOpp4'); //Delete an opportunity. $this->setGetArray(array('id' => $superOpportunityId4)); $this->resetPostArray(); $this->runControllerWithRedirectExceptionAndGetContent('opportunities/default/delete'); $opportunities = Opportunity::getAll(); $this->assertEquals(11, count($opportunities)); try { Contact::getById($superOpportunityId4); $this->fail(); } catch (NotFoundException $e) { //success } }
public function testSuperUserAllDefaultControllerActions() { $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $superAccountId = self::getModelIdByModelNameAndName('Account', 'superAccount'); $superAccountId2 = self::getModelIdByModelNameAndName('Account', 'superAccount2'); $superContactId = self::getModelIdByModelNameAndName('Contact', 'superContact superContactson'); $superContactId2 = self::getModelIdByModelNameAndName('Contact', 'superContact2 superContact2son'); $superContactId3 = self::getModelIdByModelNameAndName('Contact', 'superContact3 superContact3son'); $account = Account::getById($superAccountId); $account2 = Account::getById($superAccountId2); $contact = Contact::getById($superContactId); $contact2 = Contact::getById($superContactId2); $contact3 = Contact::getById($superContactId3); //confirm no existing activities exist $activities = Activity::getAll(); $this->assertEquals(0, count($activities)); //Test just going to the create from relation view. $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect')); $this->runControllerWithNoExceptionsAndGetContent('meetings/default/createFromRelation'); //add related meeting for account using createFromRelation action $activityItemPostData = array('Account' => array('id' => $superAccountId)); $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect')); $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Meeting' => array('name' => 'myMeeting', 'startDateTime' => '11/1/2011 7:45 PM'))); $this->runControllerWithRedirectExceptionAndGetContent('meetings/default/createFromRelation'); //now test that the new meeting exists, and is related to the account. $meetings = Meeting::getAll(); $this->assertEquals(1, count($meetings)); $this->assertEquals('myMeeting', $meetings[0]->name); $this->assertEquals(1, $meetings[0]->activityItems->count()); $activityItem1 = $meetings[0]->activityItems->offsetGet(0); $this->assertEquals($account, $activityItem1); //test viewing the existing meeting in a details view $this->setGetArray(array('id' => $meetings[0]->id)); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('meetings/default/details'); //test editing an existing meeting and saving. Add a second relation, to a contact. //First just go to the edit view and confirm it loads ok. $this->setGetArray(array('id' => $meetings[0]->id, 'redirectUrl' => 'someRedirect')); $this->resetPostArray(); $this->runControllerWithNoExceptionsAndGetContent('meetings/default/edit'); //Save changes via edit action. $activityItemPostData = array('Account' => array('id' => $superAccountId), 'Contact' => array('id' => $superContactId)); $this->setGetArray(array('id' => $meetings[0]->id, 'redirectUrl' => 'someRedirect')); $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Meeting' => array('name' => 'myMeetingX'))); $this->runControllerWithRedirectExceptionAndGetContent('meetings/default/edit'); //Confirm changes applied correctly. $meetings = Meeting::getAll(); $this->assertEquals(1, count($meetings)); $this->assertEquals('myMeetingX', $meetings[0]->name); $this->assertEquals(2, $meetings[0]->activityItems->count()); $activityItem1 = $meetings[0]->activityItems->offsetGet(0); $activityItem2 = $meetings[0]->activityItems->offsetGet(1); $this->assertEquals($account, $activityItem1); $this->assertEquals($contact, $activityItem2); //Remove contact relation. Switch account relation to a different account. $activityItemPostData = array('Account' => array('id' => $superAccountId2)); $this->setGetArray(array('id' => $meetings[0]->id)); $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Meeting' => array('name' => 'myMeetingX'))); $this->runControllerWithRedirectExceptionAndGetContent('meetings/default/edit'); //Confirm changes applied correctly. $meetings = Meeting::getAll(); $this->assertEquals(1, count($meetings)); $this->assertEquals('myMeetingX', $meetings[0]->name); $this->assertEquals(1, $meetings[0]->activityItems->count()); $activityItem1 = $meetings[0]->activityItems->offsetGet(0); $this->assertEquals($account2, $activityItem1); //test removing a meeting. $this->setGetArray(array('id' => $meetings[0]->id)); $this->resetPostArray(); $this->runControllerWithRedirectExceptionAndGetContent('meetings/default/delete'); //Confirm no more meetings exist. $meetings = Meeting::getAll(); $this->assertEquals(0, count($meetings)); //Test adding a meeting with multiple contacts $contactItemPrefix = Meeting::CONTACT_ATTENDEE_PREFIX; $meetingAttendeesData = $contactItemPrefix . $superContactId . ',' . $contactItemPrefix . $superContactId2 . ',' . $contactItemPrefix . $superContactId3; $activityItemPostData = array('Account' => array('id' => $superAccountId), 'Contact' => array('ids' => $meetingAttendeesData)); // Not Coding Standard $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect')); $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Meeting' => array('name' => 'myMeeting2', 'startDateTime' => '11/1/2011 7:45 PM'))); $this->runControllerWithRedirectExceptionAndGetContent('meetings/default/createFromRelation'); //now test that the new meeting exists, and is related to the account. $meetings = Meeting::getAll(); $this->assertEquals(1, count($meetings)); $this->assertEquals('myMeeting2', $meetings[0]->name); $this->assertEquals(4, $meetings[0]->activityItems->count()); $activityItem1 = $meetings[0]->activityItems->offsetGet(0); $this->assertEquals($account, $activityItem1); }
/** * @depends testCreateWithRelations */ public function testUpdateWithRelations() { $super = User::getByUsername('super'); Yii::app()->user->userModel = $super; $authenticationData = $this->login(); $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST'); $account = AccountTestHelper::createAccountByNameForOwner('Factor X', $super); $account1 = AccountTestHelper::createAccountByNameForOwner('Miko', $super); $account2 = AccountTestHelper::createAccountByNameForOwner('Troter', $super); $contact = ContactTestHelper::createContactByNameForOwner('Simon', $super); $compareData = $this->getModelToApiDataUtilData($account); $account->forget(); $data['modelRelations'] = array('accounts' => array(array('action' => 'add', 'modelId' => $account1->id, 'modelClassName' => 'Account'), array('action' => 'add', 'modelId' => $account2->id, 'modelClassName' => 'Account')), 'contacts' => array(array('action' => 'add', 'modelId' => $contact->id, 'modelClassName' => 'Contact'))); $data['name'] = 'Zurmo Inc.'; $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data)); $response = json_decode($response, true); unset($response['data']['modifiedDateTime']); unset($compareData['modifiedDateTime']); $compareData['name'] = 'Zurmo Inc.'; $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']); $this->assertEquals($compareData, $response['data']); RedBeanModel::forgetAll(); $account = Account::getById($compareData['id']); $this->assertEquals(2, count($account->accounts)); $this->assertEquals($account1->id, $account->accounts[0]->id); $this->assertEquals($account2->id, $account->accounts[1]->id); $this->assertEquals(1, count($account->contacts)); $this->assertEquals($contact->id, $account->contacts[0]->id); $account1 = Account::getById($account1->id); $this->assertEquals($account->id, $account1->account->id); $account2 = Account::getById($account2->id); $this->assertEquals($account->id, $account2->account->id); $contact = Contact::getById($contact->id); $this->assertEquals($account->id, $contact->account->id); // Now test remove relations $data['modelRelations'] = array('accounts' => array(array('action' => 'remove', 'modelId' => $account1->id, 'modelClassName' => 'Account'), array('action' => 'remove', 'modelId' => $account2->id, 'modelClassName' => 'Account')), 'contacts' => array(array('action' => 'remove', 'modelId' => $contact->id, 'modelClassName' => 'Contact'))); $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data)); $response = json_decode($response, true); $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']); RedBeanModel::forgetAll(); $updatedModel = Account::getById($compareData['id']); $this->assertEquals(0, count($updatedModel->accounts)); $this->assertEquals(0, count($updatedModel->contacts)); $account1 = Account::getById($account1->id); $this->assertLessThanOrEqual(0, $account1->account->id); $account2 = Account::getById($account2->id); $this->assertLessThanOrEqual(0, $account2->account->id); $contact = Contact::getById($contact->id); $this->assertLessThanOrEqual(0, $contact->account->id); }
public function testArePermissionsFlushedOnRemovingParentFromChildRole() { Contact::deleteAll(); try { $role = Role::getByName('Parent'); $role->delete(); } catch (NotFoundException $e) { } try { $user = User::getByUsername('jim'); $user->delete(); } catch (NotFoundException $e) { } try { $user = User::getByUsername('jane'); $user->delete(); } catch (NotFoundException $e) { } // we could have used helpers to do a lot of the following stuff (such as creating users, roles, // etc) but we wanted to mimic user's interaction as closely as possible. Hence using walkthroughs // for everything // create Parent and Child Roles, Create Jim to be member of Child role // create parent role $this->resetGetArray(); $this->setPostArray(array('Role' => array('name' => 'Parent'))); $this->runControllerWithRedirectExceptionAndGetUrl('/zurmo/role/create'); $parentRole = Role::getByName('Parent'); $this->assertNotNull($parentRole); $this->assertEquals('Parent', strval($parentRole)); $parentRoleId = $parentRole->id; // create child role $this->resetGetArray(); $this->setPostArray(array('Role' => array('name' => 'Child', 'role' => array('id' => $parentRoleId)))); $this->runControllerWithRedirectExceptionAndGetUrl('/zurmo/role/create'); $childRole = Role::getByName('Child'); $this->assertNotNull($childRole); $this->assertEquals('Child', strval($childRole)); $parentRole->forgetAll(); $parentRole = Role::getById($parentRoleId); $childRoleId = $childRole->id; $childRole->forgetAll(); $childRole = Role::getById($childRoleId); $this->assertEquals($childRole->id, $parentRole->roles[0]->id); // create jim's user $this->resetGetArray(); $this->setPostArray(array('UserPasswordForm' => array('firstName' => 'Some', 'lastName' => 'Body', 'username' => 'jim', 'newPassword' => 'myPassword123', 'newPassword_repeat' => 'myPassword123', 'officePhone' => '456765421', 'userStatus' => 'Active', 'role' => array('id' => $childRoleId)))); $this->runControllerWithRedirectExceptionAndGetContent('/users/default/create'); $jim = User::getByUsername('jim'); $this->assertNotNull($jim); $childRole->forgetAll(); $childRole = Role::getById($childRoleId); $this->assertEquals($childRole->id, $jim->role->id); // give jim rights to contact's module $jim->setRight('ContactsModule', ContactsModule::getAccessRight()); $jim->setRight('ContactsModule', ContactsModule::getCreateRight()); $this->assertTrue($jim->save()); $jim->forgetAll(); $jim = User::getByUsername('jim'); // create jane's user $this->resetGetArray(); $this->setPostArray(array('UserPasswordForm' => array('firstName' => 'Some', 'lastName' => 'Body', 'username' => 'jane', 'newPassword' => 'myPassword123', 'newPassword_repeat' => 'myPassword123', 'officePhone' => '456765421', 'userStatus' => 'Active', 'role' => array('id' => $parentRoleId)))); $this->runControllerWithRedirectExceptionAndGetContent('/users/default/create'); $jane = User::getByUsername('jane'); $this->assertNotNull($jane); $parentRole->forgetAll(); $parentRole = Role::getById($parentRoleId); $this->assertEquals($parentRole->id, $jane->role->id); // give jane rights to contact's module, we need to do this because once the link between parent and child // role is broken jane won't be able to access the listview of contacts $jane->setRight('ContactsModule', ContactsModule::getAccessRight()); $this->assertTrue($jane->save()); $jane->forgetAll(); $jane = User::getByUsername('jane'); // create a contact from jim's account // create ContactStates ContactsModule::loadStartingData(); // ensure contact states have been created $this->assertEquals(6, count(ContactState::GetAll())); $this->logoutCurrentUserLoginNewUserAndGetByUsername('jim'); // go ahead and create contact with parent role given readwrite. $startingState = ContactsUtil::getStartingState(); $this->resetGetArray(); $this->setPostArray(array('Contact' => array('firstName' => 'Jim', 'lastName' => 'Doe', 'officePhone' => '456765421', 'state' => array('id' => $startingState->id)))); $url = $this->runControllerWithRedirectExceptionAndGetUrl('/contacts/default/create'); $jimDoeContactId = intval(substr($url, strpos($url, 'id=') + 3)); $jimDoeContact = Contact::getById($jimDoeContactId); $this->assertNotNull($jimDoeContact); $this->resetPostArray(); $this->setGetArray(array('id' => $jimDoeContactId)); $content = $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); $this->assertContains('Who can read and write Owner', $content); // create a contact using jane which she would see at all times $this->logoutCurrentUserLoginNewUserAndGetByUsername('jane'); $this->resetGetArray(); $this->setPostArray(array('Contact' => array('firstName' => 'Jane', 'lastName' => 'Doe', 'officePhone' => '456765421', 'state' => array('id' => $startingState->id)))); $url = $this->runControllerWithRedirectExceptionAndGetUrl('/contacts/default/create'); $janeDoeContactId = intval(substr($url, strpos($url, 'id=') + 3)); $janeDoeContact = Contact::getById($jimDoeContactId); $this->assertNotNull($janeDoeContact); $this->resetPostArray(); $this->setGetArray(array('id' => $janeDoeContactId)); $content = $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); $this->assertContains('Who can read and write Owner', $content); // ensure jim can see that contact everywhere // jim should have access to see contact on list view $this->logoutCurrentUserLoginNewUserAndGetByUsername('jim'); $this->resetGetArray(); // get the page, ensure the name of contact does show up there. $content = $this->runControllerWithNoExceptionsAndGetContent('/contacts/default'); $this->assertContains('Jim Doe</a></td><td>', $content); $this->assertNotContains('Jane Doe</a></td><td>', $content); // jim should have access to jimDoeContact's detail view $this->setGetArray(array('id' => $jimDoeContactId)); $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); // jim should have access to jimDoeContact's edit view $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/edit'); // jim should not have access to janeDoeContact's detail view $this->setGetArray(array('id' => $janeDoeContactId)); try { $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); $this->fail('Accessing details action should have thrown ExitException'); } catch (ExitException $e) { // just cleanup buffer $this->endAndGetOutputBuffer(); } // jim should have access to janeDoeContact's edit view try { $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/edit'); $this->fail('Accessing edit action should have thrown ExitException'); } catch (ExitException $e) { // just cleanup buffer $this->endAndGetOutputBuffer(); } // ensure jane can see that contact everywhere // jane should have access to see contact on list view $this->logoutCurrentUserLoginNewUserAndGetByUsername('jane'); $this->resetGetArray(); // get the page, ensure the name of contact does show up there. $content = $this->runControllerWithNoExceptionsAndGetContent('/contacts/default'); $this->assertContains('Jim Doe</a></td><td>', $content); $this->assertContains('Jane Doe</a></td><td>', $content); // jane should have access to jimDoeContact's detail view $this->setGetArray(array('id' => $jimDoeContactId)); $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); // jane should have access to jimDoeContact's edit view $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/edit'); // jane should have access to janeDoeContact's detail view $this->setGetArray(array('id' => $janeDoeContactId)); $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); // jane should have access to janeDoeContact's edit view $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/edit'); // unlink Parent role from child $this->logoutCurrentUserLoginNewUserAndGetByUsername('super'); $this->setGetArray(array('id' => $childRoleId)); $this->setPostArray(array('Role' => array('name' => 'Child', 'role' => array('id' => '')))); $this->runControllerWithRedirectExceptionAndGetUrl('/zurmo/role/edit'); $childRole = Role::getByName('Child'); $this->assertNotNull($childRole); $this->assertEquals('Child', strval($childRole)); $parentRole->forgetAll(); $parentRole = Role::getById($parentRoleId); $this->assertNotNull($parentRole); $this->assertCount(0, $parentRole->roles); // ensure jim can still see that contact everywhere // jim should have access to see contact on list view $this->logoutCurrentUserLoginNewUserAndGetByUsername('jim'); $this->resetGetArray(); // get the page, ensure the name of contact does show up there. $content = $this->runControllerWithNoExceptionsAndGetContent('/contacts/default'); $this->assertContains('Jim Doe</a></td><td>', $content); $this->assertNotContains('Jane Doe</a></td><td>', $content); // jim should have access to jimDoeContact's detail view $this->setGetArray(array('id' => $jimDoeContactId)); $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); // jim should have access to jimDoeContact's edit view $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/edit'); // jim should not have access to janeDoeContact's detail view $this->setGetArray(array('id' => $janeDoeContactId)); try { $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); $this->fail('Accessing details action should have thrown ExitException'); } catch (ExitException $e) { // just cleanup buffer $this->endAndGetOutputBuffer(); } // jim should have access to janeDoeContact's edit view try { $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/edit'); $this->fail('Accessing edit action should have thrown ExitException'); } catch (ExitException $e) { // just cleanup buffer $this->endAndGetOutputBuffer(); } // ensure jane can not see that contact anywhere // jane should have access to see contact on list view $this->logoutCurrentUserLoginNewUserAndGetByUsername('jane'); $this->resetGetArray(); // get the page, ensure the name of contact does not show up there. $content = $this->runControllerWithNoExceptionsAndGetContent('/contacts/default'); $this->assertNotContains('Jim Doe</a></td><td>', $content); $this->assertContains('Jane Doe</a></td><td>', $content); // jane should have access to janeDoeContact's detail view $this->setGetArray(array('id' => $janeDoeContactId)); $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); // jane should have access to janeDoeContact's edit view $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/edit'); // jane should not have access to jimDoeContact's detail view $this->setGetArray(array('id' => $jimDoeContactId)); try { $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); $this->fail('Accessing details action should have thrown ExitException'); } catch (ExitException $e) { // just cleanup buffer $this->endAndGetOutputBuffer(); } // jane should not have access to jimDoeContact's edit view try { $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/edit'); $this->fail('Accessing edit action should have thrown ExitException'); } catch (ExitException $e) { // just cleanup buffer $this->endAndGetOutputBuffer(); } }
public function resolveRecordSharingPerformanceTime($count) { $groupMembers = array(); // create group $this->resetGetArray(); $this->setPostArray(array('Group' => array('name' => "Group {$count}"))); $this->runControllerWithRedirectExceptionAndGetUrl('/zurmo/group/create'); $group = Group::getByName("Group {$count}"); $this->assertNotNull($group); $this->assertEquals("Group {$count}", strval($group)); $group->setRight('ContactsModule', ContactsModule::getAccessRight()); $group->setRight('ContactsModule', ContactsModule::getCreateRight()); $group->setRight('ContactsModule', ContactsModule::getDeleteRight()); $this->assertTrue($group->save()); $groupId = $group->id; $group->forgetAll(); $group = Group::getById($groupId); $this->resetGetArray(); for ($i = 0; $i < $count; $i++) { $username = static::$baseUsername . "_{$i}_of_{$count}"; // Populate group $this->setPostArray(array('UserPasswordForm' => array('firstName' => 'Some', 'lastName' => 'Body', 'username' => $username, 'newPassword' => 'myPassword123', 'newPassword_repeat' => 'myPassword123', 'officePhone' => '456765421', 'userStatus' => 'Active'))); $this->runControllerWithRedirectExceptionAndGetContent('/users/default/create'); $user = User::getByUsername($username); $this->assertNotNull($user); $groupMembers['usernames'][] = $user->username; $groupMembers['ids'][] = $user->id; } $this->assertCount($count, $groupMembers['ids']); // set user's group $this->setGetArray(array('id' => $groupId)); $this->setPostArray(array('GroupUserMembershipForm' => array('userMembershipData' => $groupMembers['ids']))); $this->runControllerWithRedirectExceptionAndGetUrl('/zurmo/group/editUserMembership'); $group->forgetAll(); $group = Group::getById($groupId); $this->assertCount($count, $group->users); foreach ($groupMembers['ids'] as $userId) { $user = User::getById($userId); $this->assertEquals($group->id, $user->groups[0]->id); $this->assertTrue(RightsUtil::doesUserHaveAllowByRightName('ContactsModule', ContactsModule::getAccessRight(), $user)); $this->assertTrue(RightsUtil::doesUserHaveAllowByRightName('ContactsModule', ContactsModule::getCreateRight(), $user)); $this->assertTrue(RightsUtil::doesUserHaveAllowByRightName('ContactsModule', ContactsModule::getDeleteRight(), $user)); } $this->clearAllCaches(); // go ahead and create contact with group given readwrite, use group's first member to confirm he has create access $this->logoutCurrentUserLoginNewUserAndGetByUsername($groupMembers['usernames'][0]); $this->resetGetArray(); $startingState = ContactsUtil::getStartingState(); $this->setPostArray(array('Contact' => array('firstName' => 'John', 'lastName' => 'Doe', 'officePhone' => '456765421', 'state' => array('id' => $startingState->id), 'explicitReadWriteModelPermissions' => array('type' => ExplicitReadWriteModelPermissionsUtil::MIXED_TYPE_NONEVERYONE_GROUP, 'nonEveryoneGroup' => $groupId)))); $startTime = microtime(true); $url = $this->runControllerWithRedirectExceptionAndGetUrl('/contacts/default/create'); $timeTakenForSave = microtime(true) - $startTime; $johnDoeContactId = intval(substr($url, strpos($url, 'id=') + 3)); $johnDoeContact = Contact::getById($johnDoeContactId); $this->assertNotNull($johnDoeContact); $this->resetPostArray(); $this->setGetArray(array('id' => $johnDoeContactId)); $content = $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); $this->assertContains('Who can read and write ' . strval($group), $content); $this->clearAllCaches(); $this->resetPostArray(); // ensure group members have access foreach ($groupMembers['usernames'] as $member) { $user = $this->logoutCurrentUserLoginNewUserAndGetByUsername($member); $this->assertNotNull($user); $this->setGetArray(array('id' => $johnDoeContactId)); $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/details'); $this->runControllerWithNoExceptionsAndGetContent('/contacts/default/edit'); } return $timeTakenForSave; }
public function testResolveContactToSenderOrRecipientForReceivedEmail() { $super = User::getByUsername('super'); Yii::app()->user->userModel = $super; $message1 = self::$message1; $contact = new Contact(); $contact->firstName = 'Jason'; $contact->lastName = 'Green'; $contact->state = ContactsUtil::getStartingState(); $saved = $contact->save(); $this->assertTrue($saved); $contactId = $contact->id; $contact->forget(); $contact = Contact::getById($contactId); $this->assertNull($contact->primaryEmail->emailAddress); ArchivedEmailMatchingUtil::resolveContactToSenderOrRecipient($message1, $contact); $saved = $message1->save(); $this->assertTrue($saved); $messageId = $message1->id; $message1->forget(); $contact->forget(); RedBeanModel::forgetAll(); //simulates crossing page requests $message1 = EmailMessage::getById($messageId); $contact = Contact::getById($contactId); $this->assertEquals(1, $message1->sender->personsOrAccounts->count()); $castedDownModel = EmailMessageMashableActivityRules::castDownItem($message1->sender->personsOrAccounts[0]); $this->assertEquals('Contact', get_class($castedDownModel)); $this->assertEquals($contact->id, $castedDownModel->id); }
public function actionConvertFinal($id) { assert('!empty($id)'); $accountPostData = LeadsUtil::getFromSession(LeadsUtil::LEAD_CONVERSION_ACCOUNT_DATA_SESSION_KEY); if (empty($accountPostData)) { $urlParams = array('/leads/' . $this->getId() . '/convert', 'id' => $id); $this->redirect($urlParams); } $contact = Contact::getById(intval($id)); if (!LeadsUtil::isStateALead($contact->state)) { $urlParams = array('/contacts/' . $this->getId() . '/details', 'id' => $contact->id); $this->redirect($urlParams); } $convertToAccountSetting = LeadsModule::getConvertToAccountSetting(); $convertToOpportunitySetting = LeadsModule::getConvertToOpportunitySetting(); $opportunity = new Opportunity(); ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($contact); $userCanAccessContacts = RightsUtil::canUserAccessModule('ContactsModule', Yii::app()->user->userModel); $userCanAccessAccounts = RightsUtil::canUserAccessModule('AccountsModule', Yii::app()->user->userModel); $userCanAccessOpportunities = RightsUtil::canUserAccessModule('OpportunitiesModule', Yii::app()->user->userModel); $userCanCreateOpportunity = RightsUtil::doesUserHaveAllowByRightName('OpportunitiesModule', OpportunitiesModule::RIGHT_CREATE_OPPORTUNITIES, Yii::app()->user->userModel); LeadsControllerSecurityUtil::resolveCanUserProperlyConvertLead($userCanAccessContacts, $userCanAccessAccounts, $convertToAccountSetting); LeadsControllerSecurityUtil::resolveCanUserProperlyConvertLeadFinalStep($userCanAccessContacts, $userCanAccessOpportunities, $convertToOpportunitySetting); if (isset($_POST['Opportunity'])) { $controllerUtil = static::getZurmoControllerUtil(); $savedSuccessfully = false; $modelToStringValue = null; $postData = $_POST['Opportunity']; $opportunity = $controllerUtil->saveModelFromPost($postData, $opportunity, $savedSuccessfully, $modelToStringValue, false); if ($savedSuccessfully) { $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($contact); ExplicitReadWriteModelPermissionsUtil::resolveExplicitReadWriteModelPermissions($opportunity, $explicitReadWriteModelPermissions); $account = LeadsUtil::createAccountForLeadConversionFromAccountPostData($accountPostData, $contact, $controllerUtil); $opportunity->account = $account; if (!$opportunity->save()) { throw new NotSupportedException(); } LeadsUtil::removeFromSession(LeadsUtil::LEAD_CONVERSION_ACCOUNT_DATA_SESSION_KEY); $this->actionSaveConvertedContact($contact, $account, $opportunity); } } elseif (isset($_POST['OpportunitySkip']) || $convertToOpportunitySetting == LeadsModule::CONVERT_NO_OPPORTUNITY || $convertToOpportunitySetting == LeadsModule::CONVERT_OPPORTUNITY_NOT_REQUIRED && !$userCanAccessOpportunities) { $controllerUtil = static::getZurmoControllerUtil(); $account = LeadsUtil::createAccountForLeadConversionFromAccountPostData($accountPostData, $contact, $controllerUtil); LeadsUtil::removeFromSession(LeadsUtil::LEAD_CONVERSION_ACCOUNT_DATA_SESSION_KEY); $this->actionSaveConvertedContact($contact, $account, null); } $progressBarAndStepsView = new LeadConversionStepsAndProgressBarForWizardView(1); $convertView = new LeadConvertOpportunityView($this->getId(), $this->getModule()->getId(), $contact->id, strval($contact), $opportunity, $convertToOpportunitySetting, $userCanCreateOpportunity); $view = new LeadsPageView(ZurmoDefaultViewUtil::makeTwoStandardViewsForCurrentUser($this, $progressBarAndStepsView, $convertView)); echo $view->render(); }
/** * @depends testCreateWithRelations */ public function testUpdateWithRelations() { $super = User::getByUsername('super'); Yii::app()->user->userModel = $super; $authenticationData = $this->login(); $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST'); $contact = ContactTestHelper::createContactByNameForOwner('Simon', $super); $opportunity = OpportunityTestHelper::createOpportunityByNameForOwner('My Opportunity', $super); $compareData = $this->getModelToApiDataUtilData($contact); $contact->forget(); $data['modelRelations'] = array('opportunities' => array(array('action' => 'add', 'modelId' => $opportunity->id, 'modelClassName' => 'Opportunity'))); $data['firstName'] = 'Fred'; $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data)); $response = json_decode($response, true); unset($response['data']['modifiedDateTime']); unset($compareData['modifiedDateTime']); $compareData['firstName'] = 'Fred'; $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']); $this->assertEquals($compareData, $response['data']); RedBeanModel::forgetAll(); $contact = Contact::getById($compareData['id']); $this->assertEquals(1, count($contact->opportunities)); $this->assertEquals($opportunity->id, $contact->opportunities[0]->id); $opportunity = Opportunity::getById($opportunity->id); $this->assertEquals(1, count($opportunity->contacts)); $this->assertEquals($contact->id, $opportunity->contacts[0]->id); // Now test remove relations $data['modelRelations'] = array('opportunities' => array(array('action' => 'remove', 'modelId' => $opportunity->id, 'modelClassName' => 'Opportunity'))); $response = $this->createApiCallWithRelativeUrl('update/' . $compareData['id'], 'PUT', $headers, array('data' => $data)); $response = json_decode($response, true); $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']); RedBeanModel::forgetAll(); $contact = Contact::getById($compareData['id']); $this->assertEquals(0, count($contact->opportunities)); $opportunity = Opportunity::getById($opportunity->id); $this->assertEquals(0, count($opportunity->contacts)); }
public function addNewMember($contactId, $unsubscribed = false, $contact = null, $scenario = null) { $member = new MarketingListMember(); if (empty($contact)) { $contact = Contact::getById($contactId); } $member->contact = $contact; $member->unsubscribed = $unsubscribed; $member->marketingList = $this; if (isset($scenario)) { $member->setScenario($scenario); } if ($this->memberAlreadyExists($contact->id)) { return false; } return $member->unrestrictedSave(); }
public function actionCopy($id) { $copyToContact = new Contact(); $postVariableName = get_class($copyToContact); if (!isset($_POST[$postVariableName])) { $contact = Contact::getById((int) $id); ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($contact); ZurmoCopyModelUtil::copy($contact, $copyToContact); } $this->processEdit($copyToContact); }