public static function updateTestAccountsWithBillingAddress($accountid, $address, $owner)
 {
     $account = Account::getById($accountid);
     $account->owner = $owner;
     foreach ($address as $key => $value) {
         $account->billingAddress->{$key} = $value;
     }
     $account->save();
 }
 public function testSuperUserAllDefaultControllerActions()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $superAccountId = self::getModelIdByModelNameAndName('Account', 'superAccount');
     $superAccountId2 = self::getModelIdByModelNameAndName('Account', 'superAccount2');
     $superContactId = self::getModelIdByModelNameAndName('Contact', 'superContact superContactson');
     $account = Account::getById($superAccountId);
     $account2 = Account::getById($superAccountId2);
     $contact = Contact::getById($superContactId);
     //confirm no existing activities exist
     $activities = Activity::getAll();
     $this->assertEquals(0, count($activities));
     //Test just going to the create from relation view.
     $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect'));
     $this->runControllerWithNoExceptionsAndGetContent('tasks/default/modalCreateFromRelation');
     //add related task for account using createFromRelation action
     $activityItemPostData = array('Account' => array('id' => $superAccountId));
     $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect'));
     $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Task' => array('name' => 'myTask')));
     $this->runControllerWithNoExceptionsAndGetContent('tasks/default/modalSaveFromRelation');
     //now test that the new task exists, and is related to the account.
     $tasks = Task::getAll();
     $this->assertEquals(1, count($tasks));
     $this->assertEquals('myTask', $tasks[0]->name);
     $this->assertEquals(1, $tasks[0]->activityItems->count());
     $activityItem1 = $tasks[0]->activityItems->offsetGet(0);
     $this->assertEquals($account, $activityItem1);
     //test viewing the existing task in a details view
     $this->setGetArray(array('id' => $tasks[0]->id));
     $this->resetPostArray();
     $this->runControllerWithNoExceptionsAndGetContent('tasks/default/modalDetails');
     //test submitting the task on change
     $this->setGetArray(array('id' => $tasks[0]->id));
     $this->setPostArray(array('Task' => array('name' => 'myTask', 'status' => Task::STATUS_IN_PROGRESS)));
     $this->runControllerWithNoExceptionsAndGetContent('tasks/default/modalDetails');
     //Test just going to the copy from relation
     $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'id' => $tasks[0]->id));
     $this->runControllerWithNoExceptionsAndGetContent('tasks/default/modalCopyFromRelation');
     $tasks = Task::getAll();
     $this->assertEquals(2, count($tasks));
     $this->assertEquals('myTask', $tasks[1]->name);
     $this->assertEquals(1, $tasks[1]->activityItems->count());
     //test removing a task.
     $this->setGetArray(array('id' => $tasks[0]->id));
     $this->resetPostArray();
     $this->runControllerWithNoExceptionsAndGetContent('tasks/default/delete', true);
     //Confirm no more tasks exist.
     $tasks = Task::getAll();
     $this->assertEquals(1, count($tasks));
 }
 public function testCopy()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $user = Yii::app()->user->userModel;
     $project = new Project();
     $project->name = 'Project 1';
     $project->owner = $user;
     $project->description = 'Description';
     $user = UserTestHelper::createBasicUser('Steven');
     $account = new Account();
     $account->owner = $user;
     $account->name = DataUtil::purifyHtml("Tom & Jerry's Account");
     $this->assertTrue($account->save());
     $id = $account->id;
     unset($account);
     $account = Account::getById($id);
     $this->assertEquals("Tom & Jerry's Account", $account->name);
     $contact = ContactTestHelper::createContactByNameForOwner('Jerry', $user);
     $opportunity = OpportunityTestHelper::createOpportunityByNameForOwner('Jerry Opp', $user);
     $this->assertTrue($project->save());
     $this->assertEquals(1, count($project->auditEvents));
     $id = $project->id;
     $project->forget();
     unset($project);
     $project = Project::getById($id);
     ProjectZurmoControllerUtil::resolveProjectManyManyAccountsFromPost($project, array('accountIds' => $account->id));
     ProjectZurmoControllerUtil::resolveProjectManyManyContactsFromPost($project, array('contactIds' => $contact->id));
     ProjectZurmoControllerUtil::resolveProjectManyManyOpportunitiesFromPost($project, array('opportunityIds' => $opportunity->id));
     $this->assertEquals('Project 1', $project->name);
     $this->assertEquals('Description', $project->description);
     $this->assertEquals(1, $project->accounts->count());
     $this->assertEquals(1, $project->contacts->count());
     $this->assertEquals(1, $project->opportunities->count());
     $task = TaskTestHelper::createTaskByNameWithProjectAndStatus('MyFirstKanbanTask', Yii::app()->user->userModel, $project, Task::STATUS_IN_PROGRESS);
     $kanbanItem1 = KanbanItem::getByTask($task->id);
     $this->assertEquals(KanbanItem::TYPE_IN_PROGRESS, $kanbanItem1->type);
     $this->assertEquals($task->project->id, $kanbanItem1->kanbanRelatedItem->id);
     $copyToProject = new Project();
     ProjectZurmoCopyModelUtil::copy($project, $copyToProject);
     ProjectZurmoCopyModelUtil::processAfterCopy($project, $copyToProject);
     $this->assertTrue($copyToProject->save());
     $this->assertEquals($copyToProject->name, $project->name);
     $this->assertEquals($copyToProject->description, $project->description);
     $this->assertEquals($copyToProject->status, $project->status);
     $project = Project::getByName('Project 1');
     $this->assertEquals(2, count($project));
     $tasks = Task::getAll();
     $this->assertEquals(2, count($tasks));
 }
 public function testCreateAndGetProjectById()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $user = Yii::app()->user->userModel;
     $project = new Project();
     $project->name = 'Project 1';
     $project->owner = $user;
     $project->description = 'Description';
     $user = UserTestHelper::createBasicUser('Steven');
     $account = new Account();
     $account->owner = $user;
     $account->name = DataUtil::purifyHtml("Tom & Jerry's Account");
     $this->assertTrue($account->save());
     $id = $account->id;
     unset($account);
     $account = Account::getById($id);
     $this->assertEquals("Tom & Jerry's Account", $account->name);
     //$project->accounts->add($account);
     $contact = ContactTestHelper::createContactByNameForOwner('Jerry', $user);
     //$project->contacts->add($contact);
     $opportunity = OpportunityTestHelper::createOpportunityByNameForOwner('Jerry Opp', $user);
     //$project->opportunities->add($opportunity);
     $this->assertTrue($project->save());
     $this->assertEquals(1, count($project->auditEvents));
     $id = $project->id;
     $project->forget();
     unset($project);
     $project = Project::getById($id);
     ProjectZurmoControllerUtil::resolveProjectManyManyAccountsFromPost($project, array('accountIds' => $account->id));
     ProjectZurmoControllerUtil::resolveProjectManyManyContactsFromPost($project, array('contactIds' => $contact->id));
     ProjectZurmoControllerUtil::resolveProjectManyManyOpportunitiesFromPost($project, array('opportunityIds' => $opportunity->id));
     $this->assertEquals('Project 1', $project->name);
     $this->assertEquals('Description', $project->description);
     $this->assertEquals(1, $project->accounts->count());
     $this->assertEquals(1, $project->contacts->count());
     $this->assertEquals(1, $project->opportunities->count());
     //Try saving a second project
     $project = new Project();
     $project->name = 'Project 2';
     $project->owner = $user;
     $project->description = 'Description';
     $this->assertTrue($project->save());
     $this->assertEquals(1, count($project->auditEvents));
 }
 /**
  * Resolves the accounts sent via post request
  * @param Project $project
  * @param array $postData
  * @return array containing accounts
  */
 public static function resolveProjectManyManyAccountsFromPost(Project $project, $postData)
 {
     assert('$project instanceof Project');
     $newAccount = array();
     if (isset($postData['accountIds']) && strlen($postData['accountIds']) > 0) {
         $accountIds = explode(",", $postData['accountIds']);
         // Not Coding Standard
         foreach ($accountIds as $accountId) {
             $newAccount[$accountId] = Account::getById((int) $accountId);
         }
         if ($project->accounts->count() > 0) {
             $project->accounts->removeAll();
         }
         //Now add missing accounts
         foreach ($newAccount as $account) {
             $project->accounts->add($account);
         }
     } else {
         //remove all accounts
         $project->accounts->removeAll();
     }
     return $newAccount;
 }
