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);
 }
 /**
  * Given a contact state id, attempt to get and return a contact state object. If the id is invalid, then an
  * InvalidValueToSanitizeException will be thrown.
  * @param string $modelClassName
  * @param string $attributeName
  * @param mixed $value
  * @param array $mappingRuleData
  */
 public static function sanitizeValue($modelClassName, $attributeName, $value, $mappingRuleData)
 {
     assert('is_string($modelClassName)');
     assert('$attributeName == null');
     assert('$mappingRuleData == null');
     if ($value == null) {
         return $value;
     }
     try {
         if ((int) $value <= 0) {
             $states = ContactState::getByName($value);
             if (count($states) > 1) {
                 throw new InvalidValueToSanitizeException(Zurmo::t('ContactsModule', 'The status specified is not unique and is invalid.'));
             } elseif (count($states) == 0) {
                 throw new NotFoundException();
             }
             $state = $states[0];
         } else {
             $state = ContactState::getById($value);
         }
         $startingState = ContactsUtil::getStartingState();
         if (!static::resolvesValidStateByOrder($state->order, $startingState->order)) {
             throw new InvalidValueToSanitizeException(Zurmo::t('ContactsModule', 'The status specified is invalid.'));
         }
         return $state;
     } catch (NotFoundException $e) {
         throw new InvalidValueToSanitizeException(Zurmo::t('ContactsModule', 'The status specified does not exist.'));
     }
 }
 /**
  * Resolves value for related attribute
  * @param string $attribute
  * @param string $relatedAttribute
  * @return string
  */
 protected function resolveDisplayedValueForRelatedAttribute($attribute, $relatedAttribute)
 {
     if ($this->element instanceof LeadStateDropDownElement) {
         $label = ContactsUtil::resolveStateLabelByLanguage($this->model->{$attribute}, Yii::app()->language);
         return Yii::app()->format->text($label);
     }
     return $this->model->{$attribute}->{$relatedAttribute};
 }
 public function getStateIds()
 {
     $states = ContactState::getAll('order');
     $startingStateOrder = ContactsUtil::getStartingStateOrder($states);
     $stateIds = array();
     foreach ($states as $state) {
         if ($this->shouldIncludeState($state->order, $startingStateOrder)) {
             $stateIds[] = $state->id;
         }
     }
     return $stateIds;
 }
 /**
  * Test when a normal user who can only view records he owns, tries to import records assigned to another user.
  */
 public function testImportSwitchingOwnerButShouldStillCreate()
 {
     $super = User::getByUsername('super');
     $jim = User::getByUsername('jim');
     Yii::app()->user->userModel = $jim;
     //Confirm Jim can can only view ImportModelTestItems he owns.
     $item = NamedSecurableItem::getByName('ContactsModule');
     $this->assertEquals(Permission::NONE, $item->getEffectivePermissions($jim));
     $testModels = Contact::getAll();
     $this->assertEquals(0, count($testModels));
     $import = new Import();
     $serializedData['importRulesType'] = 'Contacts';
     $serializedData['firstRowIsHeaderRow'] = true;
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('importTest.csv', $import->getTempTableName(), true, Yii::getPathOfAlias('application.modules.contacts.tests.unit.files'));
     $this->assertEquals(4, ImportDatabaseUtil::getCount($import->getTempTableName()));
     // includes header rows.
     $ownerColumnMappingData = array('attributeIndexOrDerivedType' => 'owner', 'type' => 'extraColumn', 'mappingRulesData' => array('DefaultModelNameIdMappingRuleForm' => array('defaultModelId' => $super->id), 'UserValueTypeModelAttributeMappingRuleForm' => array('type' => UserValueTypeModelAttributeMappingRuleForm::ZURMO_USER_ID)));
     $startingStateId = ContactsUtil::getStartingState()->id;
     $mappingData = array('column_0' => ImportMappingUtil::makeStringColumnMappingData('firstName'), 'column_1' => ImportMappingUtil::makeStringColumnMappingData('lastName'), 'column_2' => $ownerColumnMappingData, 'column_3' => ContactImportTestHelper::makeStateColumnMappingData($startingStateId, 'extraColumn'));
     $importRules = ImportRulesUtil::makeImportRulesByType('Contacts');
     $page = 0;
     $config = array('pagination' => array('pageSize' => 50));
     //This way all rows are processed.
     $dataProvider = new ImportDataProvider($import->getTempTableName(), true, $config);
     $dataProvider->getPagination()->setCurrentPage($page);
     $importResultsUtil = new ImportResultsUtil($import);
     $messageLogger = new ImportMessageLogger();
     ImportUtil::importByDataProvider($dataProvider, $importRules, $mappingData, $importResultsUtil, new ExplicitReadWriteModelPermissions(), $messageLogger);
     $importResultsUtil->processStatusAndMessagesForEachRow();
     //3 models are created, but Jim can't see them since they are assigned to someone else.
     $testModels = Contact::getAll();
     $this->assertEquals(0, count($testModels));
     //Using super, should see all 3 models created.
     Yii::app()->user->userModel = $super;
     $testModels = Contact::getAll();
     $this->assertEquals(3, count($testModels));
     foreach ($testModels as $model) {
         $this->assertEquals(array(Permission::NONE, Permission::NONE), $model->getExplicitActualPermissions($jim));
     }
     //Confirm 4 rows were processed as 'created'.
     $this->assertEquals(3, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::CREATED));
     //Confirm that 0 rows were processed as 'updated'.
     $this->assertEquals(0, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::UPDATED));
     //Confirm 0 rows were processed as 'errors'.
     $this->assertEquals(0, ImportDatabaseUtil::getCount($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::ERROR));
     $beansWithErrors = ImportDatabaseUtil::getSubset($import->getTempTableName(), "status = " . ImportRowDataResultsUtil::ERROR);
     $this->assertEquals(0, count($beansWithErrors));
     //Clear out data in table
     Contact::deleteAll();
 }
