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);
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     ZurmoDatabaseCompatibilityUtil::dropStoredFunctionsAndProcedures();
     $super = SecurityTestHelper::createSuperAdmin();
     Yii::app()->user->userModel = User::getByUsername('super');
     $headquarters = AccountTestHelper::createAccountByNameForOwner('Headquarters', $super);
     $division1 = AccountTestHelper::createAccountByNameForOwner('Division1', $super);
     $division2 = AccountTestHelper::createAccountByNameForOwner('Division2', $super);
     $ceo = ContactTestHelper::createContactWithAccountByNameForOwner('ceo', $super, $headquarters);
     $div1President = ContactTestHelper::createContactWithAccountByNameForOwner('div1 President', $super, $division1);
     $div2President = ContactTestHelper::createContactWithAccountByNameForOwner('div2 President', $super, $division2);
     $opportunity = OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('big opp', $super, $headquarters);
     $opportunityDiv1 = OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('div1 small opp', $super, $division1);
     $opportunityDiv2 = OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('div2 small opp', $super, $division2);
     //attach divisions to headquarters
     $headquarters->accounts->add($division1);
     $headquarters->accounts->add($division2);
     assert($headquarters->save());
     // Not Coding Standard
     //attach opportunities to contacts
     $opportunity->contacts->add($ceo);
     assert($opportunity->save());
     // Not Coding Standard
     //Forget models to ensure relations are known on the next retrieval
     $headquarters->forget();
     $division1->forget();
     $division2->forget();
     $ceo->forget();
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     AccountTestHelper::createAccountByNameForOwner('superAccount2', $super);
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact', $super, $account);
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact2', $super, $account);
     OpportunityTestHelper::createOpportunityStagesIfDoesNotExist();
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp2', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp3', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp4', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp5', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp6', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp7', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp8', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp9', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp10', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp11', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp12', $super, $account);
     //Setup default dashboard.
     Dashboard::getByLayoutIdAndUser(Dashboard::DEFAULT_USER_LAYOUT_ID, $super);
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     Yii::app()->user->userModel = User::getByUsername('nobody');
     self::$account = AccountTestHelper::createAccountByNameForOwner('superAccount', Yii::app()->user->userModel);
     self::$contact = ContactTestHelper::createContactWithAccountByNameForOwner('superContact', Yii::app()->user->userModel, self::$account);
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $nobody = UserTestHelper::createBasicUser('nobody');
     $nobody->setRight('MarketingListsModule', MarketingListsModule::getAccessRight());
     $saved = $nobody->save();
     static::assertTrue($saved);
     Yii::app()->user->userModel = $nobody;
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('nobodyAccount', $nobody);
     $marketingList1 = MarketingListTestHelper::createMarketingListByName('MarketingList1', 'MarketingList Description1');
     $marketingList2 = MarketingListTestHelper::createMarketingListByName('MarketingList2', 'MarketingList Description2');
     for ($i = 0; $i < 17; $i++) {
         if ($i % 2) {
             $unsubscribed = 0;
         } else {
             $unsubscribed = 1;
         }
         $contact1 = ContactTestHelper::createContactWithAccountByNameForOwner('nobodyContact1' . $i, $nobody, $account);
         $contact2 = ContactTestHelper::createContactWithAccountByNameForOwner('nobodyContact2' . $i, $nobody, $account);
         MarketingListMemberTestHelper::createMarketingListMember($unsubscribed, $marketingList1, $contact1);
         MarketingListMemberTestHelper::createMarketingListMember($unsubscribed, $marketingList2, $contact2);
     }
     AllPermissionsOptimizationUtil::rebuild();
 }