Beispiel #6
0
 /**
  * @depends testCreatingACustomDropDownAfterAnAccountExists
  */
 public function testWebsiteCanBeSavedWithoutUrlScheme()
 {
     $user = User::getByUsername('steven');
     $account = new Account();
     $account->owner = $user;
     $account->name = 'AccountForURLSchemeTest';
     $account->website = 'www.zurmo.com';
     $this->assertTrue($account->save());
     $id = $account->id;
     unset($account);
     $account = Account::getById($id);
     $this->assertEquals('AccountForURLSchemeTest', $account->name);
     $this->assertEquals('http://www.zurmo.com', $account->website);
     $account->setAttributes(array('website' => 'https://www.zurmo.com'));
     $this->assertTrue($account->save());
     $account->forget();
     $account = Account::getById($id);
     $this->assertEquals('https://www.zurmo.com', $account->website);
 }
 /**
  * @depends testResolveElementForEditableRender
  */
 public function testResolveElementForNonEditableRender()
 {
     $betty = User::getByUsername('betty');
     $billy = User::getByUsername('billy');
     $contactForBetty = ContactTestHelper::createContactByNameForOwner("betty's contact2", $betty);
     $contactForBetty->account = AccountTestHelper::createAccountByNameForOwner('BillyCompany', $billy);
     $this->assertTrue($contactForBetty->save());
     $accountId = $contactForBetty->account->id;
     $nullElementInformation = array('attributeName' => null, 'type' => 'Null');
     //test non ModelElement, should pass through without modification.
     $elementInformation = array('attributeName' => 'something', 'type' => 'Text');
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForNonEditableRender($contactForBetty, $referenceElementInformation, $betty);
     $this->assertEquals($elementInformation, $referenceElementInformation);
     //test Acc ModelElement
     //Betty will see a nullified Element because Betty cannot access read the related account
     $elementInformation = array('attributeName' => 'account', 'type' => 'Account');
     $noLinkElementInformation = array('attributeName' => 'account', 'type' => 'Account', 'noLink' => true);
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForNonEditableRender($contactForBetty, $referenceElementInformation, $betty);
     $this->assertEquals($nullElementInformation, $referenceElementInformation);
     $this->assertEquals(Right::ALLOW, $betty->getEffectiveRight('AccountsModule', AccountsModule::RIGHT_ACCESS_ACCOUNTS));
     //Betty can see the account with a link, because she has been added for Permission::READ on the account.
     //and she has access to the accounts tab.
     $account = Account::getById($accountId);
     $account->addPermissions($betty, Permission::READ);
     $this->assertTrue($account->save());
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForNonEditableRender($contactForBetty, $referenceElementInformation, $betty);
     $this->assertEquals($elementInformation, $referenceElementInformation);
     //Removing Betty's access to the accounts tab means she will see the element, but without a link
     $betty->setRight('AccountsModule', AccountsModule::RIGHT_ACCESS_ACCOUNTS, Right::DENY);
     $this->assertTrue($betty->save());
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForNonEditableRender($contactForBetty, $referenceElementInformation, $betty);
     $this->assertEquals($noLinkElementInformation, $referenceElementInformation);
     //Testing UserElement
     $elementInformation = array('attributeName' => 'owner', 'type' => 'User');
     $noLinkElementInformation = array('attributeName' => 'owner', 'type' => 'User', 'noLink' => true);
     //Super can see related user picker link without a problem.
     $referenceElementInformation = $elementInformation;
     FormLayoutSecurityUtil::resolveElementForNonEditableRender($contactForBetty, $referenceElementInformation, User::getByUsername('super'));
     $this->assertEquals($elementInformation, $referenceElementInformation);
     //Betty can also see related user name, but not a link.
     $referenceElementInformation = $elementInformation;
     $this->assertEquals(Right::DENY, $betty->getEffectiveRight('UsersModule', UsersModule::RIGHT_ACCESS_USERS));
     FormLayoutSecurityUtil::resolveElementForNonEditableRender($contactForBetty, $referenceElementInformation, $betty);
     $this->assertEquals($noLinkElementInformation, $referenceElementInformation);
 }
 /**
  * Testing when a user who is not a super user, has a model owned by themselves but not created by themselves.
  * Then that user tries to change the owner to someone else and at the same time change the read/write from
  * owner only to everyone.
  */
 public function testRegularUserChangingOwnershipToEveryoneOnNonCreatedAccount()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $nobody = User::getByUsername('nobody');
     $account = AccountTestHelper::createAccountByNameForOwner('superAccountReadableByNobody', $nobody);
     $nobody = $this->logoutCurrentUserLoginNewUserAndGetByUsername('nobody');
     //First set the read/write as owner only.
     $this->setGetArray(array('id' => $account->id));
     $postData = array('type' => '');
     $this->setPostArray(array('Account' => array('owner' => array('id' => $nobody->id), 'explicitReadWriteModelPermissions' => $postData)));
     //Make sure the redirect is to the details view and not the list view.
     $this->runControllerWithRedirectExceptionAndGetContent('accounts/default/edit');
     // Not Coding Standard
     $accountId = $account->id;
     $account->forget();
     $account = Account::getById($accountId);
     $this->setGetArray(array('id' => $account->id));
     $postData = array('type' => ExplicitReadWriteModelPermissionsUtil::MIXED_TYPE_EVERYONE_GROUP);
     $this->setPostArray(array('Account' => array('owner' => array('id' => $super->id), 'explicitReadWriteModelPermissions' => $postData)));
     //Make sure the redirect is to the details view and not the list view.
     $this->runControllerWithRedirectExceptionAndGetContent('accounts/default/edit');
     // Not Coding Standard
     //Make sure user can still go to details view
     $this->setGetArray(array('id' => $account->id));
     $this->resetPostArray();
     $content = $this->runControllerWithNoExceptionsAndGetContent('accounts/default/details');
 }
 public function testABitOfEverythingAsAnExample()
 {
     $superAdminDude = new User();
     $superAdminDude->title->value = 'Miss';
     $superAdminDude->username = '******';
     $superAdminDude->firstName = 'Laura';
     $superAdminDude->lastName = 'Laurason';
     $superAdminDude->setPassword('laura');
     $this->assertTrue($superAdminDude->save());
     $adminDude = new User();
     $adminDude->title->value = 'Mr.';
     $adminDude->username = '******';
     $adminDude->firstName = 'Jason';
     $adminDude->lastName = 'Jasonson';
     $adminDude->setPassword('jason');
     $this->assertTrue($adminDude->save());
     $accountOwner = new User();
     $accountOwner->title->value = 'Mr.';
     // :P
     $accountOwner->username = '******';
     $accountOwner->firstName = 'lisa';
     $accountOwner->lastName = 'Lisason';
     $accountOwner->setPassword('lisay');
     $this->assertTrue($accountOwner->save());
     $salesDude1 = new User();
     $salesDude1->title->value = 'Mr.';
     $salesDude1->username = '******';
     $salesDude1->firstName = 'Ray';
     $salesDude1->lastName = 'Rayson';
     $salesDude1->setPassword('ray45');
     $this->assertTrue($salesDude1->save());
     $salesDude2 = new User();
     $salesDude2->title->value = 'Mr.';
     $salesDude2->username = '******';
     $salesDude2->firstName = 'Stafford';
     $salesDude2->lastName = 'Staffordson';
     $salesDude2->setPassword('stafford');
     $this->assertTrue($salesDude2->save());
     $managementDudette = new User();
     $managementDudette->title->value = 'Ms.';
     $managementDudette->username = '******';
     $managementDudette->firstName = 'Donna';
     $managementDudette->lastName = 'Donnason';
     $managementDudette->setPassword('donna');
     $this->assertTrue($managementDudette->save());
     $supportDude = new User();
     $supportDude->title->value = 'Mr.';
     $supportDude->username = '******';
     $supportDude->firstName = 'Ross';
     $supportDude->lastName = 'Rosson';
     $supportDude->setPassword('rossy');
     $this->assertTrue($supportDude->save());
     $superAdminDudes = new Group();
     $superAdminDudes->name = 'Super Admin Dudes';
     $superAdminDudes->users->add($superAdminDude);
     $this->assertTrue($superAdminDudes->save());
     $adminDudes = new Group();
     $adminDudes->name = 'Admin Dudes';
     $adminDudes->users->add($adminDude);
     $adminDudes->groups->add($superAdminDudes);
     $this->assertTrue($adminDudes->save());
     $superAdminDudes->setPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES, 0);
     $this->assertTrue($superAdminDudes->save());
     $adminDudes->setRight('UsersModule', UsersModule::RIGHT_CHANGE_USER_PASSWORDS);
     $adminDudes->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB);
     $adminDudes->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_MOBILE);
     $adminDudes->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB_API);
     $adminDudes->setPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS, 90);
     $this->assertTrue($adminDudes->save());
     $salesDudes = new Group();
     $salesDudes->name = 'Sales Dudes';
     $salesDudes->users->add($salesDude1);
     $salesDudes->users->add($salesDude2);
     $this->assertTrue($salesDudes->save());
     $managementDudes = new Group();
     $managementDudes->name = 'Management Dudes';
     $managementDudes->users->add($managementDudette);
     $this->assertTrue($managementDudes->save());
     $everyone = Group::getByName(Group::EVERYONE_GROUP_NAME);
     $everyone->setRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB);
     $everyone->setPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES, 1);
     $everyone->setPolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS, 30);
     $this->assertTrue($everyone->save());
     Yii::app()->user->userModel = $accountOwner;
     $account = new Account();
     $account->name = 'Doozy Co.';
     $this->assertTrue($account->save());
     // The account has no explicit permissions set at this point.
     // The account owner has full permissions implicitly.
     $this->assertEquals(Permission::ALL, $account->getEffectivePermissions($accountOwner));
     // Nobody else has permissions.
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($adminDude));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($adminDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($salesDude1));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($salesDude2));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($managementDudette));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($salesDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($managementDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($supportDude));
     // Everyone is given read permissions to the account.
     $everyone = Group::getByName(Group::EVERYONE_GROUP_NAME);
     $account->addPermissions($everyone, Permission::READ);
     $account->save();
     // In one step everyone has read permissions, except the owner who still has full.
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDudes));
     $this->assertEquals(Permission::ALL, $account->getEffectivePermissions($accountOwner));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($salesDude1));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($salesDude2));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($managementDudette));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($salesDudes));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($managementDudes));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($supportDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($everyone));
     // Sales Dudes is given write permissions to the account.
     $account->addPermissions($salesDudes, Permission::WRITE);
     $account->save();
     // The Sales Dudes group and everyone in it has write.
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDudes));
     $this->assertEquals(Permission::ALL, $account->getEffectivePermissions($accountOwner));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude1));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude2));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($managementDudette));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDudes));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($managementDudes));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($supportDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($everyone));
     // Management Dudes is given change owner permissions to the account.
     $account->addPermissions($managementDudes, Permission::CHANGE_OWNER);
     $account->save();
     // The Managment Dudes group and everyone in it has change owner.
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDudes));
     $this->assertEquals(Permission::ALL, $account->getEffectivePermissions($accountOwner));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude1));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude2));
     $this->assertEquals(Permission::READ | Permission::CHANGE_OWNER, $account->getEffectivePermissions($managementDudette));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDudes));
     $this->assertEquals(Permission::READ | Permission::CHANGE_OWNER, $account->getEffectivePermissions($managementDudes));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($supportDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($everyone));
     // We want to remove Support Dude's read on the account.
     // The first way... having thought about our security and groups well...
     // Everyone's read permission is removed, and instead Sales Dudes
     // and Managment Dudes are given read permissions. Order is irrelevant.
     $account->removePermissions($everyone, Permission::READ);
     $account->addPermissions($salesDudes, Permission::READ);
     $account->addPermissions($managementDudes, Permission::READ);
     $account->save();
     // The effect is that Support Dude and Admin Dudes lose read permissions because
     // now nobody has that permission via Everyone.
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($adminDude));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($adminDudes));
     $this->assertEquals(Permission::ALL, $account->getEffectivePermissions($accountOwner));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude1));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude2));
     $this->assertEquals(Permission::READ | Permission::CHANGE_OWNER, $account->getEffectivePermissions($managementDudette));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDudes));
     $this->assertEquals(Permission::READ | Permission::CHANGE_OWNER, $account->getEffectivePermissions($managementDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($supportDude));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($everyone));
     // Permissions are set back.
     $account->addPermissions($everyone, Permission::READ);
     $account->removePermissions($salesDudes, Permission::READ);
     $account->removePermissions($managementDudes, Permission::READ);
     $account->save();
     // Support Dude and Admin Dudes get their read back.
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDudes));
     $this->assertEquals(Permission::ALL, $account->getEffectivePermissions($accountOwner));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude1));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude2));
     $this->assertEquals(Permission::READ | Permission::CHANGE_OWNER, $account->getEffectivePermissions($managementDudette));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDudes));
     $this->assertEquals(Permission::READ | Permission::CHANGE_OWNER, $account->getEffectivePermissions($managementDudes));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($supportDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($everyone));
     // The second way... more ad-hoc...
     // We explicitly deny. Deny's have precedence over allows.
     $account->addPermissions($supportDude, Permission::READ, Permission::DENY);
     $account->save();
     // The effect is that Support Dude loses read permissions but
     // Everyone else still has read.
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDudes));
     $this->assertEquals(Permission::ALL, $account->getEffectivePermissions($accountOwner));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude1));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude2));
     $this->assertEquals(Permission::READ | Permission::CHANGE_OWNER, $account->getEffectivePermissions($managementDudette));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDudes));
     $this->assertEquals(Permission::READ | Permission::CHANGE_OWNER, $account->getEffectivePermissions($managementDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($supportDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($everyone));
     // Managment Dudes has all permissions is denied.
     // This takes precedence over the read permission the group was given.
     $account->addPermissions($managementDudes, Permission::ALL, Permission::DENY);
     $account->save();
     // The effect is that Management Dudes lose all permissions
     // regardless of what they have been granted.
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDudes));
     $this->assertEquals(Permission::ALL, $account->getEffectivePermissions($accountOwner));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude1));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude2));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($managementDudette));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($managementDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($supportDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($everyone));
     // We'll give Management Dudes back their permissions.
     $account->removePermissions($managementDudes, Permission::ALL, Permission::DENY);
     // And give management dudette change permissions.
     $account->addPermissions($managementDudette, Permission::CHANGE_PERMISSIONS);
     $account->save();
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($adminDudes));
     $this->assertEquals(Permission::ALL, $account->getEffectivePermissions($accountOwner));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude1));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDude2));
     $this->assertEquals(Permission::READ | Permission::CHANGE_PERMISSIONS | Permission::CHANGE_OWNER, $account->getEffectivePermissions($managementDudette));
     $this->assertEquals(Permission::READ_WRITE, $account->getEffectivePermissions($salesDudes));
     $this->assertEquals(Permission::READ | Permission::CHANGE_OWNER, $account->getEffectivePermissions($managementDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($supportDude));
     $this->assertEquals(Permission::READ, $account->getEffectivePermissions($everyone));
     // Then we'll just nuke eveyone's permissions. If you use this it is for
     // the kind of scenario where an admin wants to re-setup permissions from scratch
     // so you'd put a Do You Really Want To Do This???? kind of message.
     Permission::deleteAll();
     // Removing all permissions is done directly on the database,
     // so we need to forget our account and get it back again.
     $accountId = $account->id;
     $account->forget();
     unset($account);
     $account = Account::getById($accountId);
     // Nobody else has permissions again.
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($adminDude));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($adminDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($salesDude1));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($salesDude2));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($managementDudette));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($salesDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($managementDudes));
     $this->assertEquals(Permission::NONE, $account->getEffectivePermissions($supportDude));
     // TODO
     // - Permissions on modules.
     // - Permissions on types.
     // - Permissions on fields.
     // All users have the right to login via the web, because the Everyone group was granted that right.
     $this->assertEquals(Right::ALLOW, $adminDude->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB));
     $this->assertEquals(Right::ALLOW, $adminDudes->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB));
     $this->assertEquals(Right::ALLOW, $salesDude1->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB));
     $this->assertEquals(Right::ALLOW, $salesDude2->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB));
     $this->assertEquals(Right::ALLOW, $managementDudette->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB));
     $this->assertEquals(Right::ALLOW, $salesDudes->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB));
     $this->assertEquals(Right::ALLOW, $managementDudes->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB));
     $this->assertEquals(Right::ALLOW, $supportDude->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB));
     $this->assertEquals(Right::ALLOW, $everyone->getEffectiveRight('UsersModule', UsersModule::RIGHT_LOGIN_VIA_WEB));
     $this->assertEquals(Right::ALLOW, $adminDude->getEffectiveRight('UsersModule', UsersModule::RIGHT_CHANGE_USER_PASSWORDS));
     $this->assertEquals(Right::ALLOW, $adminDudes->getEffectiveRight('UsersModule', UsersModule::RIGHT_CHANGE_USER_PASSWORDS));
     $this->assertEquals(Right::DENY, $salesDude1->getEffectiveRight('UsersModule', UsersModule::RIGHT_CHANGE_USER_PASSWORDS));
     $this->assertEquals(Right::DENY, $salesDude2->getEffectiveRight('UsersModule', UsersModule::RIGHT_CHANGE_USER_PASSWORDS));
     $this->assertEquals(Right::DENY, $managementDudette->getEffectiveRight('UsersModule', UsersModule::RIGHT_CHANGE_USER_PASSWORDS));
     $this->assertEquals(Right::DENY, $salesDudes->getEffectiveRight('UsersModule', UsersModule::RIGHT_CHANGE_USER_PASSWORDS));
     $this->assertEquals(Right::DENY, $managementDudes->getEffectiveRight('UsersModule', UsersModule::RIGHT_CHANGE_USER_PASSWORDS));
     $this->assertEquals(Right::DENY, $supportDude->getEffectiveRight('UsersModule', UsersModule::RIGHT_CHANGE_USER_PASSWORDS));
     $this->assertEquals(Right::DENY, $everyone->getEffectiveRight('UsersModule', UsersModule::RIGHT_CHANGE_USER_PASSWORDS));
     // All users have a password expiry days of 30 because it was set on Everyone, but that was overridden
     // for Admin Dudes with a more generous password expiry policy set for them.
     $this->assertEquals(90, $adminDude->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(90, $adminDudes->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(90, $adminDude->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(90, $adminDudes->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(30, $salesDude1->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(30, $salesDude2->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(30, $managementDudette->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(30, $salesDudes->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(30, $managementDudes->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(30, $supportDude->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     $this->assertEquals(30, $everyone->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRY_DAYS));
     // But all users' passwords, except Super Admin Dudes, expire because of the policy set on Everyone,
     // which is set more specifically for Super Admin Dudes.
     $this->assertEquals(0, $superAdminDude->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     $this->assertEquals(0, $superAdminDudes->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     $this->assertEquals(1, $adminDude->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     $this->assertEquals(1, $adminDudes->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     $this->assertEquals(1, $salesDude1->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     $this->assertEquals(1, $salesDude2->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     $this->assertEquals(1, $managementDudette->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     $this->assertEquals(1, $salesDudes->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     $this->assertEquals(1, $managementDudes->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     $this->assertEquals(1, $supportDude->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     $this->assertEquals(1, $everyone->getEffectivePolicy('UsersModule', UsersModule::POLICY_PASSWORD_EXPIRES));
     // The policy set on Super Admin Dudes that their passwords don't expire is more explicit than the Everyone
     // setting and so takes precedence. While ALLOW for permissions and rights is just required from any one
     // source (explicit or inherited from a group) and DENY on any source overrides it, the effective policy
     // is the most explicit. A policy set specifically on a user overrides a policy set on a group they are
     // directly in, which overrides one that that group is in, and so on, which overrides anything set on the
     // Everyone group. If nothing is set the policy value is null.
     // TODO
     // - Roles.
 }
 public function testUpdateLatestActivityDateTimeWhenAnEmailIsSentOrArchived()
 {
     $emailMessage = EmailMessageTestHelper::createDraftSystemEmail('subject 1', Yii::app()->user->userModel);
     $account3 = AccountTestHelper::createAccountByNameForOwner('account3', Yii::app()->user->userModel);
     $account4 = AccountTestHelper::createAccountByNameForOwner('account4', Yii::app()->user->userModel);
     $account5 = AccountTestHelper::createAccountByNameForOwner('account4', Yii::app()->user->userModel);
     $dateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $account5->setLatestActivityDateTime($dateTime);
     $this->assertTrue($account5->save());
     $account3Id = $account3->id;
     $account4Id = $account4->id;
     $account5Id = $account5->id;
     $this->assertNull($account3->latestActivityDateTime);
     $this->assertNull($account4->latestActivityDateTime);
     $this->assertEquals($dateTime, $account5->latestActivityDateTime);
     $emailMessage->sender->personsOrAccounts->add($account3);
     $emailMessage->recipients[0]->personsOrAccounts->add($account4);
     $emailMessage->recipients[0]->personsOrAccounts->add($account5);
     $this->assertTrue($emailMessage->save());
     $this->assertNull($account3->latestActivityDateTime);
     $this->assertNull($account4->latestActivityDateTime);
     $this->assertEquals($dateTime, $account5->latestActivityDateTime);
     $emailMessageId = $emailMessage->id;
     $emailMessage->forget();
     $account3->forget();
     $account4->forget();
     $account5->forget();
     //Retrieve email message and set sentDateTime, at this point the accounts should update with this value
     $sentDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 86400);
     $emailMessage = EmailMessage::getById($emailMessageId);
     $emailMessage->sentDateTime = $sentDateTime;
     $this->assertTrue($emailMessage->save());
     $account3 = Account::getById($account3Id);
     $account4 = Account::getById($account4Id);
     $account5 = Account::getById($account5Id);
     $this->assertEquals($sentDateTime, $account3->latestActivityDateTime);
     $this->assertEquals($sentDateTime, $account4->latestActivityDateTime);
     $this->assertEquals($dateTime, $account5->latestActivityDateTime);
 }
 public function testOnCreateOwnerChangeAndDeleteAccountModel()
 {
     $super = User::getByUsername('super');
     $billy = self::$billy;
     Yii::app()->user->userModel = $super;
     $job = new ReadPermissionSubscriptionUpdateForAccountFromBuildTableJob();
     Yii::app()->jobQueue->deleteAll();
     // Clean contact table
     $sql = "SELECT * FROM account_read_subscription";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertTrue(empty($rows));
     $account1 = AccountTestHelper::createAccountByNameForOwner('First Account', $super);
     sleep(1);
     $queuedJobs = Yii::app()->jobQueue->getAll();
     $this->assertEquals(1, count($queuedJobs[5]));
     $this->assertEquals('ReadPermissionSubscriptionUpdateForAccountFromBuildTable', $queuedJobs[5][0]['jobType']);
     Yii::app()->jobQueue->deleteAll();
     $this->assertTrue($job->run());
     $sql = "SELECT * FROM account_read_subscription order by userid";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertEquals(2, count($rows));
     $this->assertEquals($super->id, $rows[0]['userid']);
     $this->assertEquals($account1->id, $rows[0]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[0]['subscriptiontype']);
     $this->assertEquals($billy->id, $rows[1]['userid']);
     $this->assertEquals($account1->id, $rows[1]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[1]['subscriptiontype']);
     sleep(1);
     // Test deletion
     $account1->delete();
     sleep(1);
     $queuedJobs = Yii::app()->jobQueue->getAll();
     $this->assertEquals(1, count($queuedJobs[5]));
     $this->assertEquals('ReadPermissionSubscriptionUpdateForAccountFromBuildTable', $queuedJobs[5][0]['jobType']);
     Yii::app()->jobQueue->deleteAll();
     $this->assertTrue($job->run());
     $sql = "SELECT * FROM account_read_subscription order by userid";
     $rows2 = ZurmoRedBean::getAll($sql);
     $this->assertEquals(2, count($rows2));
     $this->assertEquals($super->id, $rows2[0]['userid']);
     $this->assertEquals($account1->id, $rows2[0]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_DELETE, $rows2[0]['subscriptiontype']);
     $this->assertNotEquals($rows[0]['modifieddatetime'], $rows2[0]['modifieddatetime']);
     $this->assertEquals($billy->id, $rows2[1]['userid']);
     $this->assertEquals($account1->id, $rows2[1]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_DELETE, $rows2[1]['subscriptiontype']);
     $this->assertNotEquals($rows[1]['modifieddatetime'], $rows2[1]['modifieddatetime']);
     // Test owner change, but when both users have permissions to access the account
     $sql = "DELETE FROM account_read_subscription";
     ZurmoRedBean::exec($sql);
     $sql = "SELECT * FROM account_read_subscription";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertTrue(empty($rows));
     $account2 = AccountTestHelper::createAccountByNameForOwner('Second Account', $super);
     sleep(1);
     $queuedJobs = Yii::app()->jobQueue->getAll();
     $this->assertEquals(1, count($queuedJobs[5]));
     $this->assertEquals('ReadPermissionSubscriptionUpdateForAccountFromBuildTable', $queuedJobs[5][0]['jobType']);
     Yii::app()->jobQueue->deleteAll();
     $this->assertTrue($job->run());
     $sql = "SELECT * FROM account_read_subscription order by userid";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertEquals(2, count($rows));
     $this->assertEquals($super->id, $rows[0]['userid']);
     $this->assertEquals($account2->id, $rows[0]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[0]['subscriptiontype']);
     $this->assertEquals($billy->id, $rows[1]['userid']);
     $this->assertEquals($account2->id, $rows[1]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[1]['subscriptiontype']);
     sleep(1);
     $account2->owner = self::$billy;
     $this->assertTrue($account2->save());
     sleep(1);
     $queuedJobs = Yii::app()->jobQueue->getAll();
     $this->assertEquals(1, count($queuedJobs[5]));
     $this->assertEquals('ReadPermissionSubscriptionUpdateForAccountFromBuildTable', $queuedJobs[5][0]['jobType']);
     Yii::app()->jobQueue->deleteAll();
     $this->assertTrue($job->run());
     $sql = "SELECT * FROM account_read_subscription order by userid";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertEquals(2, count($rows));
     $this->assertEquals($super->id, $rows[0]['userid']);
     $this->assertEquals($account2->id, $rows[0]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[0]['subscriptiontype']);
     $this->assertEquals(self::$billy->id, $rows[1]['userid']);
     $this->assertEquals($account2->id, $rows[1]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[1]['subscriptiontype']);
     // Clean account table
     $accounts = Account::getAll();
     foreach ($accounts as $account) {
         $account->delete();
     }
     $sql = "DELETE FROM account_read_subscription";
     ZurmoRedBean::exec($sql);
     $johnny = self::$johnny;
     $account3 = AccountTestHelper::createAccountByNameForOwner('Third Account', $johnny);
     sleep(1);
     $queuedJobs = Yii::app()->jobQueue->getAll();
     $this->assertEquals(1, count($queuedJobs[5]));
     $this->assertEquals('ReadPermissionSubscriptionUpdateForAccountFromBuildTable', $queuedJobs[5][0]['jobType']);
     Yii::app()->jobQueue->deleteAll();
     $this->assertTrue($job->run());
     $sql = "SELECT * FROM account_read_subscription order by userid";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertEquals(3, count($rows));
     $this->assertEquals($super->id, $rows[0]['userid']);
     $this->assertEquals($account3->id, $rows[0]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[0]['subscriptiontype']);
     $this->assertEquals($billy->id, $rows[1]['userid']);
     $this->assertEquals($account3->id, $rows[1]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[1]['subscriptiontype']);
     $this->assertEquals($johnny->id, $rows[2]['userid']);
     $this->assertEquals($account3->id, $rows[2]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[2]['subscriptiontype']);
     $account3Id = $account3->id;
     $account3->forgetAll();
     $account3 = Account::getById($account3Id);
     $this->assertTrue($account3->save());
     $account3->forgetAll();
     PermissionsCache::forgetAll();
     $account3 = Account::getById($account3Id);
     $account3->owner = $super;
     $this->assertTrue($account3->save());
     sleep(1);
     $queuedJobs = Yii::app()->jobQueue->getAll();
     $this->assertEquals(1, count($queuedJobs[5]));
     $this->assertEquals('ReadPermissionSubscriptionUpdateForAccountFromBuildTable', $queuedJobs[5][0]['jobType']);
     Yii::app()->jobQueue->deleteAll();
     $this->assertTrue($job->run());
     $sql = "SELECT * FROM account_read_subscription order by userid";
     $rows = ZurmoRedBean::getAll($sql);
     $this->assertEquals(3, count($rows));
     $this->assertEquals($super->id, $rows[0]['userid']);
     $this->assertEquals($account3->id, $rows[0]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[0]['subscriptiontype']);
     $this->assertEquals($billy->id, $rows[1]['userid']);
     $this->assertEquals($account3->id, $rows[1]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_ADD, $rows[1]['subscriptiontype']);
     $this->assertEquals($johnny->id, $rows[2]['userid']);
     $this->assertEquals($account3->id, $rows[2]['modelid']);
     $this->assertEquals(ReadPermissionsSubscriptionUtil::TYPE_DELETE, $rows[2]['subscriptiontype']);
 }
 /**
  * @depends testTriggerBeforeSaveCreatedByUser
  */
 public function testTriggerBeforeSaveModifiedByUser()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     //First test equals
     $workflow = self::makeOnSaveWorkflowAndTriggerWithoutValueType('modifiedByUser', 'equals', self::$superUserId);
     $model = new Account();
     $model->name = 'name';
     $model->owner = User::getByUsername('bobby');
     $this->assertTrue(WorkflowTriggersUtil::areTriggersTrueBeforeSave($workflow, $model));
     $this->assertTrue($model->save());
     $modelId = $model->id;
     $model->forget();
     Yii::app()->user->userModel = User::getByUsername('bobby');
     $model = Account::getById($modelId);
     $model->name = 'name2';
     $this->assertFalse(WorkflowTriggersUtil::areTriggersTrueBeforeSave($workflow, $model));
 }
Beispiel #13
0
 /**
  * @depends testCreateAndGetTaskById
  */
 public function testAddingActivityItemThatShouldCastDownAndThrowException()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $accounts = Account::getByName('anAccount');
     $accountId = $accounts[0]->id;
     $accounts[0]->forget();
     $task = new Task();
     $task->activityItems->add(Account::getById($accountId));
     foreach ($task->activityItems as $existingItem) {
         try {
             $castedDownModel = $existingItem->castDown(array(array('SecurableItem', 'OwnedSecurableItem', 'Account')));
             //this should not fail
         } catch (NotFoundException $e) {
             $this->fail();
         }
     }
     foreach ($task->activityItems as $existingItem) {
         try {
             $castedDownModel = $existingItem->castDown(array(array('SecurableItem', 'OwnedSecurableItem', 'Person', 'Contact')));
             //this should fail
             $this->fail();
         } catch (NotFoundException $e) {
         }
     }
 }
 public function actionEdit($id, $redirectUrl = null)
 {
     $contract = Contract::getById(intval($id));
     $sql = "select * from contract_opportunity where contract_id=" . $id;
     $rec = Yii::app()->db->createCommand($sql)->queryRow();
     $rec_t['value'] = $rec_c['value'] = '';
     if (!empty($rec) && !empty($rec['opportunity_id'])) {
         $getopportunity = Opportunity::getById(intval($rec['opportunity_id']));
         $sql1 = "select * from opportunity where id=" . $rec['opportunity_id'];
         $rec1 = Yii::app()->db->createCommand($sql1)->queryRow();
     }
     if (isset($rec1['totalbulkpricstm_currencyvalue_id']) && !empty($rec1['totalbulkpricstm_currencyvalue_id'])) {
         //get totalbuilprice
         $sql_t = "select * from currencyvalue where id=" . $rec1['totalbulkpricstm_currencyvalue_id'];
         $rec_t = Yii::app()->db->createCommand($sql_t)->queryRow();
     }
     if (isset($rec1['constructcoscstm_currencyvalue_id']) && !empty($rec1['constructcoscstm_currencyvalue_id'])) {
         $sql_c = "select * from currencyvalue where id=" . $rec1['constructcoscstm_currencyvalue_id'];
         $rec_c = Yii::app()->db->createCommand($sql_c)->queryRow();
     }
     $getaccount = Account::getById(intval($getopportunity->account->id));
     $_SESSION['unitsCstmCstm'] = !empty($getaccount->unitsCstmCstm) ? $getaccount->unitsCstmCstm : 1;
     $_SESSION['totalbulkpricstm'] = !empty($rec_t['value']) ? $rec_t['value'] : 1;
     $_SESSION['totalcostprccstm'] = !empty($rec_c['value']) ? $_SESSION['unitsCstmCstm'] * $rec_c['value'] : $_SESSION['unitsCstmCstm'] * 1;
     ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($contract);
     $this->processEdit($contract, $redirectUrl);
 }
 /**
  * @depends testCreateWithRelations
  */
 public function testUpdateWithRelations()
 {
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $authenticationData = $this->login();
     $headers = array('Accept: application/xml', 'ZURMO_SESSION_ID: ' . $authenticationData['sessionId'], 'ZURMO_TOKEN: ' . $authenticationData['token'], 'ZURMO_API_REQUEST_TYPE: REST');
     $account = AccountTestHelper::createAccountByNameForOwner('Factor X', $super);
     $account1 = AccountTestHelper::createAccountByNameForOwner('Miko', $super);
     $account2 = AccountTestHelper::createAccountByNameForOwner('Troter', $super);
     $contact = ContactTestHelper::createContactByNameForOwner('Simon', $super);
     $redBeanModelToApiDataUtil = new RedBeanModelToApiDataUtil($account);
     $compareData = $redBeanModelToApiDataUtil->getData();
     $account->forget();
     $data['modelRelations'] = array('accounts' => array(array('action' => 'add', 'modelId' => $account1->id, 'modelClassName' => 'Account'), array('action' => 'add', 'modelId' => $account2->id, 'modelClassName' => 'Account')), 'contacts' => array(array('action' => 'add', 'modelId' => $contact->id, 'modelClassName' => 'Contact')));
     $data['name'] = 'Zurmo Inc.';
     $response = ApiRestTestHelper::createXmlApiCall($this->serverUrl . '/test.php/accounts/account/api/update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = XML2Array::createArray($response);
     unset($response['data']['modifiedDateTime']);
     unset($compareData['modifiedDateTime']);
     $compareData['name'] = 'Zurmo Inc.';
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     $this->assertEquals($compareData, $response['data']);
     RedBeanModel::forgetAll();
     $account = Account::getById($compareData['id']);
     $this->assertEquals(2, count($account->accounts));
     $this->assertEquals($account1->id, $account->accounts[0]->id);
     $this->assertEquals($account2->id, $account->accounts[1]->id);
     $this->assertEquals(1, count($account->contacts));
     $this->assertEquals($contact->id, $account->contacts[0]->id);
     $account1 = Account::getById($account1->id);
     $this->assertEquals($account->id, $account1->account->id);
     $account2 = Account::getById($account2->id);
     $this->assertEquals($account->id, $account2->account->id);
     $contact = Contact::getById($contact->id);
     $this->assertEquals($account->id, $contact->account->id);
     // Now test remove relations
     $data['modelRelations'] = array('accounts' => array(array('action' => 'remove', 'modelId' => $account1->id, 'modelClassName' => 'Account'), array('action' => 'remove', 'modelId' => $account2->id, 'modelClassName' => 'Account')), 'contacts' => array(array('action' => 'remove', 'modelId' => $contact->id, 'modelClassName' => 'Contact')));
     $response = ApiRestTestHelper::createXmlApiCall($this->serverUrl . '/test.php/accounts/account/api/update/' . $compareData['id'], 'PUT', $headers, array('data' => $data));
     $response = XML2Array::createArray($response);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     RedBeanModel::forgetAll();
     $updatedModel = Account::getById($compareData['id']);
     $this->assertEquals(0, count($updatedModel->accounts));
     $this->assertEquals(0, count($updatedModel->contacts));
     $account1 = Account::getById($account1->id);
     $this->assertLessThanOrEqual(0, $account1->account->id);
     $account2 = Account::getById($account2->id);
     $this->assertLessThanOrEqual(0, $account2->account->id);
     $contact = Contact::getById($contact->id);
     $this->assertLessThanOrEqual(0, $contact->account->id);
 }
 /**
  * @depends testAutoBuildDatabase
  */
 public function testAutoBuildUpgrade()
 {
     $this->unfreezeWhenDone = false;
     if (RedBeanDatabase::isFrozen()) {
         RedBeanDatabase::unfreeze();
         $this->unfreezeWhenDone = true;
     }
     // adding Text Field
     $metadata = Account::getMetadata();
     $metadata['Account']['members'][] = 'newField';
     $rules = array('newField', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'string128';
     $rules = array('string128', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $rules = array('string128', 'length', 'min' => 3, 'max' => 128);
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'string555';
     $rules = array('string555', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $rules = array('string555', 'length', 'min' => 1, 'max' => 555);
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'string100000';
     $rules = array('string100000', 'type', 'type' => 'string');
     $metadata['Account']['rules'][] = $rules;
     $rules = array('string100000', 'length', 'min' => 1, 'max' => 100000);
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'textField';
     $rules = array('textField', 'type', 'type' => 'text');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'longTextField';
     $rules = array('longTextField', 'type', 'type' => 'longtext');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'dateField';
     $rules = array('dateField', 'type', 'type' => 'date');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'booleanField';
     $rules = array('booleanField', 'boolean');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'integerField';
     $rules = array('integerField', 'type', 'type' => 'integer');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'dateTimeField';
     $rules = array('dateTimeField', 'type', 'type' => 'datetime');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'urlField';
     $rules = array('urlField', 'url');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'floatField';
     $rules = array('floatField', 'type', 'type' => 'float');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'longTextField';
     $rules = array('longTextField', 'type', 'type' => 'longtext');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'blobField';
     $rules = array('blobField', 'type', 'type' => 'blob');
     $metadata['Account']['rules'][] = $rules;
     $metadata['Account']['members'][] = 'longBlobField';
     $rules = array('longBlobField', 'type', 'type' => 'longblob');
     $metadata['Account']['rules'][] = $rules;
     Account::setMetadata($metadata);
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $messageLogger = new MessageLogger();
     $beforeRowCount = DatabaseCompatibilityUtil::getTableRowsCountTotal();
     InstallUtil::autoBuildDatabase($messageLogger);
     $afterRowCount = DatabaseCompatibilityUtil::getTableRowsCountTotal();
     $this->assertEquals($beforeRowCount, $afterRowCount);
     //Check Account fields
     $tableName = RedBeanModel::getTableName('Account');
     $columns = R::$writer->getColumns($tableName);
     $this->assertEquals('text', $columns['newfield']);
     $this->assertEquals('varchar(128)', $columns['string128']);
     $this->assertEquals('text', $columns['string555']);
     $this->assertEquals('longtext', $columns['string100000']);
     $this->assertEquals('text', $columns['textfield']);
     $this->assertEquals('date', $columns['datefield']);
     $this->assertEquals('tinyint(1)', $columns['booleanfield']);
     $this->assertEquals('int(11) unsigned', $columns['integerfield']);
     $this->assertEquals('datetime', $columns['datetimefield']);
     $this->assertEquals('varchar(255)', $columns['urlfield']);
     $this->assertEquals('double', $columns['floatfield']);
     $this->assertEquals('longtext', $columns['longtextfield']);
     $this->assertEquals('blob', $columns['blobfield']);
     $this->assertEquals('longblob', $columns['longblobfield']);
     $account = new Account();
     $account->name = 'Test Name';
     $account->owner = $super;
     $randomString = str_repeat("Aa", 64);
     $account->string128 = $randomString;
     $this->assertTrue($account->save());
     $metadata = Account::getMetadata();
     foreach ($metadata['Account']['rules'] as $key => $rule) {
         if ($rule[0] == 'string128' && $rule[1] == 'length') {
             $metadata['Account']['rules'][$key]['max'] = 64;
         }
     }
     Account::setMetadata($metadata);
     InstallUtil::autoBuildDatabase($messageLogger);
     RedBeanModel::forgetAll();
     $modifiedAccount = Account::getById($account->id);
     $this->assertEquals($randomString, $modifiedAccount->string128);
     //Check Account fields
     $tableName = RedBeanModel::getTableName('Account');
     $columns = R::$writer->getColumns($tableName);
     $this->assertEquals('varchar(128)', $columns['string128']);
 }
Beispiel #17
0
 public function actionCopy($id)
 {
     $copyToAccount = new Account();
     $postVariableName = get_class($copyToAccount);
     if (!isset($_POST[$postVariableName])) {
         $account = Account::getById((int) $id);
         ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($account);
         ZurmoCopyModelUtil::copy($account, $copyToAccount);
     }
     $this->processEdit($copyToAccount);
 }
 /**
  * @depends testCreateAddAndSaveAndRemoveByIndexRelatedModels
  */
 public function testRemoveRelatedModels()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $accounts = Account::getByName('Wibble Corp');
     $this->assertEquals(1, count($accounts));
     $account = $accounts[0];
     $this->assertEquals(self::CONTACTS, $account->contacts->count());
     $account->contacts->removeByIndex(0);
     $this->assertEquals(self::CONTACTS - 1, $account->contacts->count());
     $accountId = $account->id;
     $account->forget();
     unset($account);
     // Removes are now deferred. The account
     // wasn't saved so no removed happened.
     $account = Account::getById($accountId);
     $this->assertEquals(self::CONTACTS, $account->contacts->count());
     $account->contacts->removeByIndex(0);
     $this->assertEquals(self::CONTACTS - 1, $account->contacts->count());
     $this->assertTrue($account->save());
     $account->forget();
     unset($account);
     $account = Account::getById($accountId);
     $this->assertEquals(self::CONTACTS - 1, $account->contacts->count());
 }
 /**
  * @depends testMakeBySecurableItem
  */
 public function testResolveExplicitReadWriteModelPermissions()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $accounts = Account::getByName('aTestAccount');
     $this->assertEquals(1, count($accounts));
     $account = $accounts[0];
     $accountId = $account->id;
     $group4 = Group::getByName('Group4');
     $group3 = Group::getByName('Group3');
     $group2 = Group::getByName('Group2');
     $explicitReadWriteModelPermissions = new ExplicitReadWriteModelPermissions();
     $explicitReadWriteModelPermissions->addReadWritePermitableToRemove($group3);
     $explicitReadWriteModelPermissions->addReadWritePermitable($group4);
     ExplicitReadWriteModelPermissionsUtil::resolveExplicitReadWriteModelPermissions($account, $explicitReadWriteModelPermissions);
     $account->forget();
     $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem(Account::getById($accountId));
     $readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
     $readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables();
     $this->assertEquals(2, count($readWritePermitables));
     $this->assertEquals(0, count($readOnlyPermitables));
     $this->assertEquals($group2, $readWritePermitables[$group2->id]);
     $this->assertEquals($group4, $readWritePermitables[$group4->id]);
 }
 public function testEditAnAccountUserAfterTheCustomDateFieldNullValueBugForAccountsModule()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $baseCurrency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
     $account = Account::getByName('myNewAccount');
     $accountId = $account[0]->id;
     //Edit and save the account.
     $this->setGetArray(array('id' => $accountId));
     $this->setPostArray(array('Account' => array('name' => 'myNewAccount', 'officePhone' => '259-784-2169', 'industry' => array('value' => 'Automotive'), 'officeFax' => '299-845-7863', 'employees' => '930', 'annualRevenue' => '474000000', 'type' => array('value' => 'Prospect'), 'website' => 'http://www.Unnamed.com', 'primaryEmail' => array('emailAddress' => '*****@*****.**', 'optOut' => '1', 'isInvalid' => '0'), 'secondaryEmail' => array('emailAddress' => '', 'optOut' => '0', 'isInvalid' => '0'), 'billingAddress' => array('street1' => '6466 South Madison Creek', 'street2' => '', 'city' => 'Chicago', 'state' => 'IL', 'postalCode' => '60652', 'country' => 'USA'), 'shippingAddress' => array('street1' => '27054 West Michigan Lane', 'street2' => '', 'city' => 'Austin', 'state' => 'TX', 'postalCode' => '78759', 'country' => 'USA'), 'description' => 'This is a Description', 'explicitReadWriteModelPermissions' => array('type' => null), 'datenotreqCstm' => '')));
     //setting null value
     $this->runControllerWithRedirectExceptionAndGetUrl('accounts/default/edit');
     //Check the details if they are saved properly for the custom fields.
     $account = Account::getByName('myNewAccount');
     //Retrieve the permission for the account.
     $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem(Account::getById($account[0]->id));
     $readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
     $readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables();
     $this->assertEquals(1, count($account));
     $this->assertEquals($account[0]->name, 'myNewAccount');
     $this->assertEquals($account[0]->officePhone, '259-784-2169');
     $this->assertEquals($account[0]->industry->value, 'Automotive');
     $this->assertEquals($account[0]->officeFax, '299-845-7863');
     $this->assertEquals($account[0]->employees, '930');
     $this->assertEquals($account[0]->annualRevenue, '474000000');
     $this->assertEquals($account[0]->type->value, 'Prospect');
     $this->assertEquals($account[0]->website, 'http://www.Unnamed.com');
     $this->assertEquals($account[0]->primaryEmail->emailAddress, '*****@*****.**');
     $this->assertEquals($account[0]->primaryEmail->optOut, '1');
     $this->assertEquals($account[0]->primaryEmail->isInvalid, '0');
     $this->assertEquals($account[0]->secondaryEmail->emailAddress, '');
     $this->assertEquals($account[0]->secondaryEmail->optOut, '0');
     $this->assertEquals($account[0]->secondaryEmail->isInvalid, '0');
     $this->assertEquals($account[0]->billingAddress->street1, '6466 South Madison Creek');
     $this->assertEquals($account[0]->billingAddress->street2, '');
     $this->assertEquals($account[0]->billingAddress->city, 'Chicago');
     $this->assertEquals($account[0]->billingAddress->state, 'IL');
     $this->assertEquals($account[0]->billingAddress->postalCode, '60652');
     $this->assertEquals($account[0]->billingAddress->country, 'USA');
     $this->assertEquals($account[0]->shippingAddress->street1, '27054 West Michigan Lane');
     $this->assertEquals($account[0]->shippingAddress->street2, '');
     $this->assertEquals($account[0]->shippingAddress->city, 'Austin');
     $this->assertEquals($account[0]->shippingAddress->state, 'TX');
     $this->assertEquals($account[0]->shippingAddress->postalCode, '78759');
     $this->assertEquals($account[0]->shippingAddress->country, 'USA');
     $this->assertEquals($account[0]->description, 'This is a Description');
     $this->assertEquals(0, count($readWritePermitables));
     $this->assertEquals(0, count($readOnlyPermitables));
     $this->assertEquals($account[0]->datenotreqCstm, null);
 }
 /**
  * @depends testBulkSetAndGetWithRelatedModels
  */
 public function testEmptyPostValueSavingAsZeros()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $_FAKEPOST = array('Account' => array('name' => 'Vomitorio Corp 2', 'officePhone' => '123456789', 'officeFax' => '', 'employees' => 3, 'annualRevenue' => null, 'website' => 'http://barf.com', 'billingAddress' => array('street1' => '123 Road Rd', 'street2' => null, 'city' => 'Cityville', 'postalCode' => '12345', 'country' => 'Countrilia'), 'description' => 'a description'));
     $user = User::getByUsername('bobby');
     $account = new Account();
     $account->owner = $user;
     $account->setAttributes($_FAKEPOST['Account']);
     $this->assertTrue($account->save());
     $account = Account::getById($account->id);
     $this->assertEmpty($account->officeFax);
     $this->assertNotSame(0, $account->officeFax);
     $this->assertNotSame(0, $account->billingAddress->street2);
 }
 public function testSuperUserAllDefaultControllerActions()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $superAccountId = self::getModelIdByModelNameAndName('Account', 'superAccount');
     $superAccountId2 = self::getModelIdByModelNameAndName('Account', 'superAccount2');
     $superContactId = self::getModelIdByModelNameAndName('Contact', 'superContact superContactson');
     $superContactId2 = self::getModelIdByModelNameAndName('Contact', 'superContact2 superContact2son');
     $superContactId3 = self::getModelIdByModelNameAndName('Contact', 'superContact3 superContact3son');
     $account = Account::getById($superAccountId);
     $account2 = Account::getById($superAccountId2);
     $contact = Contact::getById($superContactId);
     $contact2 = Contact::getById($superContactId2);
     $contact3 = Contact::getById($superContactId3);
     //confirm no existing activities exist
     $activities = Activity::getAll();
     $this->assertEquals(0, count($activities));
     //Test just going to the create from relation view.
     $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect'));
     $this->runControllerWithNoExceptionsAndGetContent('meetings/default/createFromRelation');
     //add related meeting for account using createFromRelation action
     $activityItemPostData = array('Account' => array('id' => $superAccountId));
     $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect'));
     $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Meeting' => array('name' => 'myMeeting', 'startDateTime' => '11/1/2011 7:45 PM')));
     $this->runControllerWithRedirectExceptionAndGetContent('meetings/default/createFromRelation');
     //now test that the new meeting exists, and is related to the account.
     $meetings = Meeting::getAll();
     $this->assertEquals(1, count($meetings));
     $this->assertEquals('myMeeting', $meetings[0]->name);
     $this->assertEquals(1, $meetings[0]->activityItems->count());
     $activityItem1 = $meetings[0]->activityItems->offsetGet(0);
     $this->assertEquals($account, $activityItem1);
     //test viewing the existing meeting in a details view
     $this->setGetArray(array('id' => $meetings[0]->id));
     $this->resetPostArray();
     $this->runControllerWithNoExceptionsAndGetContent('meetings/default/details');
     //test editing an existing meeting and saving. Add a second relation, to a contact.
     //First just go to the edit view and confirm it loads ok.
     $this->setGetArray(array('id' => $meetings[0]->id, 'redirectUrl' => 'someRedirect'));
     $this->resetPostArray();
     $this->runControllerWithNoExceptionsAndGetContent('meetings/default/edit');
     //Save changes via edit action.
     $activityItemPostData = array('Account' => array('id' => $superAccountId), 'Contact' => array('id' => $superContactId));
     $this->setGetArray(array('id' => $meetings[0]->id, 'redirectUrl' => 'someRedirect'));
     $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Meeting' => array('name' => 'myMeetingX')));
     $this->runControllerWithRedirectExceptionAndGetContent('meetings/default/edit');
     //Confirm changes applied correctly.
     $meetings = Meeting::getAll();
     $this->assertEquals(1, count($meetings));
     $this->assertEquals('myMeetingX', $meetings[0]->name);
     $this->assertEquals(2, $meetings[0]->activityItems->count());
     $activityItem1 = $meetings[0]->activityItems->offsetGet(0);
     $activityItem2 = $meetings[0]->activityItems->offsetGet(1);
     $this->assertEquals($account, $activityItem1);
     $this->assertEquals($contact, $activityItem2);
     //Remove contact relation.  Switch account relation to a different account.
     $activityItemPostData = array('Account' => array('id' => $superAccountId2));
     $this->setGetArray(array('id' => $meetings[0]->id));
     $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Meeting' => array('name' => 'myMeetingX')));
     $this->runControllerWithRedirectExceptionAndGetContent('meetings/default/edit');
     //Confirm changes applied correctly.
     $meetings = Meeting::getAll();
     $this->assertEquals(1, count($meetings));
     $this->assertEquals('myMeetingX', $meetings[0]->name);
     $this->assertEquals(1, $meetings[0]->activityItems->count());
     $activityItem1 = $meetings[0]->activityItems->offsetGet(0);
     $this->assertEquals($account2, $activityItem1);
     //test removing a meeting.
     $this->setGetArray(array('id' => $meetings[0]->id));
     $this->resetPostArray();
     $this->runControllerWithRedirectExceptionAndGetContent('meetings/default/delete');
     //Confirm no more meetings exist.
     $meetings = Meeting::getAll();
     $this->assertEquals(0, count($meetings));
     //Test adding a meeting with multiple contacts
     $contactItemPrefix = Meeting::CONTACT_ATTENDEE_PREFIX;
     $meetingAttendeesData = $contactItemPrefix . $superContactId . ',' . $contactItemPrefix . $superContactId2 . ',' . $contactItemPrefix . $superContactId3;
     $activityItemPostData = array('Account' => array('id' => $superAccountId), 'Contact' => array('ids' => $meetingAttendeesData));
     // Not Coding Standard
     $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect'));
     $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Meeting' => array('name' => 'myMeeting2', 'startDateTime' => '11/1/2011 7:45 PM')));
     $this->runControllerWithRedirectExceptionAndGetContent('meetings/default/createFromRelation');
     //now test that the new meeting exists, and is related to the account.
     $meetings = Meeting::getAll();
     $this->assertEquals(1, count($meetings));
     $this->assertEquals('myMeeting2', $meetings[0]->name);
     $this->assertEquals(4, $meetings[0]->activityItems->count());
     $activityItem1 = $meetings[0]->activityItems->offsetGet(0);
     $this->assertEquals($account, $activityItem1);
 }
 public function testSuperUserCopyAction()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $superAccountId = self::getModelIdByModelNameAndName('Account', 'superAccount');
     $superContactId = self::getModelIdByModelNameAndName('Contact', 'superContact superContactson');
     $account = Account::getById($superAccountId);
     $contact = Contact::getById($superContactId);
     $activityItemPostData = array('Account' => array('id' => $superAccountId), 'Contact' => array('id' => $superContactId));
     $this->setGetArray(array('relationAttributeName' => 'Account', 'relationModelId' => $superAccountId, 'relationModuleId' => 'accounts', 'redirectUrl' => 'someRedirect'));
     $this->setPostArray(array('ActivityItemForm' => $activityItemPostData, 'Task' => array('name' => 'myTask', 'description' => 'Some task description')));
     $this->runControllerWithRedirectExceptionAndGetContent('tasks/default/createFromRelation');
     $tasks = Task::getByName('myTask');
     $this->assertCount(1, $tasks);
     $this->setGetArray(array('id' => $tasks[0]->id));
     $this->resetPostArray();
     $content = $this->runControllerWithNoExceptionsAndGetContent('tasks/default/copy');
     $this->assertContains($tasks[0]->name, $content);
     $this->assertContains($tasks[0]->description, $content);
     $this->assertContains($account->name, $content);
     $this->assertContains($contact->getFullName(), $content);
     $taskCopy = new Task();
     ActivityCopyModelUtil::copy($tasks[0], $taskCopy);
     $activityItemPostData = array();
     foreach ($taskCopy->activityItems as $relatedModel) {
         $activityItemPostData[get_class($relatedModel)] = array('id' => $relatedModel->id);
     }
     $postArray = array('Task' => array('name' => $taskCopy->name, 'description' => $taskCopy->description), 'ActivityItemForm' => $activityItemPostData);
     $this->setPostArray($postArray);
     $this->setGetArray(array('id' => $tasks[0]->id));
     $content = $this->runControllerWithRedirectExceptionAndGetContent('tasks/default/copy');
     $tasks = Task::getByName('myTask');
     $this->assertCount(2, $tasks);
     $this->assertEquals($tasks[0]->name, $tasks[1]->name);
     $this->assertEquals($tasks[0]->description, $tasks[1]->description);
     $this->assertEquals($tasks[0]->activityItems[0], $tasks[1]->activityItems[0]);
     $this->assertEquals($tasks[0]->activityItems[1], $tasks[1]->activityItems[1]);
     $tasks[0]->delete();
     $tasks[1]->delete();
 }
 /**
  * @depends testSearchForMultiSelectDropDownAttributePlacedForAccountsModule
  */
 public function testMultiSelectDropDownAttributeValuesAfterCreateAndEditPlacedForAccountsModule()
 {
     //Test that the multiple select attribute can query properly for search.
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     //Create an account to test searching multiple fields on for search.
     $account = new Account();
     $this->assertEquals(1, $account->testHobbiesCstm->values->count());
     $account->testHobbiesCstm->values->removeAll();
     $this->assertEquals(0, $account->testHobbiesCstm->values->count());
     $account->name = 'MyTestAccount';
     $account->owner = Yii::app()->user->userModel;
     $customFieldValue1 = new CustomFieldValue();
     $customFieldValue1->value = 'Reading';
     $account->testHobbiesCstm->values->add($customFieldValue1);
     $customFieldValue2 = new CustomFieldValue();
     $customFieldValue2->value = 'Writing';
     $account->testHobbiesCstm->values->add($customFieldValue2);
     $this->assertTrue($account->save());
     $accountId = $account->id;
     $account->forget();
     unset($account);
     $account = Account::getById($accountId);
     $this->assertEquals(2, $account->testHobbiesCstm->values->count());
     $this->assertContains('Reading', $account->testHobbiesCstm->values);
     $this->assertContains('Writing', $account->testHobbiesCstm->values);
     $account->forget();
     unset($account);
     $account = Account::getById($accountId);
     $customFieldValue3 = new CustomFieldValue();
     $customFieldValue3->value = 'Writing';
     $account->testHobbiesCstm->values->add($customFieldValue3);
     $this->assertEquals(3, $account->testHobbiesCstm->values->count());
     $this->assertContains('Reading', $account->testHobbiesCstm->values);
     $this->assertContains('Writing', $account->testHobbiesCstm->values);
     $this->assertNotContains('Surfing', $account->testHobbiesCstm->values);
     $this->assertNotContains('Gardening', $account->testHobbiesCstm->values);
 }
Beispiel #25
0
 /**
  * @depends testParentAccountHasCorrectAttributeImportType
  */
 public function testSimpleUserImportWhereAllRowsSucceed()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $parentAccount = AccountTestHelper::createAccountByNameForOwner('parentAccount', Yii::app()->user->userModel);
     $parentAccountId = $parentAccount->id;
     $accounts = Account::getAll();
     $this->assertEquals(1, count($accounts));
     $import = new Import();
     $serializedData['importRulesType'] = 'Accounts';
     $serializedData['firstRowIsHeaderRow'] = true;
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('importTest.csv', $import->getTempTableName(), Yii::getPathOfAlias('application.modules.accounts.tests.unit.files'));
     //update the ids of the account column to match the parent account.
     R::exec("update " . $import->getTempTableName() . " set column_16 = " . $parentAccount->id . " where id != 1 limit 4");
     $this->assertEquals(4, ImportDatabaseUtil::getCount($import->getTempTableName()));
     // includes header rows.
     $mappingData = array('column_0' => ImportMappingUtil::makeStringColumnMappingData('name'), 'column_1' => ImportMappingUtil::makeStringColumnMappingData('officePhone'), 'column_2' => ImportMappingUtil::makeStringColumnMappingData('officeFax'), 'column_3' => ImportMappingUtil::makeIntegerColumnMappingData('employees'), 'column_4' => ImportMappingUtil::makeUrlColumnMappingData('website'), 'column_5' => ImportMappingUtil::makeFloatColumnMappingData('annualRevenue'), 'column_6' => ImportMappingUtil::makeTextAreaColumnMappingData('description'), 'column_7' => ImportMappingUtil::makeStringColumnMappingData('billingAddress__city'), 'column_8' => ImportMappingUtil::makeStringColumnMappingData('billingAddress__country'), 'column_9' => ImportMappingUtil::makeStringColumnMappingData('billingAddress__postalCode'), 'column_10' => ImportMappingUtil::makeStringColumnMappingData('billingAddress__state'), 'column_11' => ImportMappingUtil::makeStringColumnMappingData('billingAddress__street1'), 'column_12' => ImportMappingUtil::makeStringColumnMappingData('billingAddress__street2'), 'column_13' => ImportMappingUtil::makeEmailColumnMappingData('primaryEmail__emailAddress'), 'column_14' => ImportMappingUtil::makeBooleanColumnMappingData('primaryEmail__isInvalid'), 'column_15' => ImportMappingUtil::makeBooleanColumnMappingData('primaryEmail__optOut'), 'column_16' => ImportMappingUtil::makeHasOneColumnMappingData('account'), 'column_17' => ImportMappingUtil::makeDropDownColumnMappingData('industry'), 'column_18' => ImportMappingUtil::makeDropDownColumnMappingData('type'));
     $importRules = ImportRulesUtil::makeImportRulesByType('Accounts');
     $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();
     //Confirm that 3 models where created.
     $accounts = Account::getAll();
     $this->assertEquals(4, count($accounts));
     $accounts = Account::getByName('account1');
     $this->assertEquals(1, count($accounts[0]));
     $this->assertEquals(123456, $accounts[0]->officePhone);
     $this->assertEquals(555, $accounts[0]->officeFax);
     $this->assertEquals(1, $accounts[0]->employees);
     $this->assertEquals('http://www.account1.com', $accounts[0]->website);
     $this->assertEquals(100, $accounts[0]->annualRevenue);
     $this->assertEquals('desc1', $accounts[0]->description);
     $this->assertEquals('city1', $accounts[0]->billingAddress->city);
     $this->assertEquals('country1', $accounts[0]->billingAddress->country);
     $this->assertEquals('postal1', $accounts[0]->billingAddress->postalCode);
     $this->assertEquals('state1', $accounts[0]->billingAddress->state);
     $this->assertEquals('street11', $accounts[0]->billingAddress->street1);
     $this->assertEquals('street21', $accounts[0]->billingAddress->street2);
     $this->assertEquals('*****@*****.**', $accounts[0]->primaryEmail->emailAddress);
     $this->assertEquals(null, $accounts[0]->primaryEmail->isInvalid);
     $this->assertEquals(null, $accounts[0]->primaryEmail->optOut);
     $this->assertTrue($accounts[0]->account->isSame($parentAccount));
     $this->assertEquals('Automotive', $accounts[0]->industry->value);
     $this->assertEquals('Prospect', $accounts[0]->type->value);
     $accounts = Account::getByName('account2');
     $this->assertEquals(1, count($accounts[0]));
     $this->assertEquals(223456, $accounts[0]->officePhone);
     $this->assertEquals(666, $accounts[0]->officeFax);
     $this->assertEquals(2, $accounts[0]->employees);
     $this->assertEquals('http://www.account2.com', $accounts[0]->website);
     $this->assertEquals(200, $accounts[0]->annualRevenue);
     $this->assertEquals('desc2', $accounts[0]->description);
     $this->assertEquals('city2', $accounts[0]->billingAddress->city);
     $this->assertEquals('country2', $accounts[0]->billingAddress->country);
     $this->assertEquals('postal2', $accounts[0]->billingAddress->postalCode);
     $this->assertEquals('state2', $accounts[0]->billingAddress->state);
     $this->assertEquals('street12', $accounts[0]->billingAddress->street1);
     $this->assertEquals('street22', $accounts[0]->billingAddress->street2);
     $this->assertEquals('*****@*****.**', $accounts[0]->primaryEmail->emailAddress);
     $this->assertEquals('1', $accounts[0]->primaryEmail->isInvalid);
     $this->assertEquals('1', $accounts[0]->primaryEmail->optOut);
     $this->assertTrue($accounts[0]->account->isSame($parentAccount));
     $this->assertEquals('Banking', $accounts[0]->industry->value);
     $this->assertEquals('Customer', $accounts[0]->type->value);
     $accounts = Account::getByName('account3');
     $this->assertEquals(1, count($accounts[0]));
     $this->assertEquals(323456, $accounts[0]->officePhone);
     $this->assertEquals(777, $accounts[0]->officeFax);
     $this->assertEquals(3, $accounts[0]->employees);
     $this->assertEquals('http://www.account3.com', $accounts[0]->website);
     $this->assertEquals(300, $accounts[0]->annualRevenue);
     $this->assertEquals('desc3', $accounts[0]->description);
     $this->assertEquals('city3', $accounts[0]->billingAddress->city);
     $this->assertEquals('country3', $accounts[0]->billingAddress->country);
     $this->assertEquals('postal3', $accounts[0]->billingAddress->postalCode);
     $this->assertEquals('state3', $accounts[0]->billingAddress->state);
     $this->assertEquals('street13', $accounts[0]->billingAddress->street1);
     $this->assertEquals('street23', $accounts[0]->billingAddress->street2);
     $this->assertEquals('*****@*****.**', $accounts[0]->primaryEmail->emailAddress);
     $this->assertEquals(null, $accounts[0]->primaryEmail->isInvalid);
     $this->assertEquals(null, $accounts[0]->primaryEmail->optOut);
     $this->assertTrue($accounts[0]->account->isSame($parentAccount));
     $this->assertEquals('Energy', $accounts[0]->industry->value);
     $this->assertEquals('Vendor', $accounts[0]->type->value);
     //Confirm 10 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 2 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));
     //test the parent account has 3 children
     $parentAccount->forget();
     $parentAccount = Account::getById($parentAccountId);
     $this->assertEquals(3, $parentAccount->accounts->count());
 }
 public function testCreateWithScenario()
 {
     $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');
     $data['name'] = 'ABCD';
     $data['createdDateTime'] = '2014-06-12 15:22:41';
     $data['modifiedDateTime'] = '2014-06-12 15:28:41';
     $response = $this->createApiCallWithRelativeUrl('create/', 'POST', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_FAILURE, $response['status']);
     $this->assertEquals('It is not allowed to set read only attribute: createdDateTime.', $response['message']);
     // Now try to use some invalid scenario name
     $data['modelScenario'] = 'dummyScenarioName';
     $response = $this->createApiCallWithRelativeUrl('create/', 'POST', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_FAILURE, $response['status']);
     $this->assertEquals('It is not allowed to set read only attribute: createdDateTime.', $response['message']);
     // Now use scenario name that allow us to set all values
     $data['modelScenario'] = 'importModel';
     $response = $this->createApiCallWithRelativeUrl('create/', 'POST', $headers, array('data' => $data));
     $response = json_decode($response, true);
     $this->assertEquals(ApiResponse::STATUS_SUCCESS, $response['status']);
     RedBeanModel::forgetAll();
     $account = Account::getById($response['data']['id']);
     $this->assertEquals($account->name, $response['data']['name']);
     $this->assertEquals($account->createdDateTime, $response['data']['createdDateTime']);
 }
 /**
  * There is a special way you can import rateToBase and currencyCode for an amount attribute.
  * if the column data is formatted like: $54.67__1.2__USD  then it will split the column and properly
  * handle rate and currency code.  Eventually this will be exposed in the user interface
  */
 public function testImportWithRateAndCurrencyCodeSpecified()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $account = AccountTestHelper::createAccountByNameForOwner('Account', Yii::app()->user->userModel);
     $accountId = $account->id;
     $contracts = Contract::getAll();
     $this->assertEquals(0, count($contracts));
     $import = new Import();
     $serializedData['importRulesType'] = 'Contracts';
     $serializedData['firstRowIsHeaderRow'] = true;
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('importTestIncludingRateAndCurrencyCode.csv', $import->getTempTableName(), true, Yii::getPathOfAlias('application.modules.contracts.tests.unit.files'));
     //update the ids of the account column to match the parent account.
     ZurmoRedBean::exec("update " . $import->getTempTableName() . " set column_3 = " . $account->id . " where id != 1 limit 4");
     $this->assertEquals(4, ImportDatabaseUtil::getCount($import->getTempTableName()));
     // includes header rows.
     $currency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
     $mappingData = array('column_0' => ImportMappingUtil::makeStringColumnMappingData('name'), 'column_1' => ImportMappingUtil::makeDateColumnMappingData('closeDate'), 'column_2' => ImportMappingUtil::makeIntegerColumnMappingData('description'), 'column_3' => ImportMappingUtil::makeHasOneColumnMappingData('account'), 'column_4' => ImportMappingUtil::makeDropDownColumnMappingData('stage'), 'column_5' => ImportMappingUtil::makeDropDownColumnMappingData('source'), 'column_6' => ImportMappingUtil::makeCurrencyColumnMappingData('amount', $currency));
     $importRules = ImportRulesUtil::makeImportRulesByType('Contracts');
     $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();
     //Confirm that 3 models where created.
     $contracts = Contract::getAll();
     $this->assertEquals(3, count($contracts));
     $contracts = Contract::getByName('opp1');
     $this->assertEquals(1, count($contracts[0]));
     $this->assertEquals('opp1', $contracts[0]->name);
     $this->assertEquals('1980-06-03', $contracts[0]->closeDate);
     $this->assertEquals(10, $contracts[0]->probability);
     $this->assertEquals('desc1', $contracts[0]->description);
     $this->assertTrue($contracts[0]->account->isSame($account));
     $this->assertEquals('Prospecting', $contracts[0]->stage->value);
     $this->assertEquals('Self-Generated', $contracts[0]->source->value);
     $this->assertEquals(500, $contracts[0]->amount->value);
     $this->assertEquals(1, $contracts[0]->amount->rateToBase);
     $this->assertEquals('USD', $contracts[0]->amount->currency->code);
     $contracts = Contract::getByName('opp2');
     $this->assertEquals(1, count($contracts[0]));
     $this->assertEquals('opp2', $contracts[0]->name);
     $this->assertEquals('1980-06-04', $contracts[0]->closeDate);
     $this->assertEquals(25, $contracts[0]->probability);
     $this->assertEquals('desc2', $contracts[0]->description);
     $this->assertTrue($contracts[0]->account->isSame($account));
     $this->assertEquals('Qualification', $contracts[0]->stage->value);
     $this->assertEquals('Inbound Call', $contracts[0]->source->value);
     $this->assertEquals(501, $contracts[0]->amount->value);
     // $this->assertEquals(2.7,                       $contracts[0]->amount->rateToBase);
     $this->assertEquals('GBP', $contracts[0]->amount->currency->code);
     $contracts = Contract::getByName('opp3');
     $this->assertEquals(1, count($contracts[0]));
     $this->assertEquals('opp3', $contracts[0]->name);
     $this->assertEquals('1980-06-05', $contracts[0]->closeDate);
     $this->assertEquals(50, $contracts[0]->probability);
     $this->assertEquals('desc3', $contracts[0]->description);
     $this->assertTrue($contracts[0]->account->isSame($account));
     $this->assertEquals('Negotiating', $contracts[0]->stage->value);
     $this->assertEquals('Tradeshow', $contracts[0]->source->value);
     $this->assertEquals(502, $contracts[0]->amount->value);
     // $this->assertEquals(3.2,                       $contracts[0]->amount->rateToBase);
     $this->assertEquals('EUR', $contracts[0]->amount->currency->code);
     //Confirm 10 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 2 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));
     //test the account has 3 contracts
     $account->forget();
     $account = Account::getById($accountId);
     $this->assertEquals(3, $account->contracts->count());
 }
 public function actionConvert($id)
 {
     assert('!empty($id)');
     LeadsUtil::removeFromSession(LeadsUtil::LEAD_CONVERSION_ACCOUNT_DATA_SESSION_KEY);
     $contact = Contact::getById(intval($id));
     if (!LeadsUtil::isStateALead($contact->state)) {
         $urlParams = array('/contacts/' . $this->getId() . '/details', 'id' => $contact->id);
         $this->redirect($urlParams);
     }
     $convertToAccountSetting = LeadsModule::getConvertToAccountSetting();
     $selectAccountForm = new AccountSelectForm();
     $account = new Account();
     ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($contact);
     $userCanAccessContacts = RightsUtil::canUserAccessModule('ContactsModule', Yii::app()->user->userModel);
     $userCanAccessAccounts = RightsUtil::canUserAccessModule('AccountsModule', Yii::app()->user->userModel);
     $userCanCreateAccount = RightsUtil::doesUserHaveAllowByRightName('AccountsModule', AccountsModule::RIGHT_CREATE_ACCOUNTS, Yii::app()->user->userModel);
     LeadsControllerSecurityUtil::resolveCanUserProperlyConvertLead($userCanAccessContacts, $userCanAccessAccounts, $convertToAccountSetting);
     if (isset($_POST['AccountSelectForm'])) {
         $selectAccountForm->setAttributes($_POST['AccountSelectForm']);
         if ($selectAccountForm->validate()) {
             $account = Account::getById(intval($selectAccountForm->accountId));
             $accountPostData = array('accountId' => intval($selectAccountForm->accountId), 'SelectAccount' => true);
             LeadsUtil::storeIntoSession(LeadsUtil::LEAD_CONVERSION_ACCOUNT_DATA_SESSION_KEY, $accountPostData);
             $this->redirect(array('/leads/default/convertFinal', 'id' => $contact->id));
         }
     } elseif (isset($_POST['Account'])) {
         $account = LeadsUtil::attributesToAccountWithNoPostData($contact, $account, $_POST['Account']);
         $savedSuccessfully = false;
         $modelToStringValue = null;
         $postData = $_POST['Account'];
         $controllerUtil = static::getZurmoControllerUtil();
         $account = $controllerUtil->saveModelFromPost($postData, $account, $savedSuccessfully, $modelToStringValue, true);
         if (!$account->getErrors()) {
             $accountPostData = $postData;
             $accountPostData['CreateAccount'] = true;
             LeadsUtil::storeIntoSession(LeadsUtil::LEAD_CONVERSION_ACCOUNT_DATA_SESSION_KEY, $accountPostData);
             $this->redirect(array('/leads/default/convertFinal', 'id' => $contact->id));
         }
     } elseif (isset($_POST['AccountSkip']) || $convertToAccountSetting == LeadsModule::CONVERT_NO_ACCOUNT || $convertToAccountSetting == LeadsModule::CONVERT_ACCOUNT_NOT_REQUIRED && !$userCanAccessAccounts) {
         $accountPostData = array('AccountSkip' => true);
         LeadsUtil::storeIntoSession(LeadsUtil::LEAD_CONVERSION_ACCOUNT_DATA_SESSION_KEY, $accountPostData);
         $this->redirect(array('/leads/default/convertFinal', 'id' => $contact->id));
     } else {
         $account = LeadsUtil::attributesToAccount($contact, $account);
     }
     $progressBarAndStepsView = new LeadConversionStepsAndProgressBarForWizardView();
     $convertView = new LeadConvertView($this->getId(), $this->getModule()->getId(), $contact->id, strval($contact), $selectAccountForm, $account, $convertToAccountSetting, $userCanCreateAccount);
     $view = new LeadsPageView(ZurmoDefaultViewUtil::makeTwoStandardViewsForCurrentUser($this, $progressBarAndStepsView, $convertView));
     echo $view->render();
 }
Beispiel #29
0
 /**
  * @depends testCreateDropDownWithMixedCaseAttributeName
  */
 public function testPopulateCustomAttributes()
 {
     $currencies = Currency::getAll();
     $account = new Account();
     $account->name = 'my test account';
     $account->owner = Yii::app()->user->userModel;
     $account->testCheckBox2Cstm = 0;
     $account->testCurrency2Cstm->value = 728.89;
     $account->testCurrency2Cstm->currency = $currencies[0];
     $account->testDate2Cstm = '2008-09-03';
     $account->testDate3Cstm = '2008-09-02';
     $account->testDateTime2Cstm = '2008-09-02 03:03:03';
     $account->testDateTime3Cstm = '2008-09-01 03:03:03';
     $account->testDecimal2Cstm = 45.67;
     $account->testDecimal3Cstm = 31.05;
     $account->testAirPlaneCstm->value = 'A380';
     //Dive Bomber
     $account->testInteger2Cstm = 56;
     $account->testInteger3Cstm = 21;
     $account->testPhone2Cstm = '345345234';
     $account->testPhone3Cstm = '345345221';
     $account->testAirPlanePartsCstm->value = 'Seat';
     // Wheel
     $account->testText2Cstm = 'some test stuff';
     $account->testText3Cstm = 'some test stuff 3';
     $account->testTextArea2Cstm = 'some test text area stuff';
     $account->testTextArea3Cstm = 'some test text area stuff 3';
     $account->testUrl2Cstm = 'https://www.zurmo.com';
     $account->testUrl3Cstm = 'www.zurmo.org';
     $account->playMyFavoriteSongCstm->value = 'song2';
     // song 3
     $account->testCountryCstm->value = 'bbbb';
     $account->testStateCstm->value = 'bbb2';
     $account->testCityCstm->value = 'bc2';
     $account->testEducationCstm->value = 'cccc';
     $account->testStreamCstm->value = 'ccc3';
     //Set value to Multiselect list.
     $customHobbyValue1 = new CustomFieldValue();
     $customHobbyValue1->value = 'Reading';
     $account->testHobbies1Cstm->values->add($customHobbyValue1);
     $customHobbyValue2 = new CustomFieldValue();
     $customHobbyValue2->value = 'Singing';
     $account->testHobbies2Cstm->values->add($customHobbyValue2);
     //Set value to Tagcloud.
     $customLanguageValue1 = new CustomFieldValue();
     $customLanguageValue1->value = 'English';
     $account->testLanguages1Cstm->values->add($customLanguageValue1);
     $customLanguageValue2 = new CustomFieldValue();
     $customLanguageValue2->value = 'Spanish';
     $account->testLanguages2Cstm->values->add($customLanguageValue2);
     unset($customHobbyValue1);
     unset($customHobbyValue2);
     unset($customLanguageValue1);
     unset($customLanguageValue2);
     $saved = $account->save();
     $this->assertTrue($saved);
     $accountId = $account->id;
     $account->forget();
     unset($account);
     $account = Account::getById($accountId);
     $this->assertEquals(0, $account->testCheckBox2Cstm);
     $this->assertEquals(false, (bool) $account->testCheckBox2Cstm);
     $this->assertEquals(728.89, $account->testCurrency2Cstm->value);
     $this->assertEquals(1, $account->testCurrency2Cstm->rateToBase);
     $this->assertEquals('2008-09-03', $account->testDate2Cstm);
     $this->assertEquals('2008-09-02 03:03:03', $account->testDateTime2Cstm);
     $this->assertEquals(45.67, $account->testDecimal2Cstm);
     $this->assertEquals('A380', $account->testAirPlaneCstm->value);
     $this->assertEquals(56, $account->testInteger2Cstm);
     $this->assertEquals(345345234, $account->testPhone2Cstm);
     $this->assertEquals('Seat', $account->testAirPlanePartsCstm->value);
     $this->assertEquals('some test stuff', $account->testText2Cstm);
     $this->assertEquals('some test text area stuff', $account->testTextArea2Cstm);
     $this->assertEquals('https://www.zurmo.com', $account->testUrl2Cstm);
     $this->assertEquals('http://www.zurmo.org', $account->testUrl3Cstm);
     $this->assertEquals('song2', $account->playMyFavoriteSongCstm->value);
     $this->assertContains('Writing', $account->testHobbies1Cstm->values);
     $this->assertContains('Reading', $account->testHobbies1Cstm->values);
     $this->assertContains('Singing', $account->testHobbies2Cstm->values);
     $this->assertContains('English', $account->testLanguages1Cstm->values);
     $this->assertContains('French', $account->testLanguages1Cstm->values);
     $this->assertContains('Spanish', $account->testLanguages2Cstm->values);
     $this->assertEquals('bbbb', $account->testCountryCstm->value);
     $this->assertEquals('bbb2', $account->testStateCstm->value);
     $this->assertEquals('bc2', $account->testCityCstm->value);
     $this->assertEquals('cccc', $account->testEducationCstm->value);
     $this->assertEquals('ccc3', $account->testStreamCstm->value);
     $metadata = CalculatedDerivedAttributeMetadata::getByNameAndModelClassName('testCalculatedValue', 'Account');
     $testCalculatedValue = CalculatedNumberUtil::calculateByFormulaAndModelAndResolveFormat($metadata->getFormula(), $account);
     $this->assertEquals('$774.56', $testCalculatedValue);
     unset($testCalculatedValue);
     $account->forget();
     unset($account);
     $account = Account::getById($accountId);
     //Switch values around to cover for any default value pollution on the assertions above.
     $account->testCheckBox2Cstm = 1;
     $account->testCurrency2Cstm->value = 728.92;
     $account->testCurrency2Cstm->currency = $currencies[0];
     $account->testDate2Cstm = '2008-09-04';
     $account->testDateTime2Cstm = '2008-09-03 03:03:03';
     $account->testDecimal2Cstm = 45.68;
     $account->testAirPlaneCstm->value = 'Dive Bomber';
     $account->testInteger2Cstm = 57;
     $account->testPhone2Cstm = '3453452344';
     $account->testAirPlanePartsCstm->value = 'Wheel';
     $account->testText2Cstm = 'some test stuff2';
     $account->testTextArea2Cstm = 'some test text area stuff2';
     $account->testUrl2Cstm = 'http://www.zurmo.org';
     $account->playMyFavoriteSongCstm->value = 'song3';
     $account->testCountryCstm->value = 'cccc';
     $account->testStateCstm->value = 'ccc3';
     $account->testCityCstm->value = 'ca3';
     $account->testEducationCstm->value = 'aaaa';
     $account->testStreamCstm->value = 'aaa1';
     $account->testHobbies1Cstm->values->removeAll();
     $account->testHobbies2Cstm->values->removeAll();
     $account->testLanguages1Cstm->values->removeAll();
     $account->testLanguages2Cstm->values->removeAll();
     $this->assertEquals(0, $account->testHobbies1Cstm->values->count());
     $this->assertEquals(0, $account->testHobbies2Cstm->values->count());
     $this->assertEquals(0, $account->testLanguages1Cstm->values->count());
     $this->assertEquals(0, $account->testLanguages2Cstm->values->count());
     //Set multiple value to Multiselect list.
     $customHobbyValue1 = new CustomFieldValue();
     $customHobbyValue1->value = 'Writing';
     $account->testHobbies1Cstm->values->add($customHobbyValue1);
     $customHobbyValue2 = new CustomFieldValue();
     $customHobbyValue2->value = 'Reading';
     $account->testHobbies1Cstm->values->add($customHobbyValue2);
     $customHobbyValue3 = new CustomFieldValue();
     $customHobbyValue3->value = 'Singing';
     $account->testHobbies2Cstm->values->add($customHobbyValue3);
     $customHobbyValue4 = new CustomFieldValue();
     $customHobbyValue4->value = 'Surfing';
     $account->testHobbies2Cstm->values->add($customHobbyValue4);
     $customHobbyValue5 = new CustomFieldValue();
     $customHobbyValue5->value = 'Reading';
     $account->testHobbies2Cstm->values->add($customHobbyValue5);
     //Set multiple value to Tagcloud.
     $customLanguageValue1 = new CustomFieldValue();
     $customLanguageValue1->value = 'English';
     $account->testLanguages1Cstm->values->add($customLanguageValue1);
     $customLanguageValue2 = new CustomFieldValue();
     $customLanguageValue2->value = 'Danish';
     $account->testLanguages1Cstm->values->add($customLanguageValue2);
     $customLanguageValue3 = new CustomFieldValue();
     $customLanguageValue3->value = 'Spanish';
     $account->testLanguages1Cstm->values->add($customLanguageValue3);
     $customLanguageValue4 = new CustomFieldValue();
     $customLanguageValue4->value = 'French';
     $account->testLanguages2Cstm->values->add($customLanguageValue4);
     $customLanguageValue5 = new CustomFieldValue();
     $customLanguageValue5->value = 'Spanish';
     $account->testLanguages2Cstm->values->add($customLanguageValue5);
     $saved = $account->save();
     $this->assertTrue($saved);
     $accountId = $account->id;
     $account->forget();
     unset($account);
     $account = Account::getById($accountId);
     $this->assertEquals(1, $account->testCheckBox2Cstm);
     $this->assertEquals(true, (bool) $account->testCheckBox2Cstm);
     $this->assertEquals(728.92, $account->testCurrency2Cstm->value);
     $this->assertEquals(1, $account->testCurrency2Cstm->rateToBase);
     $this->assertEquals('2008-09-04', $account->testDate2Cstm);
     $this->assertEquals('2008-09-03 03:03:03', $account->testDateTime2Cstm);
     $this->assertEquals(45.68, $account->testDecimal2Cstm);
     $this->assertEquals('Dive Bomber', $account->testAirPlaneCstm->value);
     $this->assertEquals(57, $account->testInteger2Cstm);
     $this->assertEquals(3453452344, $account->testPhone2Cstm);
     $this->assertEquals('Wheel', $account->testAirPlanePartsCstm->value);
     $this->assertEquals('some test stuff2', $account->testText2Cstm);
     $this->assertEquals('some test text area stuff2', $account->testTextArea2Cstm);
     $this->assertEquals('http://www.zurmo.org', $account->testUrl2Cstm);
     $this->assertEquals('song3', $account->playMyFavoriteSongCstm->value);
     $this->assertEquals(2, $account->testHobbies1Cstm->values->count());
     $this->assertEquals(3, $account->testHobbies2Cstm->values->count());
     $this->assertEquals(3, $account->testLanguages1Cstm->values->count());
     $this->assertEquals(2, $account->testLanguages2Cstm->values->count());
     $this->assertContains('Writing', $account->testHobbies1Cstm->values);
     $this->assertContains('Reading', $account->testHobbies1Cstm->values);
     $this->assertContains('Singing', $account->testHobbies2Cstm->values);
     $this->assertContains('Surfing', $account->testHobbies2Cstm->values);
     $this->assertContains('Reading', $account->testHobbies2Cstm->values);
     $this->assertContains('English', $account->testLanguages1Cstm->values);
     $this->assertContains('Danish', $account->testLanguages1Cstm->values);
     $this->assertContains('Spanish', $account->testLanguages1Cstm->values);
     $this->assertContains('French', $account->testLanguages2Cstm->values);
     $this->assertContains('Spanish', $account->testLanguages2Cstm->values);
     $this->assertEquals('cccc', $account->testCountryCstm->value);
     $this->assertEquals('ccc3', $account->testStateCstm->value);
     $this->assertEquals('ca3', $account->testCityCstm->value);
     $this->assertEquals('aaaa', $account->testEducationCstm->value);
     $this->assertEquals('aaa1', $account->testStreamCstm->value);
 }
 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
     }
 }