示例#6
0
 public static function createContactWithAccountByNameForOwner($firstName, $owner, $account)
 {
     ContactsModule::loadStartingData();
     $contact = new Contact();
     $contact->firstName = $firstName;
     $contact->lastName = $firstName . 'son';
     $contact->owner = $owner;
     $contact->account = $account;
     $contact->state = ContactsUtil::getStartingState();
     $saved = $contact->save();
     assert('$saved');
     return $contact;
 }
 public function testSuperUserCompleteMatchVariations()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/matchingList');
     $message1 = EmailMessageTestHelper::createArchivedUnmatchedReceivedMessage($super);
     $message2 = EmailMessageTestHelper::createArchivedUnmatchedReceivedMessage($super);
     $message3 = EmailMessageTestHelper::createArchivedUnmatchedReceivedMessage($super);
     $contact = ContactTestHelper::createContactByNameForOwner('gail', $super);
     $startingContactState = ContactsUtil::getStartingState();
     $startingLeadState = LeadsUtil::getStartingState();
     //test validating selecting an existing contact
     $this->setGetArray(array('id' => $message1->id));
     $this->setPostArray(array('ajax' => 'select-contact-form-' . $message1->id, 'AnyContactSelectForm' => array($message1->id => array('contactId' => $contact->id, 'contactName' => 'Some Name'))));
     $this->runControllerWithExitExceptionAndGetContent('emailMessages/default/completeMatch');
     //test validating creating a new contact
     $this->setGetArray(array('id' => $message1->id));
     $this->setPostArray(array('ajax' => 'contact-inline-create-form-' . $message1->id, 'Contact' => array($message1->id => array('firstName' => 'Gail', 'lastName' => 'Green', 'officePhone' => '456765421', 'state' => array('id' => $startingContactState->id)))));
     $this->runControllerWithExitExceptionAndGetContent('emailMessages/default/completeMatch');
     //test validating creating a new lead
     $this->setGetArray(array('id' => $message1->id));
     $this->setPostArray(array('ajax' => 'lead-inline-create-form-' . $message1->id, 'Lead' => array($message1->id => array('firstName' => 'Gail', 'lastName' => 'Green', 'officePhone' => '456765421', 'state' => array('id' => $startingLeadState->id)))));
     $this->runControllerWithExitExceptionAndGetContent('emailMessages/default/completeMatch');
     //test selecting existing contact and saving
     $this->assertNull($contact->primaryEmail->emailAddress);
     $this->setGetArray(array('id' => $message1->id));
     $this->setPostArray(array('AnyContactSelectForm' => array($message1->id => array('contactId' => $contact->id, 'contactName' => 'Some Name'))));
     $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/completeMatch', true);
     $this->assertEquals('bob.message@zurmotest.com', $contact->primaryEmail->emailAddress);
     $this->assertTrue($message1->sender->personOrAccount->isSame($contact));
     $this->assertEquals('Archived', $message1->folder);
     //test creating new contact and saving
     $this->assertEquals(1, Contact::getCount());
     $this->setGetArray(array('id' => $message2->id));
     $this->setPostArray(array('Contact' => array($message2->id => array('firstName' => 'George', 'lastName' => 'Patton', 'officePhone' => '456765421', 'state' => array('id' => $startingContactState->id)))));
     $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/completeMatch', true);
     $this->assertEquals(2, Contact::getCount());
     $contacts = Contact::getByName('George Patton');
     $contact = $contacts[0];
     $this->assertTrue($message2->sender->personOrAccount->isSame($contact));
     $this->assertEquals('Archived', $message2->folder);
     //test creating new lead and saving
     $this->assertEquals(2, Contact::getCount());
     $this->setGetArray(array('id' => $message3->id));
     $this->setPostArray(array('Lead' => array($message3->id => array('firstName' => 'Billy', 'lastName' => 'Kid', 'officePhone' => '456765421', 'state' => array('id' => $startingLeadState->id)))));
     $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/completeMatch', true);
     $this->assertEquals(3, Contact::getCount());
     $contacts = Contact::getByName('Billy Kid');
     $contact = $contacts[0];
     $this->assertTrue($message3->sender->personOrAccount->isSame($contact));
     $this->assertEquals('Archived', $message3->folder);
 }
 /**
  * @depends testGetContactState
  */
 public function testListContactStates()
 {
     $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');
     $contactStates = ContactsUtil::getContactStateDataFromStartingStateLabelByLanguage(Yii::app()->language);
     $compareData = array();
     foreach ($contactStates as $contactState) {
         $compareData[] = $this->getModelToApiDataUtilData($contactState);
     }
     $response = $this->createApiCallWithRelativeUrl('listContactStates/', 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals(count($compareData), count($response['data']['items']));
     $this->assertEquals(count($compareData), $response['data']['totalCount']);
     $this->assertEquals(1, $response['data']['currentPage']);
     $this->assertEquals($compareData, $response['data']['items']);
 }
 /**
  * Special method to load contacts for marketing functional test.
  */
 public function actionLoadContactsSampler()
 {
     if (!Group::isUserASuperAdministrator(Yii::app()->user->userModel)) {
         throw new NotSupportedException();
     }
     //Load 12 contacts so there is sufficient data for marketing list pagination testing and mass delete.
     for ($i = 1; $i <= 12; $i++) {
         $firstName = 'Test';
         $lastName = 'Contact';
         $owner = Yii::app()->user->userModel;
         $contact = new Contact();
         $contact->firstName = $firstName;
         $contact->lastName = $lastName . ' ' . $i;
         $contact->owner = $owner;
         $contact->state = ContactsUtil::getStartingState();
         $saved = $contact->save();
         assert('$saved');
         if (!$saved) {
             throw new NotSupportedException();
         }
     }
 }
 protected function resolveStates()
 {
     return ContactsUtil::getContactStateDataFromStartingStateOnAndKeyedById();
 }
 public function actionCreateFromRelation($relationAttributeName, $relationModelId, $relationModuleId, $redirectUrl)
 {
     $contact = $this->resolveNewModelByRelationInformation(new Contact(), $relationAttributeName, (int) $relationModelId, $relationModuleId);
     ContactsUtil::resolveAddressesFromRelatedAccount($contact);
     $this->actionCreateByModel($contact, $redirectUrl);
 }
 public function testSuperUserCompleteMatchVariations()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/matchingList');
     $message1 = EmailMessageTestHelper::createArchivedUnmatchedReceivedMessage($super);
     $message1Id = $message1->id;
     $message2 = EmailMessageTestHelper::createArchivedUnmatchedReceivedMessage($super);
     $message2Id = $message2->id;
     $message3 = EmailMessageTestHelper::createArchivedUnmatchedReceivedMessage($super);
     $contact = ContactTestHelper::createContactByNameForOwner('gail', $super);
     $startingContactState = ContactsUtil::getStartingState();
     $startingLeadState = LeadsUtil::getStartingState();
     //test validating selecting an existing contact
     $this->setGetArray(array('id' => $message1->id));
     $this->setPostArray(array('ajax' => 'select-contact-form-' . $message1->id, 'AnyContactSelectForm' => array($message1->id => array('contactId' => $contact->id, 'contactName' => 'Some Name'))));
     $this->runControllerWithExitExceptionAndGetContent('emailMessages/default/completeMatch');
     //test validating creating a new contact
     $this->setGetArray(array('id' => $message1->id));
     $this->setPostArray(array('ajax' => 'contact-inline-create-form-' . $message1->id, 'Contact' => array($message1->id => array('firstName' => 'Gail', 'lastName' => 'Green', 'officePhone' => '456765421', 'state' => array('id' => $startingContactState->id)))));
     $this->runControllerWithExitExceptionAndGetContent('emailMessages/default/completeMatch');
     //test validating creating a new lead
     $this->setGetArray(array('id' => $message1->id));
     $this->setPostArray(array('ajax' => 'lead-inline-create-form-' . $message1->id, 'Lead' => array($message1->id => array('firstName' => 'Gail', 'lastName' => 'Green', 'officePhone' => '456765421', 'state' => array('id' => $startingLeadState->id)))));
     $this->runControllerWithExitExceptionAndGetContent('emailMessages/default/completeMatch');
     //test selecting existing contact and saving
     $this->assertNull($contact->primaryEmail->emailAddress);
     $this->setGetArray(array('id' => $message1->id));
     $this->setPostArray(array('AnyContactSelectForm' => array($message1->id => array('contactId' => $contact->id, 'contactName' => 'Some Name'))));
     $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/completeMatch', true);
     $message1->forget();
     $message1 = EmailMessage::getById($message1Id);
     $this->assertNull($contact->primaryEmail->emailAddress);
     $this->assertCount(1, $message1->sender->personsOrAccounts);
     $this->assertTrue($message1->sender->personsOrAccounts[0]->isSame($contact));
     $this->assertEquals('Archived', $message1->folder);
     //assert subject of the email going to edit.
     $this->setGetArray(array('id' => $contact->id));
     $this->runControllerWithNoExceptionsAndGetContent('contacts/default/details');
     $this->assertEquals('A test unmatched archived received email', $message1->subject);
     //edit subject of email message.
     $this->setGetArray(array('id' => $message1->id));
     $createEmailMessageFormData = array('subject' => 'A test unmatched archived received email edited');
     $this->setPostArray(array('ajax' => 'edit-form', 'EmailMessage' => $createEmailMessageFormData));
     $this->runControllerWithRedirectExceptionAndGetUrl('emailMessages/default/edit');
     //assert subject is edited or not.
     $this->setGetArray(array('id' => $contact->id));
     $this->runControllerWithNoExceptionsAndGetContent('contacts/default/details');
     $this->assertEquals('A test unmatched archived received email edited', $message1->subject);
     //delete email message.
     $this->setGetArray(array('id' => $message1->id));
     $this->runControllerWithRedirectExceptionAndGetUrl('emailMessages/default/delete', true);
     //assert subject not present.
     try {
         EmailMessage::getById($message1->id);
         $this->fail();
     } catch (NotFoundException $e) {
         //success
     }
     //Test the default permission was setted
     $everyoneGroup = Group::getByName(Group::EVERYONE_GROUP_NAME);
     $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($message1);
     $readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
     $this->assertEquals($everyoneGroup, $readWritePermitables[$everyoneGroup->getClassId('Permitable')]);
     //test creating new contact and saving
     $this->assertEquals(1, Contact::getCount());
     $this->setGetArray(array('id' => $message2->id));
     $this->setPostArray(array('Contact' => array($message2->id => array('firstName' => 'George', 'lastName' => 'Patton', 'officePhone' => '456765421', 'state' => array('id' => $startingContactState->id)))));
     $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/completeMatch', true);
     $message2->forget();
     $message2 = EmailMessage::getById($message2Id);
     $this->assertEquals(2, Contact::getCount());
     $contacts = Contact::getByName('George Patton');
     $contact = $contacts[0];
     $this->assertCount(1, $message2->sender->personsOrAccounts);
     $this->assertTrue($message2->sender->personsOrAccounts[0]->isSame($contact));
     $this->assertEquals('Archived', $message2->folder);
     //Test the default permission was setted
     $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($message2);
     $readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
     $this->assertEquals($everyoneGroup, $readWritePermitables[$everyoneGroup->getClassId('Permitable')]);
     //test creating new lead and saving
     $this->assertEquals(2, Contact::getCount());
     $this->setGetArray(array('id' => $message3->id));
     $this->setPostArray(array('Lead' => array($message3->id => array('firstName' => 'Billy', 'lastName' => 'Kid', 'officePhone' => '456765421', 'state' => array('id' => $startingLeadState->id)))));
     $this->runControllerWithNoExceptionsAndGetContent('emailMessages/default/completeMatch', true);
     $this->assertEquals(3, Contact::getCount());
     $contacts = Contact::getByName('Billy Kid');
     $contact = $contacts[0];
     $this->assertCount(1, $message3->sender->personsOrAccounts);
     $this->assertTrue($message3->sender->personsOrAccounts[0]->isSame($contact));
     $this->assertEquals('Archived', $message3->folder);
     //Test the default permission was setted
     $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($message3);
     $readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
     $this->assertEquals($everyoneGroup, $readWritePermitables[$everyoneGroup->getClassId('Permitable')]);
 }
 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;
 }
 /**
  * @depends testLayoutsLoadOkAfterCustomFieldsPlacedForContactsModule
  */
 public function testSuperUserModifyContactStatesDefaultValueItemsInDropDown()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     //test existing ContactState changes to labels.
     $extraPostData = array('startingStateOrder' => '4', 'isAudited' => '1', 'isRequired' => '1', 'contactStatesData' => array('New', 'In ProgressD', 'RecycledC', 'QualifiedA', 'CustomerF', 'YRE'), 'contactStatesDataExistingValues' => array('New', 'In Progress', 'Recycled', 'Qualified', 'Customer', 'YRE'));
     $this->createCustomAttributeWalkthroughSequence('ContactsModule', 'state', 'ContactState', $extraPostData, 'state');
     $compareData = array('New', 'In ProgressD', 'RecycledC', 'QualifiedA', 'CustomerF', 'YRE');
     $this->assertEquals($compareData, ContactsUtil::getContactStateDataKeyedByOrder());
     //todo: test that the changed labels, updated the existing data if any existed.
     //Removing ContactStates items
     $extraPostData = array('startingStateOrder' => '2', 'isAudited' => '1', 'isRequired' => '1', 'contactStatesData' => array('New', 'RecycledC', 'QualifiedA'));
     $this->createCustomAttributeWalkthroughSequence('ContactsModule', 'state', 'ContactState', $extraPostData, 'state');
     $compareData = array('New', 'RecycledC', 'QualifiedA');
     $this->assertEquals($compareData, ContactsUtil::getContactStateDataKeyedByOrder());
     //Adding ContactStates items
     $extraPostData = array('startingStateOrder' => '2', 'isAudited' => '1', 'isRequired' => '1', 'contactStatesData' => array('New', 'RecycledC', 'QualifiedA', 'NewItem', 'NewItem2'));
     $this->createCustomAttributeWalkthroughSequence('ContactsModule', 'state', 'ContactState', $extraPostData, 'state');
     $compareData = array('New', 'RecycledC', 'QualifiedA', 'NewItem', 'NewItem2');
     $this->assertEquals($compareData, ContactsUtil::getContactStateDataKeyedByOrder());
     //Changing order of ContactStates items
     $extraPostData = array('startingStateOrder' => '2', 'isAudited' => '1', 'isRequired' => '1', 'contactStatesData' => array('New', 'NewItem2', 'RecycledC', 'QualifiedA', 'NewItem'));
     $this->createCustomAttributeWalkthroughSequence('ContactsModule', 'state', 'ContactState', $extraPostData, 'state');
     $compareData = array('New', 'NewItem2', 'RecycledC', 'QualifiedA', 'NewItem');
     $this->assertEquals($compareData, ContactsUtil::getContactStateDataKeyedByOrder());
     //test trying to save 2 ContactStates with the same name (QualifiedA is twice)
     $extraPostData = array('startingStateOrder' => '2', 'isAudited' => '1', 'isRequired' => '1', 'contactStatesData' => array('New', 'NewItem2', 'QualifiedA', 'QualifiedA', 'NewItem'));
     $this->setGetArray(array('moduleClassName' => 'ContactsModule', 'attributeTypeName' => 'ContactState', 'attributeName' => 'state'));
     $this->setPostArray(array('ajax' => 'edit-form', 'ContactStateAttributeForm' => array_merge(array('attributeLabels' => $this->createAttributeLabelGoodValidationPostData('state'), 'attributeName' => 'state'), $extraPostData)));
     $content = $this->runControllerWithExitExceptionAndGetContent('designer/default/attributeEdit');
     $this->assertTrue(strlen($content) > 50);
     //approximate, but should definetely be larger than 50.
     //test trying to save 0 ContactStates
     $extraPostData = array('startingStateOrder' => '2', 'isAudited' => '1', 'isRequired' => '1', 'contactStatesData' => array());
     $this->setPostArray(array('ajax' => 'edit-form', 'ContactStateAttributeForm' => array_merge(array('attributeLabels' => $this->createAttributeLabelGoodValidationPostData('state'), 'attributeName' => 'state'), $extraPostData)));
     $content = $this->runControllerWithExitExceptionAndGetContent('designer/default/attributeEdit');
     $this->assertTrue(strlen($content) > 50);
     //approximate, but should definetely be larger than 50.
     //test trying to save contact states that are shorter than the minimum length.
     $extraPostData = array('startingStateOrder' => '2', 'isAudited' => '1', 'isRequired' => '1', 'contactStatesData' => array('NA', ' NB', 'NC'));
     $this->setPostArray(array('ajax' => 'edit-form', 'ContactStateAttributeForm' => array_merge(array('attributeLabels' => $this->createAttributeLabelGoodValidationPostData('state'), 'attributeName' => 'state'), $extraPostData)));
     $content = $this->runControllerWithExitExceptionAndGetContent('designer/default/attributeEdit');
     $this->assertTrue(strlen($content) > 50);
     //approximate, but should definetely be larger than 50.
 }