Exemple #6
0
 public function testCreateAndGetMeetingById()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $accounts = Account::getByName('anAccount');
     $contact1 = ContactTestHelper::createContactWithAccountByNameForOwner('superContact', $super, $accounts[0]);
     $contact2 = ContactTestHelper::createContactWithAccountByNameForOwner('superContact2', $super, $accounts[0]);
     $contact3 = ContactTestHelper::createContactWithAccountByNameForOwner('superContact3', $super, $accounts[0]);
     $user = UserTestHelper::createBasicUser('Billy');
     $startStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + 10000);
     $endStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + 11000);
     $meeting = new Meeting();
     $meeting->name = 'MyMeeting';
     $meeting->owner = $user;
     $meeting->location = 'my location';
     $meeting->category->value = 'Call';
     $meeting->startDateTime = $startStamp;
     $meeting->endDateTime = $endStamp;
     $meeting->description = 'my test description';
     $meeting->activityItems->add($accounts[0]);
     $meeting->activityItems->add($contact1);
     $meeting->activityItems->add($contact2);
     $meeting->activityItems->add($contact3);
     $this->assertTrue($meeting->save());
     $id = $meeting->id;
     unset($meeting);
     $meeting = Meeting::getById($id);
     $this->assertEquals('MyMeeting', $meeting->name);
     $this->assertEquals($startStamp, $meeting->startDateTime);
     $this->assertEquals($endStamp, $meeting->endDateTime);
     $this->assertEquals('my test description', $meeting->description);
     $this->assertEquals($user, $meeting->owner);
     $this->assertEquals(4, $meeting->activityItems->count());
     $this->assertEquals($accounts[0], $meeting->activityItems->offsetGet(0));
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     $super = Yii::app()->user->userModel;
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     AccountTestHelper::createAccountByNameForOwner('superAccount2', $super);
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact', $super, $account);
 }
 public function testDownCasts()
 {
     $possibleDerivationPaths = array(array('SecurableItem', 'OwnedSecurableItem', 'Account'), array('SecurableItem', 'OwnedSecurableItem', 'Person', 'Contact'), array('SecurableItem', 'OwnedSecurableItem', 'Opportunity'));
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $account = AccountTestHelper::createAccountByNameForOwner('Waggle', $super);
     $contact = ContactTestHelper::createContactByNameForOwner('Noddy', $super);
     $opportunity = OpportunityTestHelper::createOpportunityByNameForOwner('Noddy', $super);
     $accountItem = Item::getById($account->getClassId('Item'));
     $contactItem = Item::getById($contact->getClassId('Item'));
     $opportunityItem = Item::getById($opportunity->getClassId('Item'));
     $this->assertTrue($accountItem->isSame($account));
     $this->assertTrue($contactItem->isSame($contact));
     $this->assertTrue($opportunityItem->isSame($opportunity));
     $this->assertFalse($accountItem instanceof Account);
     $this->assertFalse($contactItem instanceof Contact);
     $this->assertFalse($opportunityItem instanceof Opportunity);
     $account2 = $accountItem->castDown($possibleDerivationPaths);
     $this->assertEquals('Account', get_class($account2));
     //Demonstrate a single array, making sure it casts down properly.
     $accountItem2 = Item::getById($account->getClassId('Item'));
     $account3 = $accountItem2->castDown(array(array('SecurableItem', 'OwnedSecurableItem', 'Account')));
     $this->assertEquals('Account', get_class($account3));
     $contact2 = $contactItem->castDown($possibleDerivationPaths);
     $opportunity2 = $opportunityItem->castDown($possibleDerivationPaths);
     $this->assertTrue($account2->isSame($account));
     $this->assertTrue($contact2->isSame($contact));
     $this->assertTrue($opportunity2->isSame($opportunity));
     $this->assertTrue($account2 instanceof Account);
     $this->assertTrue($contact2 instanceof Contact);
     $this->assertTrue($opportunity2 instanceof Opportunity);
     $account2 = AccountTestHelper::createAccountByNameForOwner('Waggle2', $super);
     //By adding a second contact with a relation to the account2, we can demonstrate a bug with how castDown works.
     //Since contacts can in fact be attached to accounts via account_id, if a contact exists connected to the account
     //we are trying to cast down, then this will cast down even though it shouldn't.
     $contact2 = ContactTestHelper::createContactWithAccountByNameForOwner('MrWaggle2', $super, $account2);
     try {
         $account2CastedDown = $account2->castDown(array(array('SecurableItem', 'OwnedSecurableItem', 'Person', 'Contact')));
         $this->fail();
     } catch (NotFoundException $e) {
         //success
     }
     //Now try to forget the account and retrieve it.
     $account2Id = $account2->id;
     $account2->forget();
     unset($account2);
     $account2 = Account::getById($account2Id);
     try {
         $account2CastedDown = $account2->castDown(array(array('SecurableItem', 'OwnedSecurableItem', 'Person', 'Contact')));
         $this->fail();
     } catch (NotFoundException $e) {
         //success
     }
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     Currency::makeBaseCurrency();
     //Create a contact for testing.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact', $super, $account);
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     //Setup test data owned by the super user.
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact', $super, $account);
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $account = AccountTestHelper::createAccountByNameForOwner('account', $super);
     static::$contact = ContactTestHelper::createContactWithAccountByNameForOwner('contact', $super, $account);
     static::$marketingList = MarketingListTestHelper::createMarketingListByName('marketingList', 'description', 'fromName', '*****@*****.**', true);
     static::$marketingListMember = MarketingListMemberTestHelper::createMarketingListMember(1, static::$marketingList, static::$contact);
     AllPermissionsOptimizationUtil::rebuild();
 }
 /**
  * Walkthrough test for synchronous download
  */
 public function testDownloadDefaultControllerActions()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     $contacts = array();
     for ($i = 0; $i < 2; $i++) {
         $contacts[] = ContactTestHelper::createContactWithAccountByNameForOwner('superContact' . $i, $super, $account);
     }
     // Check if access is denied if user doesn't have access privileges at all to export actions
     Yii::app()->user->userModel = User::getByUsername('nobody');
     $nobody = $this->logoutCurrentUserLoginNewUserAndGetByUsername('nobody');
     $this->runControllerShouldResultInAccessFailureAndGetContent('contacts/default/list');
     // Check if user have access to module action, but not to export action
     // Now test peon with elevated rights to accounts
     $nobody->setRight('ContactsModule', ContactsModule::RIGHT_ACCESS_CONTACTS);
     $nobody->setRight('ContactsModule', ContactsModule::RIGHT_CREATE_CONTACTS);
     $nobody->setRight('ContactsModule', ContactsModule::RIGHT_DELETE_CONTACTS);
     $nobody->setRight('ExportModule', ExportModule::RIGHT_ACCESS_EXPORT);
     $this->assertTrue($nobody->save());
     // Check if access is denied if user doesn't have access privileges at all to export actions
     $nobody = $this->logoutCurrentUserLoginNewUserAndGetByUsername('nobody');
     Yii::app()->user->userModel = User::getByUsername('nobody');
     $this->runControllerWithNoExceptionsAndGetContent('contacts/default/list');
     $this->setGetArray(array('Contact_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '', 'selectedIds' => ''));
     $response = $this->runControllerWithRedirectExceptionAndGetUrl('contacts/default/export');
     $this->assertTrue(strstr($response, 'contacts/default/index') !== false);
     $this->setGetArray(array('ContactsSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => '', 'fullName' => 'superContact', 'officePhone' => ''), 'multiselect_ContactsSearchForm_anyMixedAttributesScope' => 'All', 'Contact_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '1', 'selectedIds' => ''));
     $response = $this->runControllerWithRedirectExceptionAndGetUrl('contacts/default/export');
     $this->assertTrue(strstr($response, 'contacts/default/index') !== false);
     $this->setGetArray(array('ContactsSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => '', 'fullName' => 'superContact', 'officePhone' => ''), 'multiselect_ContactsSearchForm_anyMixedAttributesScope' => 'All', 'Contact_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '', 'selectedIds' => "{$contacts[0]->id}, {$contacts[1]->id}"));
     $response = $this->runControllerWithRedirectExceptionAndGetUrl('contacts/default/export');
     $this->assertTrue(strstr($response, 'contacts/default/index') !== false);
     $this->assertContains('There is no data to export.', Yii::app()->user->getFlash('notification'));
     //give nobody access to read and write
     Yii::app()->user->userModel = $super;
     foreach ($contacts as $contact) {
         $contact->addPermissions($nobody, Permission::READ_WRITE_CHANGE_PERMISSIONS);
         ReadPermissionsOptimizationUtil::securableItemGivenPermissionsForUser($contact, $nobody);
         $this->assertTrue($contact->save());
     }
     //Now the nobody user should be able to access the edit view and still the details view.
     Yii::app()->user->userModel = $nobody;
     $this->setGetArray(array('ContactsSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => '', 'fullName' => 'superContact', 'officePhone' => ''), 'multiselect_ContactsSearchForm_anyMixedAttributesScope' => 'All', 'Contact_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '1', 'selectedIds' => ''));
     $response = $this->runControllerWithExitExceptionAndGetContent('contacts/default/export');
     $this->assertEquals('Testing download.', $response);
     $this->setGetArray(array('ContactsSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => '', 'fullName' => 'superContact', 'officePhone' => ''), 'multiselect_ContactsSearchForm_anyMixedAttributesScope' => 'All', 'Contact_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '', 'selectedIds' => "{$contacts[0]->id}, {$contacts[1]->id}"));
     $response = $this->runControllerWithExitExceptionAndGetContent('contacts/default/export');
     $this->assertEquals('Testing download.', $response);
     // No mathces
     $this->setGetArray(array('ContactsSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => '', 'fullName' => 'missingName', 'officePhone' => ''), 'multiselect_ContactsSearchForm_anyMixedAttributesScope' => 'All', 'Contact_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '1', 'selectedIds' => ''));
     $response = $this->runControllerWithRedirectExceptionAndGetUrl('contacts/default/export');
     $this->assertTrue(strstr($response, 'contacts/default/index') !== false);
 }
 public function testResolveElementForEditableRender()
 {
     $nullElementInformation = array('attributeName' => null, 'type' => 'Null');
     $super = User::getByUsername('super');
     $betty = User::getByUsername('betty');
     $billy = User::getByUsername('billy');
     $accountForBetty = AccountTestHelper::createAccountByNameForOwner("betty's account", $betty);
     $accountForSuper = AccountTestHelper::createAccountByNameForOwner("super's account", $super);
     $contactForBetty = ContactTestHelper::createContactWithAccountByNameForOwner("betty's contact", $betty, $accountForBetty);
     $contactForBilly = ContactTestHelper::createContactByNameForOwner("betty's contact", $billy);
     $contactForBettyButAccountForSuper = ContactTestHelper::createContactWithAccountByNameForOwner("betty's contact", $betty, $accountForSuper);
     //Testing a non ModelElement.
     $elementInformation = array('attributeName' => 'something', 'type' => 'Text');
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForEditableRender($contactForBetty, $referenceElementInformation, $betty);
     $this->assertEquals($elementInformation, $referenceElementInformation);
     //Testing a AccountElement when Betty cannot access accounts module.
     $elementInformation = array('attributeName' => 'account', 'type' => 'Account');
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForEditableRender($contactForBetty, $referenceElementInformation, $betty);
     $this->assertEquals($nullElementInformation, $referenceElementInformation);
     //Testing ok access for Betty.
     $betty->setRight('AccountsModule', AccountsModule::RIGHT_ACCESS_ACCOUNTS, Right::ALLOW);
     $this->assertTrue($betty->save());
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForEditableRender($contactForBetty, $referenceElementInformation, $betty);
     $this->assertEquals($elementInformation, $referenceElementInformation);
     //Testing where Betty can access the accounts, module, but she cannot view the account.
     $elementInformation = array('attributeName' => 'account', 'type' => 'Account');
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForEditableRender($contactForBettyButAccountForSuper, $referenceElementInformation, $betty);
     $this->assertEquals($nullElementInformation, $referenceElementInformation);
     //Testing where Betty can access the accounts, module, and now can read the super account.
     $accountForSuper->addPermissions($betty, Permission::READ);
     $this->assertTrue($accountForSuper->save());
     AllPermissionsOptimizationUtil::securableItemGivenPermissionsForUser($accountForSuper, $betty);
     $elementInformation = array('attributeName' => 'account', 'type' => 'Account');
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForEditableRender($contactForBettyButAccountForSuper, $referenceElementInformation, $betty);
     $this->assertEquals($elementInformation, $referenceElementInformation);
     //Testing UserElement.
     $elementInformation = array('attributeName' => 'owner', 'type' => 'User');
     //Super can see related user picker without any problem.
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForEditableRender($contactForBetty, $referenceElementInformation, User::getByUsername('super'));
     $this->assertEquals($elementInformation, $referenceElementInformation);
     //Betty can also see related user picker without problem, even though betty has no access to user tab.
     $referenceElementInformation = $elementInformation;
     $this->assertEquals(Right::DENY, $betty->getEffectiveRight('UsersModule', UsersModule::RIGHT_ACCESS_USERS));
     FormLayoutSecurityUtil::resolveElementForEditableRender($contactForBetty, $referenceElementInformation, $betty);
     $this->assertEquals($elementInformation, $referenceElementInformation);
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     SecurityTestHelper::createUsers();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     for ($i = 0; $i < 10; $i++) {
         MarketingListTestHelper::createMarketingListByName('test marketing List ' . $i);
         ContactTestHelper::createContactWithAccountByNameForOwner('superContact' . $i, $super, $account);
     }
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     Currency::makeBaseCurrency();
     //Create a account for testing.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     //Create a opportunity for testing.
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpp', $super, $account);
     //Create a two contacts for testing.
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact1', $super, $account);
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact2', $super, $account);
     //Create a note for testing.
     NoteTestHelper::createNoteWithOwnerAndRelatedAccount('superNote', $super, $account);
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     $super = Yii::app()->user->userModel;
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     AccountTestHelper::createAccountByNameForOwner('superAccount2', $super);
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact', $super, $account);
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact2', $super, $account);
     ContractTestHelper::createContractStagesIfDoesNotExist();
     ContractTestHelper::createContractWithAccountByNameForOwner('superOpp', $super, $account);
     ContractTestHelper::createContractWithAccountByNameForOwner('superOpp2', $super, $account);
     ContractTestHelper::createContractWithAccountByNameForOwner('superOpp3', $super, $account);
     ContractTestHelper::createContractWithAccountByNameForOwner('superOpp4', $super, $account);
     //Setup default dashboard.
     Dashboard::getByLayoutIdAndUser(Dashboard::DEFAULT_USER_LAYOUT_ID, $super);
     AllPermissionsOptimizationUtil::rebuild();
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     //Make sure everyone group is created
     $group = Group::getByName(Group::EVERYONE_GROUP_NAME);
     $group->save();
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact', $super, $account);
     OpportunityTestHelper::createOpportunityWithAccountByNameForOwner('superOpportunity', $super, $account);
     ProductTestHelper::createProductStagesIfDoesNotExist();
     ProductTestHelper::createProductByNameForOwner("My Product 1", $super);
     //Setup test data owned by the super user.
     ProductTemplateTestHelper::createProductTemplateByName('My Product Template');
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     AccountTestHelper::createAccountByNameForOwner('superAccount2', $super);
     ContactTestHelper::createContactWithAccountByNameForOwner('superContact', $super, $account);
     WorkflowTestHelper::createWorkflowModelTestItem('Jason', 'Green');
     $savedWorkflow = new SavedWorkflow();
     $savedWorkflow->name = 'some workflow';
     $savedWorkflow->description = 'description';
     $savedWorkflow->moduleClassName = 'WorkflowsTestModule';
     $savedWorkflow->triggerOn = Workflow::TRIGGER_ON_NEW;
     $savedWorkflow->type = Workflow::TYPE_BY_TIME;
     $savedWorkflow->serializedData = serialize(array(ComponentForWorkflowForm::TYPE_TRIGGERS => array(), ComponentForWorkflowForm::TYPE_ACTIONS => array(), ComponentForWorkflowForm::TYPE_EMAIL_MESSAGES => array()));
     $savedWorkflow->save();
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $emailAccount = EmailAccount::resolveAndGetByUserAndName(Yii::app()->user->userModel);
     //So the email is configured
     $emailAccount->fromAddress = '*****@*****.**';
     $saved = $emailAccount->save();
     assert($saved);
     // Not Coding Standard
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     $contact = ContactTestHelper::createContactWithAccountByNameForOwner('superContact', $super, $account);
     $contact->primaryEmail = new Email();
     $contact->primaryEmail->emailAddress = '*****@*****.**';
     $saved = $contact->save();
     assert($saved);
     // Not Coding Standard
 }
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     SecurityTestHelper::createSuperAdmin();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     $marketingList1 = MarketingListTestHelper::createMarketingListByName('MarketingList1', 'MarketingList Description1');
     $marketingList2 = MarketingListTestHelper::createMarketingListByName('MarketingList2', 'MarketingList Description2');
     for ($i = 0; $i < 17; $i++) {
         if ($i % 2) {
             $unsubscribed = 0;
         } else {
             $unsubscribed = 1;
         }
         $contact1 = ContactTestHelper::createContactWithAccountByNameForOwner('superContact1' . $i, $super, $account);
         $contact2 = ContactTestHelper::createContactWithAccountByNameForOwner('superContact2' . $i, $super, $account);
         MarketingListMemberTestHelper::createMarketingListMember($unsubscribed, $marketingList1, $contact1);
         MarketingListMemberTestHelper::createMarketingListMember($unsubscribed, $marketingList2, $contact2);
         AllPermissionsOptimizationUtil::rebuild();
     }
 }
    public function generateCampaignItemsForDueCampaigns($count)
    {
        $marketingList = MarketingListTestHelper::createMarketingListByName('marketingList Test', 'description goes here', 'fromName', '*****@*****.**');
        $marketingListId = $marketingList->id;
        $contacts = array();
        $emails = array();
        for ($i = 0; $i < $count; $i++) {
            $emails[$i] = new Email();
            $emails[$i]->emailAddress = "demo{$i}@zurmo.com";
            $account = AccountTestHelper::createAccountByNameForOwner('account ' . $i, $this->user);
            $contact = ContactTestHelper::createContactWithAccountByNameForOwner('contact ' . $i, $this->user, $account);
            $contact->primaryEmail = $emails[$i];
            $this->assertTrue($contact->save());
            $contacts[$i] = $contact;
            MarketingListMemberTestHelper::createMarketingListMember(0, $marketingList, $contact);
        }
        $marketingList->forgetAll();
        $marketingList = MarketingList::getById($marketingListId);
        $content = <<<MTG
[[COMPANY^NAME]]
[[CREATED^DATE^TIME]]
[[DEPARTMENT]]
[[DESCRIPTION]]
[[FIRST^NAME]]
[[GOOGLE^WEB^TRACKING^ID]]
[[INDUSTRY]]
[[JOB^TITLE]]
[[LAST^NAME]]
[[LATEST^ACTIVITY^DATE^TIME]]
[[MOBILE^PHONE]]
[[MODIFIED^DATE^TIME]]
[[OFFICE^FAX]]
[[OFFICE^PHONE]]
[[TITLE]]
[[SOURCE]]
[[STATE]]
[[WEBSITE]]
[[MODEL^URL]]
[[BASE^URL]]
[[APPLICATION^NAME]]
[[CURRENT^YEAR]]
[[LAST^YEAR]]
[[OWNERS^AVATAR^SMALL]]
[[OWNERS^AVATAR^MEDIUM]]
[[OWNERS^AVATAR^LARGE]]
[[OWNERS^EMAIL^SIGNATURE]]
[[UNSUBSCRIBE^URL]]
[[MANAGE^SUBSCRIPTIONS^URL]]
[[PRIMARY^EMAIL__EMAIL^ADDRESS]]
[[PRIMARY^EMAIL__EMAIL^ADDRESS]]
[[SECONDARY^ADDRESS__CITY]]
[[SECONDARY^ADDRESS__COUNTRY]]
[[SECONDARY^ADDRESS__INVALID]]
[[SECONDARY^ADDRESS__LATITUDE]]
[[SECONDARY^ADDRESS__LONGITUDE]]
[[SECONDARY^ADDRESS__POSTAL^CODE]]
[[SECONDARY^ADDRESS__STATE]]
[[SECONDARY^ADDRESS__STREET1]]
[[SECONDARY^ADDRESS__STREET2]]
[[OWNER__DEPARTMENT]]
[[OWNER__FIRST^NAME]]
[[OWNER__IS^ACTIVE]]
[[OWNER__MOBILE^PHONE]]
[[OWNER__LAST^LOGIN^DATE^TIME]]
[[OWNER__LAST^NAME]]
[[CREATED^BY^USER__FIRST^NAME]]
[[CREATED^BY^USER__LAST^NAME]]
[[CREATED^BY^USER__MOBILE^PHONE]]
[[CREATED^BY^USER__TITLE]]
[[CREATED^BY^USER__USERNAME]]
[[ACCOUNT__ANNUAL^REVENUE]]
[[ACCOUNT__INDUSTRY]]
[[ACCOUNT__NAME]]
[[ACCOUNT__WEBSITE]]
[[ACCOUNT__BILLING^ADDRESS__COUNTRY]]
[[ACCOUNT__BILLING^ADDRESS__CITY]]
[[ACCOUNT__OWNER__FIRST^NAME]]
 ' " ` " '
MTG;
        $sendOnDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 600);
        $campaign = CampaignTestHelper::createCampaign('campaign Test', 'subject', $content, $content, null, null, null, Campaign::STATUS_ACTIVE, $sendOnDateTime, null, $marketingList, false);
        $fileNames = array('testImage.png', 'testZip.zip', 'testPDF.pdf');
        $files = array();
        foreach ($fileNames as $index => $fileName) {
            $file = ZurmoTestHelper::createFileModel($fileName);
            $files[$index]['name'] = $fileName;
            $files[$index]['type'] = $file->type;
            $files[$index]['size'] = $file->size;
            $files[$index]['contents'] = $file->fileContent->content;
            $campaign->files->add($file);
        }
        $this->assertTrue($campaign->save(false));
        $campaignId = $campaign->id;
        $campaign->forgetAll();
        $campaignItems = CampaignItem::getByProcessedAndCampaignId(0, $campaignId);
        $this->assertEmpty($campaignItems);
        //Process open campaigns.
        Yii::app()->jobQueue->deleteAll();
        AutoresponderOrCampaignBatchSizeConfigUtil::setBatchSize($count);
        Yii::app()->jobQueue->deleteAll();
        $this->assertCount(0, Yii::app()->jobQueue->getAll());
        ForgetAllCacheUtil::forgetAllCaches();
        $job = new CampaignGenerateDueCampaignItemsJob();
        $startedAt = microtime(true);
        $this->assertTrue($job->run());
        $timeTaken = microtime(true) - $startedAt;
        ForgetAllCacheUtil::forgetAllCaches();
        $campaign->forgetAll();
        unset($campaign);
        $campaign = Campaign::getById($campaignId);
        $this->assertNotNull($campaign);
        $this->assertEquals(Campaign::STATUS_PROCESSING, $campaign->status);
        $campaignItems = CampaignItem::getByProcessedAndCampaignId(0, $campaignId);
        $this->assertNotEmpty($campaignItems);
        $this->assertCount($count, $campaignItems);
        return $timeTaken;
    }
 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 testRegularUserActionsWithMarketingListRightAndRequiredPermissions()
 {
     $this->setGetArray(array('id' => static::$regularUserMemberId));
     $this->runControllerWithNoExceptionsAndGetContent('marketingLists/defaultPortlet/toggleUnsubscribed', true);
     $this->runControllerWithNoExceptionsAndGetContent('marketingLists/defaultPortlet/delete', true);
     $this->setGetArray(array('marketingListId' => static::$regularUserMarketingListId));
     $this->runControllerWithNoExceptionsAndGetContent('marketingLists/defaultPortlet/countMembers');
     $type = 'contact';
     $account = AccountTestHelper::createAccountByNameForOwner('account2', $this->user);
     $contact8 = ContactTestHelper::createContactWithAccountByNameForOwner('contact8', $this->user, $account);
     $this->setGetArray(array('marketingListId' => static::$regularUserMarketingListId, 'id' => $contact8->id, 'type' => $type));
     $this->runControllerWithNoExceptionsAndGetContent('marketingLists/defaultPortlet/subscribeContacts');
     //$this->user->setRight('ReportsModule', ReportsModule::getAccessRight());
     $this->user->setRight('ContactsModule', ContactsModule::getAccessRight());
     // or leads. Else PartialRightsForReportSecurityException
     $this->assertTrue($this->user->save());
     $type = 'report';
     $report = SavedReportTestHelper::makeSimpleContactRowsAndColumnsReport();
     $this->setGetArray(array('marketingListId' => static::$regularUserMarketingListId, 'id' => $report->id, 'type' => $type));
     $this->runControllerWithNoExceptionsAndGetContent('marketingLists/defaultPortlet/subscribeContacts');
 }
 public function testWhenRoleIsRequired()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     //Set role as required but without a default value.
     $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName(new AccountContactAffiliation(), 'role');
     $attributeForm->isRequired = true;
     $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData();
     $adapter = new $modelAttributesAdapterClassName(new AccountContactAffiliation());
     try {
         $adapter->setAttributeMetadataFromForm($attributeForm);
     } catch (FailedDatabaseSchemaChangeException $e) {
         echo $e->getMessage();
         $this->fail();
     }
     //Now create an affiliation, the role should be the first value.
     $this->assertEquals(0, count(AccountContactAffiliation::getAll()));
     $account = AccountTestHelper::createAccountByNameForOwner('thirdAccount', $super);
     $contact = ContactTestHelper::createContactWithAccountByNameForOwner('thirdContact', $super, $account);
     $accountContactAffiliations = AccountContactAffiliation::getAll();
     $this->assertEquals(1, count($accountContactAffiliations));
     $this->assertEquals(1, $accountContactAffiliations[0]->primary);
     $this->assertEquals('AAA', $accountContactAffiliations[0]->role->value);
     $this->assertTrue($accountContactAffiliations[0]->account->isSame($account));
     $this->assertTrue($accountContactAffiliations[0]->contact->isSame($contact));
     $this->assertTrue($contact->delete());
     $accountContactAffiliations = AccountContactAffiliation::getAll();
     $this->assertEquals(0, count($accountContactAffiliations));
     //Now add a default value, so the role should be the default value.
     $attributeForm = AttributesFormFactory::createAttributeFormByAttributeName(new AccountContactAffiliation(), 'role');
     $attributeForm->defaultValueOrder = 1;
     $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData();
     $adapter = new $modelAttributesAdapterClassName(new AccountContactAffiliation());
     try {
         $adapter->setAttributeMetadataFromForm($attributeForm);
     } catch (FailedDatabaseSchemaChangeException $e) {
         echo $e->getMessage();
         $this->fail();
     }
     //Now create an account/contact and an affiliation. The role should be BBB
     $this->assertEquals(0, count(AccountContactAffiliation::getAll()));
     $account = AccountTestHelper::createAccountByNameForOwner('fourthAccount', $super);
     $contact = ContactTestHelper::createContactWithAccountByNameForOwner('fourthContact', $super, $account);
     $accountContactAffiliations = AccountContactAffiliation::getAll();
     $this->assertEquals(1, count($accountContactAffiliations));
     $this->assertEquals(1, $accountContactAffiliations[0]->primary);
     $this->assertEquals('BBB', $accountContactAffiliations[0]->role->value);
     $this->assertTrue($accountContactAffiliations[0]->account->isSame($account));
     $this->assertTrue($accountContactAffiliations[0]->contact->isSame($contact));
     $this->assertTrue($contact->delete());
     $accountContactAffiliations = AccountContactAffiliation::getAll();
     $this->assertEquals(0, count($accountContactAffiliations));
 }
 /**
  * Walkthrough test for synchronous download
  */
 public function testAsynchronousDownloadDefaultControllerActions()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount2', $super);
     $notificationsBeforeCount = Notification::getCount();
     $notificationMessagesBeforeCount = NotificationMessage::getCount();
     $contacts = Contact::getAll();
     if (count($contacts)) {
         foreach ($contacts as $contact) {
             $contact->delete();
         }
     }
     $contacts = array();
     for ($i = 0; $i <= ExportModule::$asynchronousThreshold + 1; $i++) {
         $contacts[] = ContactTestHelper::createContactWithAccountByNameForOwner('superContact' . $i, $super, $account);
     }
     $this->setGetArray(array('Contact_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '1', 'selectedIds' => ''));
     $this->runControllerWithRedirectExceptionAndGetUrl('contacts/default/export');
     // Start background job
     $job = new ExportJob();
     $this->assertTrue($job->run());
     $exportItems = ExportItem::getAll();
     $this->assertEquals(1, count($exportItems));
     $fileModel = $exportItems[0]->exportFileModel;
     $this->assertEquals(1, $exportItems[0]->isCompleted);
     $this->assertEquals('csv', $exportItems[0]->exportFileType);
     $this->assertEquals('contacts', $exportItems[0]->exportFileName);
     $this->assertTrue($fileModel instanceof ExportFileModel);
     $this->assertEquals($notificationsBeforeCount + 1, Notification::getCount());
     $this->assertEquals($notificationMessagesBeforeCount + 1, NotificationMessage::getCount());
     // Check export job, when many ids are selected.
     // This will probably never happen, but we need test for this case too.
     $notificationsBeforeCount = Notification::getCount();
     $notificationMessagesBeforeCount = NotificationMessage::getCount();
     // Now test case when multiple ids are selected
     $exportItems = ExportItem::getAll();
     if (count($exportItems)) {
         foreach ($exportItems as $exportItem) {
             $exportItem->delete();
         }
     }
     $selectedIds = "";
     foreach ($contacts as $contact) {
         $selectedIds .= $contact->id . ",";
         // Not Coding Standard
     }
     $this->setGetArray(array('ContactsSearchForm' => array('anyMixedAttributesScope' => array(0 => 'All'), 'anyMixedAttributes' => '', 'fullName' => '', 'officePhone' => ''), 'multiselect_ContactsSearchForm_anyMixedAttributesScope' => 'All', 'Contact_page' => '1', 'export' => '', 'ajax' => '', 'selectAll' => '', 'selectedIds' => "{$selectedIds}"));
     $this->runControllerWithRedirectExceptionAndGetUrl('contacts/default/export');
     // Start background job
     $job = new ExportJob();
     $this->assertTrue($job->run());
     $exportItems = ExportItem::getAll();
     $this->assertEquals(1, count($exportItems));
     $fileModel = $exportItems[0]->exportFileModel;
     $this->assertEquals(1, $exportItems[0]->isCompleted);
     $this->assertEquals('csv', $exportItems[0]->exportFileType);
     $this->assertEquals('contacts', $exportItems[0]->exportFileName);
     $this->assertTrue($fileModel instanceof ExportFileModel);
     $this->assertEquals($notificationsBeforeCount + 1, Notification::getCount());
     $this->assertEquals($notificationMessagesBeforeCount + 1, NotificationMessage::getCount());
 }
    public function generateAndProcessCampaignItems($count)
    {
        $contacts = array();
        $emails = array();
        for ($i = 0; $i < $count; $i++) {
            $emails[$i] = new Email();
            $emails[$i]->emailAddress = "demo{$i}@zurmo.com";
            $account = AccountTestHelper::createAccountByNameForOwner('account ' . $i, $this->user);
            $contact = ContactTestHelper::createContactWithAccountByNameForOwner('contact ' . $i, $this->user, $account);
            $contact->primaryEmail = $emails[$i];
            $this->assertTrue($contact->save());
            $contacts[$i] = $contact;
        }
        $content = <<<MTG
[[COMPANY^NAME]]
[[CREATED^DATE^TIME]]
[[DEPARTMENT]]
[[DESCRIPTION]]
[[FIRST^NAME]]
[[GOOGLE^WEB^TRACKING^ID]]
[[INDUSTRY]]
[[JOB^TITLE]]
[[LAST^NAME]]
[[LATEST^ACTIVITY^DATE^TIME]]
[[MOBILE^PHONE]]
[[MODIFIED^DATE^TIME]]
[[OFFICE^FAX]]
[[OFFICE^PHONE]]
[[TITLE]]
[[SOURCE]]
[[STATE]]
[[WEBSITE]]
[[MODEL^URL]]
[[BASE^URL]]
[[APPLICATION^NAME]]
[[CURRENT^YEAR]]
[[LAST^YEAR]]
[[OWNERS^AVATAR^SMALL]]
[[OWNERS^AVATAR^MEDIUM]]
[[OWNERS^AVATAR^LARGE]]
[[OWNERS^EMAIL^SIGNATURE]]
[[UNSUBSCRIBE^URL]]
[[MANAGE^SUBSCRIPTIONS^URL]]
[[PRIMARY^EMAIL__EMAIL^ADDRESS]]
[[PRIMARY^EMAIL__EMAIL^ADDRESS]]
[[SECONDARY^ADDRESS__CITY]]
[[SECONDARY^ADDRESS__COUNTRY]]
[[SECONDARY^ADDRESS__INVALID]]
[[SECONDARY^ADDRESS__LATITUDE]]
[[SECONDARY^ADDRESS__LONGITUDE]]
[[SECONDARY^ADDRESS__POSTAL^CODE]]
[[SECONDARY^ADDRESS__STATE]]
[[SECONDARY^ADDRESS__STREET1]]
[[SECONDARY^ADDRESS__STREET2]]
[[OWNER__DEPARTMENT]]
[[OWNER__FIRST^NAME]]
[[OWNER__IS^ACTIVE]]
[[OWNER__MOBILE^PHONE]]
[[OWNER__LAST^LOGIN^DATE^TIME]]
[[OWNER__LAST^NAME]]
[[CREATED^BY^USER__FIRST^NAME]]
[[CREATED^BY^USER__LAST^NAME]]
[[CREATED^BY^USER__MOBILE^PHONE]]
[[CREATED^BY^USER__TITLE]]
[[CREATED^BY^USER__USERNAME]]
[[ACCOUNT__ANNUAL^REVENUE]]
[[ACCOUNT__INDUSTRY]]
[[ACCOUNT__NAME]]
[[ACCOUNT__WEBSITE]]
[[ACCOUNT__BILLING^ADDRESS__COUNTRY]]
[[ACCOUNT__BILLING^ADDRESS__CITY]]
[[ACCOUNT__OWNER__FIRST^NAME]]
 ' " ` " '
MTG;
        $marketingList = MarketingListTestHelper::createMarketingListByName('marketingList Test', 'description goes here', 'fromName', '*****@*****.**');
        $campaign = CampaignTestHelper::createCampaign('campaign Test', 'subject', $content, $content, null, null, null, Campaign::STATUS_PROCESSING, null, null, $marketingList, false);
        $fileNames = array('testImage.png', 'testZip.zip', 'testPDF.pdf');
        $files = array();
        foreach ($fileNames as $index => $fileName) {
            $file = ZurmoTestHelper::createFileModel($fileName);
            $files[$index]['name'] = $fileName;
            $files[$index]['type'] = $file->type;
            $files[$index]['size'] = $file->size;
            $files[$index]['contents'] = $file->fileContent->content;
            $campaign->files->add($file);
        }
        $this->assertTrue($campaign->save(false));
        $processed = 0;
        foreach ($contacts as $contact) {
            MarketingListMemberTestHelper::createMarketingListMember(0, $marketingList, $contact);
            CampaignItemTestHelper::createCampaignItem($processed, $campaign, $contact);
        }
        AutoresponderOrCampaignBatchSizeConfigUtil::setBatchSize($count);
        Yii::app()->jobQueue->deleteAll();
        ForgetAllCacheUtil::forgetAllCaches();
        $job = new CampaignQueueMessagesInOutboxJob();
        $this->assertCount(0, Yii::app()->jobQueue->getAll());
        $startedAt = microtime(true);
        $this->assertTrue($job->run());
        $timeTaken = microtime(true) - $startedAt;
        ForgetAllCacheUtil::forgetAllCaches();
        $campaignItemsCountExpected = $count;
        $campaignItemsCountAfter = CampaignItem::getCount();
        $this->assertEquals($campaignItemsCountExpected, $campaignItemsCountAfter);
        $campaignItemsProcessed = CampaignItem::getByProcessedAndCampaignId(1, $campaign->id);
        $this->assertCount($count, $campaignItemsProcessed);
        foreach ($campaignItemsProcessed as $i => $campaignItem) {
            $contact = $contacts[$i];
            $email = $emails[$i];
            $emailMessage = $campaignItem->emailMessage;
            $this->assertEquals($marketingList->owner->id, $emailMessage->owner->id);
            $marketingListPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($marketingList);
            $emailMessagePermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem($emailMessage);
            $this->assertEquals($marketingListPermissions, $emailMessagePermissions);
            $this->assertEquals($campaign->subject, $emailMessage->subject);
            $this->assertNotEquals($campaign->textContent, $emailMessage->content->textContent);
            $this->assertNotEquals($campaign->htmlContent, $emailMessage->content->htmlContent);
            $this->assertEquals(2, substr_count($emailMessage->content->textContent, '/marketingLists/external/'));
            $this->assertContains('/marketingLists/external/', $emailMessage->content->htmlContent);
            $this->assertEquals(2, substr_count($emailMessage->content->htmlContent, '/marketingLists/external/'));
            $this->assertEquals('*****@*****.**', $emailMessage->sender->fromAddress);
            $this->assertEquals('Support Team', $emailMessage->sender->fromName);
            $this->assertEquals(1, $emailMessage->recipients->count());
            $recipients = $emailMessage->recipients;
            $this->assertEquals(strval($contact), $recipients[0]->toName);
            $this->assertEquals($email->emailAddress, $recipients[0]->toAddress);
            $this->assertEquals(EmailMessageRecipient::TYPE_TO, $recipients[0]->type);
            $this->assertNotEmpty($emailMessage->files);
            $this->assertCount(count($files), $emailMessage->files);
            foreach ($campaign->files as $index => $file) {
                $this->assertEquals($file->name, $emailMessage->files[$index]->name);
                $this->assertEquals($file->type, $emailMessage->files[$index]->type);
                $this->assertEquals($file->size, $emailMessage->files[$index]->size);
                //CampaingItem should share the Attachments content from Campaign
                $this->assertEquals($file->fileContent->content, $emailMessage->files[$index]->fileContent->content);
                $this->assertEquals($file->fileContent->id, $emailMessage->files[$index]->fileContent->id);
            }
            $headersArray = array('zurmoItemId' => $campaignItem->id, 'zurmoItemClass' => get_class($campaignItem), 'zurmoPersonId' => $contact->getClassId('Person'));
            $expectedHeaders = serialize($headersArray);
            $this->assertEquals($expectedHeaders, $emailMessage->headers);
        }
        return $timeTaken;
    }
Exemple #27
0
 /**
  * Special method to load each type of email message.  Can help with reviewing user interface scenarios.
  */
 public function actionLoadEmailMessagesSampler()
 {
     if (!Group::isUserASuperAdministrator(Yii::app()->user->userModel)) {
         throw new NotSupportedException();
     }
     $box = EmailBoxUtil::getDefaultEmailBoxByUser(Yii::app()->user->userModel);
     $account = AccountTestHelper::createAccountByNameForOwner('Email Messages Test Account', Yii::app()->user->userModel);
     $contact = ContactTestHelper::createContactWithAccountByNameForOwner('BobMessage', Yii::app()->user->userModel, $account);
     //#1 Create Archived - Sent
     $emailMessage = new EmailMessage();
     $emailMessage->owner = Yii::app()->user->userModel;
     $emailMessage->subject = 'A test archived sent email';
     $emailContent = new EmailMessageContent();
     $emailContent->textContent = 'My First Message';
     $emailContent->htmlContent = 'Some fake HTML content';
     $emailMessage->content = $emailContent;
     //Sending is current user (super)
     $sender = new EmailMessageSender();
     $sender->fromAddress = '*****@*****.**';
     $sender->fromName = 'Super User';
     $sender->personOrAccount = Yii::app()->user->userModel;
     $emailMessage->sender = $sender;
     //Recipient is BobMessage
     $recipient = new EmailMessageRecipient();
     $recipient->toAddress = '*****@*****.**';
     $recipient->toName = strval($contact);
     $recipient->type = EmailMessageRecipient::TYPE_TO;
     $recipient->personOrAccount = $contact;
     $emailMessage->recipients->add($recipient);
     $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_ARCHIVED);
     $emailMessage->sentDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $saved = $emailMessage->save();
     if (!$saved) {
         throw new NotSupportedException();
     }
     //#2 Create Archived - Received
     $emailMessage = new EmailMessage();
     $emailMessage->owner = Yii::app()->user->userModel;
     $emailMessage->subject = 'A test archived received email';
     $emailContent = new EmailMessageContent();
     $emailContent->textContent = 'My Second Message';
     $emailContent->htmlContent = 'Some fake HTML content';
     $emailMessage->content = $emailContent;
     //Sending is current user (super)
     $sender = new EmailMessageSender();
     $sender->fromAddress = '*****@*****.**';
     $sender->fromName = strval($contact);
     $sender->personOrAccount = $contact;
     $emailMessage->sender = $sender;
     //Recipient is BobMessage
     $recipient = new EmailMessageRecipient();
     $recipient->toAddress = '*****@*****.**';
     $recipient->toName = 'Super User';
     $recipient->type = EmailMessageRecipient::TYPE_TO;
     $recipient->personOrAccount = Yii::app()->user->userModel;
     $emailMessage->recipients->add($recipient);
     $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_ARCHIVED);
     $emailMessage->sentDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $saved = $emailMessage->save();
     if (!$saved) {
         throw new NotSupportedException();
     }
     //#3 Sent from Zurmo UI
     $emailMessage = new EmailMessage();
     $emailMessage->owner = Yii::app()->user->userModel;
     $emailMessage->subject = 'A test archived sent email';
     $emailContent = new EmailMessageContent();
     $emailContent->textContent = 'My First Message';
     $emailContent->htmlContent = 'Some fake HTML content';
     $emailMessage->content = $emailContent;
     //Sending is current user (super)
     $sender = new EmailMessageSender();
     $sender->fromAddress = '*****@*****.**';
     $sender->fromName = 'Super User';
     $sender->personOrAccount = Yii::app()->user->userModel;
     $emailMessage->sender = $sender;
     //Recipient is BobMessage
     $recipient = new EmailMessageRecipient();
     $recipient->toAddress = '*****@*****.**';
     $recipient->toName = strval($contact);
     $recipient->type = EmailMessageRecipient::TYPE_TO;
     $recipient->personOrAccount = $contact;
     $emailMessage->recipients->add($recipient);
     $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_SENT);
     $emailMessage->sentDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $saved = $emailMessage->save();
     if (!$saved) {
         throw new NotSupportedException();
     }
     //#4 Received from future Zurmo mail client
     $emailMessage = new EmailMessage();
     $emailMessage->owner = Yii::app()->user->userModel;
     $emailMessage->subject = 'A test archived received email';
     $emailContent = new EmailMessageContent();
     $emailContent->textContent = 'My Second Message';
     $emailContent->htmlContent = 'Some fake HTML content';
     $emailMessage->content = $emailContent;
     //Sending is current user (super)
     $sender = new EmailMessageSender();
     $sender->fromAddress = '*****@*****.**';
     $sender->fromName = strval($contact);
     $sender->personOrAccount = $contact;
     $emailMessage->sender = $sender;
     //Recipient is BobMessage
     $recipient = new EmailMessageRecipient();
     $recipient->toAddress = '*****@*****.**';
     $recipient->toName = 'Super User';
     $recipient->type = EmailMessageRecipient::TYPE_TO;
     $recipient->personOrAccount = Yii::app()->user->userModel;
     $emailMessage->recipients->add($recipient);
     $emailMessage->folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_INBOX);
     $saved = $emailMessage->save();
     if (!$saved) {
         throw new NotSupportedException();
     }
 }
 /**
  * @depends testUnprivilegedUserViewUpdateDeleteContacts
  */
 public function testBasicSearchContacts()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     Contact::deleteAll();
     $authenticationData = $this->login();
     $headers = array('Accept: application/json', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     //Setup test data owned by the super user.
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount', $super);
     $account2 = AccountTestHelper::createAccountByNameForOwner('superAccount2', $super);
     ContactTestHelper::createContactWithAccountByNameForOwner('First Contact', $super, $account);
     ContactTestHelper::createContactWithAccountByNameForOwner('Second Contact', $super, $account);
     ContactTestHelper::createContactWithAccountByNameForOwner('Third Contact', $super, $account);
     ContactTestHelper::createContactWithAccountByNameForOwner('Forth Contact', $super, $account2);
     ContactTestHelper::createContactWithAccountByNameForOwner('Fifth Contact', $super, $account2);
     LeadTestHelper::createLeadWithAccountByNameForOwner('First Lead', $super, $account);
     LeadTestHelper::createLeadWithAccountByNameForOwner('Second Lead', $super, $account2);
     $searchParams = array('pagination' => array('page' => 1, 'pageSize' => 3), 'search' => array('firstName' => ''), 'sort' => 'firstName');
     $searchParamsQuery = http_build_query($searchParams);
     $response = $this->createApiCallWithRelativeUrl('list/filter/' . $searchParamsQuery, 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals(3, count($response['data']['items']));
     $this->assertEquals(5, $response['data']['totalCount']);
     $this->assertEquals(1, $response['data']['currentPage']);
     $this->assertEquals('Fifth Contact', $response['data']['items'][0]['firstName']);
     $this->assertEquals('First Contact', $response['data']['items'][1]['firstName']);
     $this->assertEquals('Forth Contact', $response['data']['items'][2]['firstName']);
     // Second page
     $searchParams['pagination']['page'] = 2;
     $searchParamsQuery = http_build_query($searchParams);
     $response = $this->createApiCallWithRelativeUrl('list/filter/' . $searchParamsQuery, 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals(2, count($response['data']['items']));
     $this->assertEquals(5, $response['data']['totalCount']);
     $this->assertEquals(2, $response['data']['currentPage']);
     $this->assertEquals('Second Contact', $response['data']['items'][0]['firstName']);
     $this->assertEquals('Third Contact', $response['data']['items'][1]['firstName']);
     // Search by name
     $searchParams['pagination']['page'] = 1;
     $searchParams['search']['firstName'] = 'First Contact';
     $searchParamsQuery = http_build_query($searchParams);
     $response = $this->createApiCallWithRelativeUrl('list/filter/' . $searchParamsQuery, 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals(1, count($response['data']['items']));
     $this->assertEquals(1, $response['data']['totalCount']);
     $this->assertEquals(1, $response['data']['currentPage']);
     $this->assertEquals('First Contact', $response['data']['items'][0]['firstName']);
     // No results
     $searchParams['pagination']['page'] = 1;
     $searchParams['search']['firstName'] = 'First Contact 2';
     $searchParamsQuery = http_build_query($searchParams);
     $response = $this->createApiCallWithRelativeUrl('list/filter/' . $searchParamsQuery, 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals(0, $response['data']['totalCount']);
     $this->assertFalse(isset($response['data']['items']));
     // Search by name desc.
     $searchParams = array('pagination' => array('page' => 1, 'pageSize' => 3), 'search' => array('firstName' => ''), 'sort' => 'firstName.desc');
     $searchParamsQuery = http_build_query($searchParams);
     $response = $this->createApiCallWithRelativeUrl('list/filter/' . $searchParamsQuery, 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals(3, count($response['data']['items']));
     $this->assertEquals(5, $response['data']['totalCount']);
     $this->assertEquals(1, $response['data']['currentPage']);
     $this->assertEquals('Third Contact', $response['data']['items'][0]['firstName']);
     $this->assertEquals('Second Contact', $response['data']['items'][1]['firstName']);
     $this->assertEquals('Forth Contact', $response['data']['items'][2]['firstName']);
     // Second page
     $searchParams['pagination']['page'] = 2;
     $searchParamsQuery = http_build_query($searchParams);
     $response = $this->createApiCallWithRelativeUrl('list/filter/' . $searchParamsQuery, 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals(2, count($response['data']['items']));
     $this->assertEquals(5, $response['data']['totalCount']);
     $this->assertEquals(2, $response['data']['currentPage']);
     $this->assertEquals('First Contact', $response['data']['items'][0]['firstName']);
     $this->assertEquals('Fifth Contact', $response['data']['items'][1]['firstName']);
     // Search by custom fields, order by name desc
     $searchParams = array('pagination' => array('page' => 1, 'pageSize' => 3), 'search' => array('account' => array('id' => $account2->id), 'owner' => array('id' => $super->id)), 'sort' => 'firstName.desc');
     $searchParamsQuery = http_build_query($searchParams);
     $response = $this->createApiCallWithRelativeUrl('list/filter/' . $searchParamsQuery, 'GET', $headers);
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals(2, $response['data']['totalCount']);
     $this->assertEquals(2, count($response['data']['items']));
     $this->assertEquals(1, $response['data']['currentPage']);
     $this->assertEquals('Forth Contact', $response['data']['items'][0]['firstName']);
     $this->assertEquals('Fifth Contact', $response['data']['items'][1]['firstName']);
 }
 public function testSubscribeContactsForContactType()
 {
     $type = 'contact';
     $account = AccountTestHelper::createAccountByNameForOwner('superAccount3', $this->user);
     $contact = ContactTestHelper::createContactWithAccountByNameForOwner('superContact6', $this->user, $account);
     $contactId = $contact->id;
     $marketingList = RandomDataUtil::getRandomValueFromArray(MarketingList::getAll());
     $marketingListId = $marketingList->id;
     $this->setGetArray(array('marketingListId' => $marketingListId, 'id' => $contact->id, 'type' => $type));
     $content = $this->runControllerWithNoExceptionsAndGetContent('marketingLists/defaultPortlet/subscribeContacts');
     $contentArray = CJSON::decode($content);
     $this->assertNotEmpty($contentArray);
     $this->assertArrayHasKey('type', $contentArray);
     $this->assertArrayHasKey('message', $contentArray);
     $this->assertEquals('1 subscribed.', $contentArray['message']);
     $this->assertEquals('message', $contentArray['type']);
     $content = $this->runControllerWithNoExceptionsAndGetContent('marketingLists/defaultPortlet/subscribeContacts');
     $contentArray = CJSON::decode($content);
     $this->assertNotEmpty($contentArray);
     $this->assertArrayHasKey('type', $contentArray);
     $this->assertArrayHasKey('message', $contentArray);
     $this->assertEquals('0 subscribed. 1 skipped, already in the list.', $contentArray['message']);
     $this->assertEquals('message', $contentArray['type']);
 }
 public function testGetPersonsAndAccountsByEmailAddress()
 {
     //Create user, contact, lead and accout
     $user = UserTestHelper::createBasicUser('newUser');
     $account = AccountTestHelper::createAccountByNameForOwner('newAccount', $user);
     $lead = LeadTestHelper::createLeadbyNameForOwner('newLead', $user);
     $contact = ContactTestHelper::createContactWithAccountByNameForOwner('newContact', $user, $account);
     $lead->primaryEmail->emailAddress = '*****@*****.**';
     $lead->secondaryEmail->emailAddress = '*****@*****.**';
     $account->primaryEmail->emailAddress = '*****@*****.**';
     $account->secondaryEmail->emailAddress = '*****@*****.**';
     $contact->primaryEmail->emailAddress = '*****@*****.**';
     $contact->secondaryEmail->emailAddress = '*****@*****.**';
     $this->assertTrue($user->save());
     $this->assertTrue($lead->save());
     $this->assertTrue($account->save());
     $this->assertTrue($contact->save());
     //Test with defaults
     $emailAddress = '*****@*****.**';
     $personsOrAccounts = EmailArchivingUtil::getPersonsAndAccountsByEmailAddress($emailAddress);
     $this->assertEmpty($personsOrAccounts);
     $emailAddress = '*****@*****.**';
     $personsOrAccounts = EmailArchivingUtil::getPersonsAndAccountsByEmailAddress($emailAddress);
     $this->assertEmpty($personsOrAccounts);
     $emailAddress = '*****@*****.**';
     $personsOrAccounts = EmailArchivingUtil::getPersonsAndAccountsByEmailAddress($emailAddress);
     $this->assertEmpty($personsOrAccounts);
     $emailAddress = '*****@*****.**';
     $personsOrAccounts = EmailArchivingUtil::getPersonsAndAccountsByEmailAddress($emailAddress);
     $this->assertEmpty($personsOrAccounts);
     //Test user can access contacts
     $emailAddress = '*****@*****.**';
     $personsOrAccounts = EmailArchivingUtil::getPersonsAndAccountsByEmailAddress($emailAddress, true);
     $this->assertNotEmpty($personsOrAccounts);
     $this->assertEquals($personsOrAccounts[0], $contact);
     //Test user can access leads
     $emailAddress = '*****@*****.**';
     $personsOrAccounts = EmailArchivingUtil::getPersonsAndAccountsByEmailAddress($emailAddress, false, true);
     $this->assertNotEmpty($personsOrAccounts);
     $this->assertEquals($personsOrAccounts[0], $lead);
     //Test user can access accounts
     $emailAddress = '*****@*****.**';
     $personsOrAccounts = EmailArchivingUtil::getPersonsAndAccountsByEmailAddress($emailAddress, false, false, true);
     $this->assertNotEmpty($personsOrAccounts);
     $this->assertEquals($personsOrAccounts[0], $account);
     //Test user can access users
     $user->primaryEmail->emailAddress = '*****@*****.**';
     $this->assertTrue($user->save());
     $emailAddress = '*****@*****.**';
     $personsOrAccounts = EmailArchivingUtil::getPersonsAndAccountsByEmailAddress($emailAddress, false, false, false);
     $this->assertNotEmpty($personsOrAccounts);
     $this->assertEquals($personsOrAccounts[0], $user);
 }