示例#15
0
 protected function afterDelete()
 {
     parent::afterDelete();
     ContactsUtil::resolveMarketingListMembersByContact($this);
 }
 public function actionModalListAllContacts()
 {
     $modalListLinkProvider = new SelectFromRelatedEditModalListLinkProvider($_GET['modalTransferInformation']['sourceIdFieldId'], $_GET['modalTransferInformation']['sourceNameFieldId'], $_GET['modalTransferInformation']['modalId']);
     $adapterName = ContactsUtil::resolveContactStateAdapterByModulesUserHasAccessTo('LeadsModule', 'ContactsModule', Yii::app()->user->userModel);
     if ($adapterName === false) {
         $messageView = new AccessFailureView();
         $view = new AccessFailurePageView($messageView);
         echo $view->render();
         Yii::app()->end(0, false);
     }
     echo ModalSearchListControllerUtil::setAjaxModeAndRenderModalSearchList($this, $modalListLinkProvider, $adapterName);
 }
 public function setAttributeMetadataFromForm(AttributeForm $attributeForm)
 {
     $modelClassName = get_class($this->model);
     $attributeName = $attributeForm->attributeName;
     $attributeLabels = $attributeForm->attributeLabels;
     $elementType = $attributeForm->getAttributeTypeName();
     $isRequired = (bool) $attributeForm->isRequired;
     $isAudited = (bool) $attributeForm->isAudited;
     $contactStatesData = $attributeForm->contactStatesData;
     $contactStatesLabels = $attributeForm->contactStatesLabels;
     $startingStateOrder = (int) $attributeForm->startingStateOrder;
     $contactStatesDataExistingValues = $attributeForm->contactStatesDataExistingValues;
     if ($contactStatesDataExistingValues == null) {
         $contactStatesDataExistingValues = array();
     }
     if ($attributeForm instanceof ContactStateAttributeForm) {
         //update order on existing states.
         //delete removed states
         $states = ContactState::getAll('order');
         $stateNames = array();
         foreach ($states as $state) {
             if (in_array($state->name, $contactStatesData)) {
                 $stateNames[] = $state->name;
                 $state->order = array_search($state->name, $contactStatesData);
                 $state->serializedLabels = $this->makeSerializedLabelsByLabelsAndOrder($contactStatesLabels, (int) $state->order);
                 $saved = $state->save();
                 assert('$saved');
             } elseif (in_array($state->name, $contactStatesDataExistingValues)) {
                 $order = array_search($state->name, $contactStatesDataExistingValues);
                 $state->name = $contactStatesData[$order];
                 $state->order = $order;
                 $state->serializedLabels = $this->makeSerializedLabelsByLabelsAndOrder($contactStatesLabels, (int) $state->order);
                 $saved = $state->save();
                 assert('$saved');
                 $stateNames[] = $state->name;
             } else {
                 $stateNames[] = $state->name;
                 $state->delete();
             }
         }
         //add new states with correct order.
         foreach ($contactStatesData as $order => $name) {
             if (!in_array($name, $stateNames)) {
                 $state = new ContactState();
                 $state->name = $name;
                 $state->order = $order;
                 $state->serializedLabels = $this->makeSerializedLabelsByLabelsAndOrder($contactStatesLabels, (int) $order);
                 $saved = $state->save();
                 assert('$saved');
             }
         }
         //Set starting state by order.
         ContactsUtil::setStartingStateByOrder($startingStateOrder);
         ModelMetadataUtil::addOrUpdateRelation($modelClassName, $attributeName, $attributeLabels, $elementType, $isRequired, $isAudited, 'ContactState');
     } else {
         throw new NotSupportedException();
     }
 }
 /**
  * @depends testSuperUserCreateAction
  */
 public function testSuperUserConvertAction()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $startingLeadState = LeadsUtil::getStartingState();
     $startingContactState = ContactsUtil::getStartingState();
     $leads = Contact::getByName('myNewLead myNewLeadson');
     $this->assertEquals(1, count($leads));
     $lead = $leads[0];
     $this->assertTrue($lead->state == $startingLeadState);
     //Test just going to the convert page.
     $this->setGetArray(array('id' => $lead->id));
     $this->resetPostArray();
     //Test trying to convert by skipping account creation
     $this->runControllerWithNoExceptionsAndGetContent('leads/default/convert');
     $this->setGetArray(array('id' => $lead->id));
     $this->setPostArray(array('AccountSkip' => 'Not Used'));
     $this->runControllerWithRedirectExceptionAndGetContent('leads/default/convert');
     $leadId = $lead->id;
     $lead->forget();
     $contact = Contact::getById($leadId);
     $this->assertTrue($contact->state == $startingContactState);
     //Test trying to convert by creating a new account.
     $lead5 = LeadTestHelper::createLeadbyNameForOwner('superLead5', $super);
     $this->assertTrue($lead5->state == $startingLeadState);
     $this->setGetArray(array('id' => $lead5->id));
     $this->setPostArray(array('Account' => array('name' => 'someAccountName')));
     $this->assertEquals(0, count(Account::getAll()));
     $this->runControllerWithRedirectExceptionAndGetContent('leads/default/convert');
     $this->assertEquals(1, count(Account::getAll()));
     $lead5Id = $lead5->id;
     $lead5->forget();
     $contact5 = Contact::getById($lead5Id);
     $this->assertTrue($contact5->state == $startingContactState);
     $this->assertEquals('someAccountName', $contact5->account->name);
     //Test trying to convert by selecting an existing account
     $account = AccountTestHelper::createAccountbyNameForOwner('someNewAccount', $super);
     $lead6 = LeadTestHelper::createLeadbyNameForOwner('superLead6', $super);
     $this->assertTrue($lead6->state == $startingLeadState);
     $this->setGetArray(array('id' => $lead6->id));
     $this->setPostArray(array('AccountSelectForm' => array('accountId' => $account->id, 'accountName' => 'someNewAccount')));
     $this->assertEquals(2, count(Account::getAll()));
     $this->runControllerWithRedirectExceptionAndGetContent('leads/default/convert');
     $this->assertEquals(2, count(Account::getAll()));
     $lead6Id = $lead6->id;
     $lead6->forget();
     $contact6 = Contact::getById($lead6Id);
     $this->assertTrue($contact6->state == $startingContactState);
     $this->assertEquals($account, $contact6->account);
 }
 /**
  * Get states by type.
  * @param string $state
  * @throws ApiException
  */
 protected function sendStatesByLeadOrContact($state = 'contact')
 {
     try {
         $states = array();
         if ($state == 'contact') {
             $states = ContactsUtil::getContactStateDataFromStartingStateLabelByLanguage(Yii::app()->language);
         } elseif ($state == 'lead') {
             $states = LeadsUtil::getLeadStateDataFromStartingStateLabelByLanguage(Yii::app()->language);
         }
         foreach ($states as $model) {
             $data['items'][] = static::getModelToApiDataUtilData($model);
         }
         $data['totalCount'] = count($data['items']);
         $data['currentPage'] = 1;
         $result = new ApiResult(ApiResponse::STATUS_SUCCESS, $data, null, null);
         Yii::app()->apiHelper->sendResponse($result);
     } catch (Exception $e) {
         $message = $e->getMessage();
         throw new ApiException($message);
     }
 }
 public function testProcessAfterSaveWhenSendIsImmediateAndToAContactThatIsRelatedToTheTriggeredModel()
 {
     foreach (EmailMessage::getAll() as $emailMessage) {
         $emailMessage->delete();
     }
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Yii::app()->emailHelper->getSentCount());
     $emailTemplate = new EmailTemplate();
     $emailTemplate->name = 'the name';
     $emailTemplate->modelClassName = 'Account';
     $emailTemplate->textContent = 'some content';
     $emailTemplate->type = 2;
     $emailTemplate->subject = 'subject';
     $saved = $emailTemplate->save();
     $this->assertTrue($saved);
     $workflow = new Workflow();
     $workflow->setId(self::$savedWorkflow->id);
     $workflow->type = Workflow::TYPE_ON_SAVE;
     $emailMessageForm = new EmailMessageForWorkflowForm('Account', Workflow::TYPE_ON_SAVE);
     $emailMessageForm->sendAfterDurationSeconds = 0;
     $emailMessageForm->emailTemplateId = $emailTemplate->id;
     $emailMessageForm->sendFromType = EmailMessageForWorkflowForm::SEND_FROM_TYPE_DEFAULT;
     $recipients = array(array('type' => WorkflowEmailMessageRecipientForm::TYPE_DYNAMIC_TRIGGERED_MODEL_RELATION, 'audienceType' => EmailMessageRecipient::TYPE_TO, 'relation' => 'contacts'));
     $emailMessageForm->setAttributes(array(EmailMessageForWorkflowForm::EMAIL_MESSAGE_RECIPIENTS => $recipients));
     $workflow->addEmailMessage($emailMessageForm);
     $model = new Account();
     $model->name = 'the account';
     $contact = new Contact();
     $contact->firstName = 'Jason';
     $contact->lastName = 'Blue';
     $contact->state = ContactsUtil::getStartingState();
     $contact->primaryEmail->emailAddress = 'jason@something.com';
     $this->assertTrue($contact->save());
     $contact2 = new Contact();
     $contact2->firstName = 'Laura';
     $contact2->lastName = 'Blue';
     $contact2->state = ContactsUtil::getStartingState();
     $contact2->primaryEmail->emailAddress = 'laura@something.com';
     $this->assertTrue($contact2->save());
     $model->contacts->add($contact);
     $model->contacts->add($contact2);
     $this->assertTrue($model->save());
     WorkflowEmailMessagesUtil::processAfterSave($workflow, $model, Yii::app()->user->userModel);
     $this->assertEquals(1, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Yii::app()->emailHelper->getSentCount());
     $queuedEmailMessages = EmailMessage::getAllByFolderType(EmailFolder::TYPE_OUTBOX);
     $this->assertEquals(1, count($queuedEmailMessages));
     $this->assertEquals(2, count($queuedEmailMessages[0]->recipients));
     $this->assertEquals('Jason Blue', $queuedEmailMessages[0]->recipients[0]->toName);
     $this->assertEquals('jason@something.com', $queuedEmailMessages[0]->recipients[0]->toAddress);
     $this->assertEquals($contact->id, $queuedEmailMessages[0]->recipients[0]->personOrAccount->id);
     $this->assertEquals('Laura Blue', $queuedEmailMessages[0]->recipients[1]->toName);
     $this->assertEquals('laura@something.com', $queuedEmailMessages[0]->recipients[1]->toAddress);
     $this->assertEquals($contact2->id, $queuedEmailMessages[0]->recipients[1]->personOrAccount->id);
 }
 /**
  * Get how many records in the Contact and Lead models have each ContactState selected.
  * During testing, it is possible a contact or lead exists with a contact state id that no longer exists.
  * In that case, it is ignored from the count.
  */
 public function getCollectionCountData()
 {
     $contactStates = ContactsUtil::getContactStateDataKeyedById();
     $stateNameCountData = array();
     $idCountData = GroupedAttributeCountUtil::getCountData('Contact', 'state');
     foreach ($idCountData as $id => $count) {
         if (isset($contactStates[$id])) {
             $stateNameCountData[$contactStates[$id]] = $count;
         }
     }
     return $stateNameCountData;
 }
 public function testMakeRecipientsForDynamicTriggeredModelRelation()
 {
     $form = new DynamicTriggeredModelRelationWorkflowEmailMessageRecipientForm('Account', Workflow::TYPE_ON_SAVE);
     $form->relation = 'contacts';
     $model = new Account();
     $model->name = 'the account';
     $contact = new Contact();
     $contact->firstName = 'Jason';
     $contact->lastName = 'Blue';
     $contact->state = ContactsUtil::getStartingState();
     $contact->primaryEmail->emailAddress = 'jason@something.com';
     $this->assertTrue($contact->save());
     $contact2 = new Contact();
     $contact2->firstName = 'Laura';
     $contact2->lastName = 'Blue';
     $contact2->state = ContactsUtil::getStartingState();
     $contact2->primaryEmail->emailAddress = 'laura@something.com';
     $this->assertTrue($contact2->save());
     $model->contacts->add($contact);
     $model->contacts->add($contact2);
     $this->assertTrue($model->save());
     $recipients = $form->makeRecipients($model, User::getById(self::$bobbyUserId));
     $this->assertEquals(2, count($recipients));
     $this->assertEquals('Jason Blue', $recipients[0]->toName);
     $this->assertEquals('jason@something.com', $recipients[0]->toAddress);
     $this->assertEquals($contact->id, $recipients[0]->personsOrAccounts[0]->id);
     $this->assertEquals('Laura Blue', $recipients[1]->toName);
     $this->assertEquals('laura@something.com', $recipients[1]->toAddress);
     $this->assertEquals($contact2->id, $recipients[1]->personsOrAccounts[0]->id);
 }
 public static function makeActiveCustomerEmailList()
 {
     $contactStateIdsAndNames = ContactsUtil::getContactStateDataFromStartingStateOnAndKeyedById();
     $report = new Report();
     $report->setDescription('A report showing active customers who have not opted out of receiving emails');
     $report->setModuleClassName('ContactsModule');
     $report->setName('Active Customer Email List');
     $report->setType(Report::TYPE_ROWS_AND_COLUMNS);
     $report->setOwner(Yii::app()->user->userModel);
     $report->setFiltersStructure('1 AND 2 AND 3');
     $report->setCurrencyConversionType(Report::CURRENCY_CONVERSION_TYPE_BASE);
     $filter = new FilterForReportForm('ContactsModule', 'Contact', $report->getType());
     $filter->attributeIndexOrDerivedType = 'account___type';
     $filter->value = 'Customer';
     $filter->operator = OperatorRules::TYPE_EQUALS;
     $report->addFilter($filter);
     $filter = new FilterForReportForm('ContactsModule', 'Contact', $report->getType());
     $filter->attributeIndexOrDerivedType = 'state';
     $filter->value = array_keys($contactStateIdsAndNames);
     $filter->operator = OperatorRules::TYPE_ONE_OF;
     $report->addFilter($filter);
     $filter = new FilterForReportForm('ContactsModule', 'Contact', $report->getType());
     $filter->attributeIndexOrDerivedType = 'primaryEmail___optOut';
     $filter->value = false;
     $filter->operator = OperatorRules::TYPE_EQUALS;
     $report->addFilter($filter);
     $displayAttribute = new DisplayAttributeForReportForm('ContactsModule', 'Contact', $report->getType());
     $displayAttribute->attributeIndexOrDerivedType = 'FullName';
     $report->addDisplayAttribute($displayAttribute);
     $displayAttribute = new DisplayAttributeForReportForm('ContactsModule', 'Contact', $report->getType());
     $displayAttribute->attributeIndexOrDerivedType = 'account___name';
     $displayAttribute->label = 'Account Name';
     $report->addDisplayAttribute($displayAttribute);
     $displayAttribute = new DisplayAttributeForReportForm('ContactsModule', 'Contact', $report->getType());
     $displayAttribute->attributeIndexOrDerivedType = 'primaryEmail___emailAddress';
     $report->addDisplayAttribute($displayAttribute);
     $savedReport = new SavedReport();
     SavedReportToReportAdapter::resolveReportToSavedReport($report, $savedReport);
     //set explicit
     $saved = $savedReport->save();
     assert('$saved');
     $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($savedReport);
     $explicitReadWriteModelPermissions->addReadWritePermitable(Group::getByName(Group::EVERYONE_GROUP_NAME));
     $success = ExplicitReadWriteModelPermissionsUtil::resolveExplicitReadWriteModelPermissions($savedReport, $explicitReadWriteModelPermissions);
     assert('$success');
     $saved = $savedReport->save();
     assert('$saved');
 }
 public function testDefaultFullnameOrderOnContacts()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $contact = new Contact();
     $contact->firstName = 'Jackie';
     $contact->lastName = 'Bonn';
     $contact->owner = $super;
     $contact->state = ContactsUtil::getStartingState();
     $this->assertTrue($contact->save());
     $searchAttributeData = array();
     $dataProvider = new RedBeanModelDataProvider('Contact', null, false, $searchAttributeData);
     $data = $dataProvider->getData();
     $contacts = array();
     foreach ($data as $contact) {
         $contacts[] = strval($contact);
     }
     $sortedContacts = $contacts;
     sort($sortedContacts);
     $compareContacts = array('Dino Dinoson', 'Jackie Bonn', 'Jackie Jackieson', 'Jackie Tyler');
     $this->assertEquals($compareContacts, $sortedContacts);
 }
 /**
  * @param User $user
  * @return null | string
  */
 public static function resolveStateAdapterUserHasAccessTo(User $user)
 {
     assert('$user->id > 0');
     return ContactsUtil::resolveContactStateAdapterByModulesUserHasAccessTo('LeadsModule', 'ContactsModule', $user);
 }
 protected function actionSaveConvertedContact($contact, $account = null, $opportunity = null)
 {
     $contact->account = $account;
     if ($opportunity !== null) {
         $contact->opportunities->add($opportunity);
     }
     $contact->state = ContactsUtil::getStartingState();
     if ($contact->save()) {
         Yii::app()->user->setFlash('notification', Zurmo::t('LeadsModule', 'LeadsModuleSingularLabel successfully converted.', LabelUtil::getTranslationParamsForAllModules()));
         $this->redirect(array('/contacts/default/details', 'id' => $contact->id));
     }
     Yii::app()->user->setFlash('notification', Zurmo::t('LeadsModule', 'LeadsModuleSingularLabel was not converted. An error occurred.'));
     $this->redirect(array('default/details', 'id' => $contact->id));
     Yii::app()->end(0, false);
 }
 /**
  * @return array
  */
 protected function getDropDownArray()
 {
     return ContactsUtil::getAllContactStatesDataFromStartingStateKeyedByIdAndLabelByLanguage(Yii::app()->language);
 }
 public static function getStatesBeforeOrStartingWithStartingState($states)
 {
     assert('is_array($states)');
     $startingStateOrder = ContactsUtil::getStartingStateOrder($states);
     $statesAfterStartingState = array();
     foreach ($states as $state) {
         if (static::shouldIncludeState($state->order, $startingStateOrder)) {
             $statesAfterStartingState[] = $state;
         }
     }
     return $statesAfterStartingState;
 }
 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 testCreateWithRelations()
 {
     $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');
     $opportunity = OpportunityTestHelper::createOpportunityByNameForOwner('My Opportunity', $super);
     $data['firstName'] = "Freddy";
     $data['lastName'] = "Smith";
     $data['state']['id'] = ContactsUtil::getStartingState()->id;
     $data['modelRelations'] = array('opportunities' => array(array('action' => 'add', 'modelId' => $opportunity->id, 'modelClassName' => 'Opportunity')));
     $response = $this->createApiCallWithRelativeUrl('create/', 'POST', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals($data['firstName'], $response['data']['firstName']);
     $this->assertEquals($data['lastName'], $response['data']['lastName']);
     RedBeanModel::forgetAll();
     $contact = Contact::getById($response['data']['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);
 }