/**
  * Deletes all job logs where the modifiedDateTime was more than 1 week ago.
  * Runs operation in bulk to improve performance when large jobLogs are present.
  *
  * @see BaseJob::run()
  */
 public function run()
 {
     $oneWeekAgoTimeStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60 * 60 * 24 * 7);
     $sql = 'DELETE from item, joblog using joblog inner join item on ' . 'item.id = joblog.item_id where joblog.enddatetime <= "' . $oneWeekAgoTimeStamp . '"';
     ZurmoRedBean::exec($sql);
     return true;
 }
 public function testCreateAndGetMissionById()
 {
     $super = User::getByUsername('super');
     $fileModel = ZurmoTestHelper::createFileModel();
     $steven = UserTestHelper::createBasicUserWithEmailAddress('steven');
     $steven->setRight('MissionsModule', MissionsModule::RIGHT_ACCESS_MISSIONS);
     $steven->save();
     $dueStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + 10000);
     $mission = new Mission();
     $mission->owner = $super;
     $mission->takenByUser = $steven;
     $mission->dueDateTime = $dueStamp;
     $mission->description = 'My test description';
     $mission->reward = 'My test reward';
     $mission->status = Mission::STATUS_AVAILABLE;
     $mission->files->add($fileModel);
     $everyoneGroup = Group::getByName(Group::EVERYONE_GROUP_NAME);
     $mission->addPermissions($everyoneGroup, Permission::READ_WRITE);
     $this->assertTrue($mission->save());
     AllPermissionsOptimizationUtil::securableItemGivenPermissionsForGroup($mission, $everyoneGroup);
     $id = $mission->id;
     $mission->forget();
     unset($mission);
     $mission = Mission::getById($id);
     $this->assertEquals('My test description', $mission->description);
     $this->assertEquals('My test reward', $mission->reward);
     $this->assertEquals(Mission::STATUS_AVAILABLE, $mission->status);
     $this->assertEquals($super, $mission->owner);
     $this->assertEquals($steven, $mission->takenByUser);
     $this->assertEquals(1, $mission->files->count());
     $this->assertEquals($fileModel, $mission->files->offsetGet(0));
     $this->assertEquals($dueStamp, $mission->dueDateTime);
     $this->assertTrue(MissionsUtil::hasUserReadMissionLatest($mission, $super));
     $this->assertFalse(MissionsUtil::hasUserReadMissionLatest($mission, $steven));
 }
 public static function resolveAndSaveEmailMessage($textContent, $htmlContent, Item $itemOwnerModel, Contact $contact, MarketingList $marketingList, $itemId, $folderId)
 {
     $recipient = static::resolveRecipient($contact);
     if (empty($recipient)) {
         throw new MissingRecipientsForEmailMessageException();
     }
     $userId = static::resolveCurrentUserId();
     if (get_class($itemOwnerModel) == 'Campaign') {
         $ownerId = $itemOwnerModel->owner->id;
     } else {
         $ownerId = $marketingList->owner->id;
     }
     $subject = $itemOwnerModel->subject;
     $serializedData = serialize($subject);
     $headers = static::resolveHeaders($itemId);
     $nowTimestamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $emailMessageData = compact('subject', 'serializedData', 'textContent', 'htmlContent', 'userId', 'ownerId', 'headers', 'attachments', 'folderId', 'nowTimestamp');
     $attachments = array('relatedModelType' => strtolower(get_class($itemOwnerModel)), 'relatedModelId' => $itemOwnerModel->id);
     $sender = static::resolveSender($marketingList, $itemOwnerModel);
     $emailMessageData = CMap::mergeArray($emailMessageData, $sender, $recipient, $attachments);
     $emailMessageId = static::saveEmailMessageWithRelated($emailMessageData);
     if (empty($emailMessageId)) {
         throw new FailedToSaveModelException();
     }
     $emailMessage = EmailMessage::getById($emailMessageId);
     return $emailMessage;
 }
Exemple #4
0
 public function testCreateAndGetMissionById()
 {
     $super = User::getByUsername('super');
     $fileModel = ZurmoTestHelper::createFileModel();
     $steven = UserTestHelper::createBasicUser('steven');
     $dueStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + 10000);
     $mission = new Mission();
     $mission->owner = $super;
     $mission->takenByUser = $steven;
     $mission->dueDateTime = $dueStamp;
     $mission->description = 'My test description';
     $mission->reward = 'My test reward';
     $mission->status = Mission::STATUS_AVAILABLE;
     $mission->files->add($fileModel);
     $mission->addPermissions(Group::getByName(Group::EVERYONE_GROUP_NAME), Permission::READ_WRITE);
     $this->assertTrue($mission->save());
     $id = $mission->id;
     $mission->forget();
     unset($mission);
     $mission = Mission::getById($id);
     $this->assertEquals('My test description', $mission->description);
     $this->assertEquals('My test reward', $mission->reward);
     $this->assertEquals(Mission::STATUS_AVAILABLE, $mission->status);
     $this->assertEquals($super, $mission->owner);
     $this->assertEquals($steven, $mission->takenByUser);
     $this->assertEquals(1, $mission->files->count());
     $this->assertEquals($fileModel, $mission->files->offsetGet(0));
     $this->assertEquals($dueStamp, $mission->dueDateTime);
     $this->assertTrue(MissionsUtil::hasUserReadMissionLatest($mission, $super));
     $this->assertFalse(MissionsUtil::hasUserReadMissionLatest($mission, $steven));
 }
Exemple #5
0
 public function testGetByType()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $jobLog = new JobLog();
     $jobLog->type = 'Monitor';
     $jobLog->startDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $jobLog->endDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $jobLog->status = JobLog::STATUS_COMPLETE_WITHOUT_ERROR;
     $jobLog->isProcessed = false;
     $this->assertTrue($jobLog->save());
     $jobLog = new JobLog();
     $jobLog->type = 'Monitor';
     $jobLog->startDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $jobLog->endDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $jobLog->status = JobLog::STATUS_COMPLETE_WITHOUT_ERROR;
     $jobLog->isProcessed = false;
     $this->assertTrue($jobLog->save());
     $jobLog = new JobLog();
     $jobLog->type = 'SomethingElse';
     $jobLog->startDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $jobLog->endDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $jobLog->status = JobLog::STATUS_COMPLETE_WITHOUT_ERROR;
     $jobLog->isProcessed = false;
     $this->assertTrue($jobLog->save());
     $jobLogs = JobLog::getByType('Monitor');
     $this->assertCount(2, $jobLogs);
     $jobLogs = JobLog::getByType('Monitor', 1);
     $this->assertCount(1, $jobLogs);
     $jobLogs = JobLog::getByType('SomethingElse');
     $this->assertCount(1, $jobLogs);
     $jobLogs = JobLog::getByType('SomethingElse', 1);
     $this->assertCount(1, $jobLogs);
 }
 public function testGetSearchAttributesDataByModelClassNamesAndRelatedItemIds()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $modelClassNames = array('Meeting', 'Task', 'Note');
     $relationItemIds = array(5, 7, 9);
     $searchAttributesData = LatestActivitiesUtil::getSearchAttributesDataByModelClassNamesAndRelatedItemIds($modelClassNames, $relationItemIds, LatestActivitiesConfigurationForm::OWNED_BY_FILTER_ALL);
     $compareSearchAttributesData = array();
     $compareSearchAttributesData['Meeting']['clauses'] = array(1 => array('attributeName' => 'activityItems', 'relatedAttributeName' => 'id', 'operatorType' => 'oneOf', 'value' => array(5, 7, 9)), 2 => array('attributeName' => 'startDateTime', 'operatorType' => 'lessThan', 'value' => DateTimeUtil::convertTimestampToDbFormatDateTime(time())), 3 => array('attributeName' => 'logged', 'operatorType' => 'equals', 'value' => true));
     $compareSearchAttributesData['Meeting']['structure'] = '1 and (2 or 3)';
     $compareSearchAttributesData['Task']['clauses'] = array(1 => array('attributeName' => 'activityItems', 'relatedAttributeName' => 'id', 'operatorType' => 'oneOf', 'value' => array(5, 7, 9)), 2 => array('attributeName' => 'completed', 'operatorType' => 'equals', 'value' => (bool) 1));
     $compareSearchAttributesData['Task']['structure'] = '1 and 2';
     $compareSearchAttributesData['Note']['clauses'] = array(1 => array('attributeName' => 'activityItems', 'relatedAttributeName' => 'id', 'operatorType' => 'oneOf', 'value' => array(5, 7, 9)));
     $compareSearchAttributesData['Note']['structure'] = '1';
     $this->assertEquals($compareSearchAttributesData['Meeting'], $searchAttributesData[0]['Meeting']);
     $this->assertEquals($compareSearchAttributesData['Task'], $searchAttributesData[1]['Task']);
     $this->assertEquals($compareSearchAttributesData['Note'], $searchAttributesData[2]['Note']);
     $searchAttributesData = LatestActivitiesUtil::getSearchAttributesDataByModelClassNamesAndRelatedItemIds($modelClassNames, $relationItemIds, LatestActivitiesConfigurationForm::OWNED_BY_FILTER_USER);
     $compareSearchAttributesData['Meeting']['structure'] = '1 and (2 or 3) and 4';
     $compareSearchAttributesData['Meeting']['clauses'][4] = array('attributeName' => 'owner', 'operatorType' => 'equals', 'value' => Yii::app()->user->userModel->id);
     $compareSearchAttributesData['Task']['structure'] = '1 and 2 and 3';
     $compareSearchAttributesData['Task']['clauses'][3] = array('attributeName' => 'owner', 'operatorType' => 'equals', 'value' => Yii::app()->user->userModel->id);
     $compareSearchAttributesData['Note']['structure'] = '1 and 2';
     $compareSearchAttributesData['Note']['clauses'][2] = array('attributeName' => 'owner', 'operatorType' => 'equals', 'value' => Yii::app()->user->userModel->id);
     $this->assertEquals($compareSearchAttributesData['Meeting'], $searchAttributesData[0]['Meeting']);
     $this->assertEquals($compareSearchAttributesData['Task'], $searchAttributesData[1]['Task']);
     $this->assertEquals($compareSearchAttributesData['Note'], $searchAttributesData[2]['Note']);
 }
 public function testRun()
 {
     $quote = DatabaseCompatibilityUtil::getQuote();
     $super = User::getByUsername('super');
     Yii::app()->user->userModel = $super;
     $box = EmailBox::resolveAndGetByName(EmailBox::NOTIFICATIONS_NAME);
     $folder = EmailFolder::getByBoxAndType($box, EmailFolder::TYPE_SENT);
     //Create 2 sent notifications, and set one with a date over a week ago (8 days ago) for the modifiedDateTime
     $emailMessage = EmailMessageTestHelper::createDraftSystemEmail('My Email Message', $super);
     $emailMessage->folder = $folder;
     $saved = $emailMessage->save();
     $this->assertTrue($saved);
     $modifiedDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60 * 60 * 24 * 8);
     $sql = "Update item set modifieddatetime = '" . $modifiedDateTime . "' where id = " . $emailMessage->getClassId('Item');
     ZurmoRedBean::exec($sql);
     $emailMessage2 = EmailMessageTestHelper::createDraftSystemEmail('My Email Message 2', $super);
     $emailMessage2->folder = $folder;
     $saved = $emailMessage2->save();
     $this->assertTrue($saved);
     $this->assertEquals(2, EmailMessage::getCount());
     $job = new ClearSentNotificationsEmailJob();
     $this->assertTrue($job->run());
     $emailMessages = EmailMessage::getAll();
     $this->assertEquals(1, count($emailMessages));
     $this->assertEquals($emailMessage2->id, $emailMessages[0]->id);
 }
Exemple #8
0
 public function testRunAndProcessStuckJobs()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $emailAddress = new Email();
     $emailAddress->emailAddress = '*****@*****.**';
     Yii::app()->user->userModel->primaryEmail = $emailAddress;
     $saved = Yii::app()->user->userModel->save();
     $this->assertTrue($saved);
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Yii::app()->emailHelper->getSentCount());
     $monitorJob = new MonitorJob();
     $this->assertEquals(0, count(JobInProcess::getAll()));
     $this->assertEquals(0, count(Notification::getAll()));
     $jobInProcess = new JobInProcess();
     $jobInProcess->type = 'Test';
     $this->assertTrue($jobInProcess->save());
     //Should make createdDateTime long enough in past to trigger as stuck.
     $createdDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 1000);
     $sql = "Update item set createddatetime = '" . $createdDateTime . "' where id = " . $jobInProcess->getClassId('Item');
     R::exec($sql);
     $jobInProcess->forget();
     $monitorJob->run();
     $this->assertEquals(1, count(Notification::getAll()));
     //Confirm an email was sent
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(1, Yii::app()->emailHelper->getSentCount());
 }
 public function testRun()
 {
     //Create 2 jobLogs, and set one with a date over a week ago (8 days ago) for the endDateTime
     $eightDaysAgoTimestamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60 * 60 * 24 * 8);
     $jobLog = new JobLog();
     $jobLog->type = 'Monitor';
     $jobLog->startDateTime = $eightDaysAgoTimestamp;
     $jobLog->endDateTime = $eightDaysAgoTimestamp;
     $jobLog->status = JobLog::STATUS_COMPLETE_WITHOUT_ERROR;
     $jobLog->isProcessed = false;
     $jobLog->save();
     $jobLog2 = new JobLog();
     $jobLog2->type = 'ImportCleanup';
     $jobLog2->startDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $jobLog2->endDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $jobLog2->status = JobLog::STATUS_COMPLETE_WITHOUT_ERROR;
     $jobLog2->isProcessed = false;
     $jobLog2->save();
     $sql = 'select count(*) count from item';
     $row = R::getRow($sql);
     $this->assertEquals(4, $row['count']);
     $job = new JobLogCleanupJob();
     $this->assertTrue($job->run());
     $jobLogs = JobLog::getAll();
     $this->assertEquals(1, count($jobLogs));
     $this->assertEquals($jobLog2->id, $jobLogs[0]->id);
     $sql = 'select count(*) count from item';
     $row = R::getRow($sql);
     $this->assertEquals(3, $row['count']);
 }
 public function testRun()
 {
     $quote = DatabaseCompatibilityUtil::getQuote();
     //Create 2 imports, and set one with a date over a week ago (8 days ago) for the modifiedDateTime
     $import = new Import();
     $serializedData['importRulesType'] = 'ImportModelTestItem';
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('importAnalyzerTest.csv', $import->getTempTableName(), true);
     $modifiedDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60 * 60 * 24 * 8);
     $sql = "Update item set modifieddatetime = '" . $modifiedDateTime . "' where id = " . $import->getClassId('Item');
     ZurmoRedBean::exec($sql);
     $staleImportId = $import->id;
     $import2 = new Import();
     $serializedData['importRulesType'] = 'ImportModelTestItem';
     $import2->serializedData = serialize($serializedData);
     $this->assertTrue($import2->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('importAnalyzerTest.csv', $import2->getTempTableName(), true);
     $this->assertEquals(2, Import::getCount());
     $tableExists = ZurmoRedBean::$writer->doesTableExist($import->getTempTableName());
     $this->assertTrue($tableExists);
     $job = new ImportCleanupJob();
     $this->assertTrue($job->run());
     $tableExists = ZurmoRedBean::$writer->doesTableExist($import->getTempTableName());
     $this->assertFalse($tableExists);
     $imports = Import::getAll();
     $this->assertEquals(1, count($imports));
     $this->assertEquals($import2->id, $imports[0]->id);
 }
 public function testProcessAfterSaveWhenSendIsInFuture()
 {
     $this->assertEquals(0, WorkflowMessageInQueue::getCount());
     $workflow = new Workflow();
     $workflow->setId(self::$savedWorkflow->id);
     $workflow->type = Workflow::TYPE_ON_SAVE;
     $emailMessageForm = new EmailMessageForWorkflowForm('WorkflowModelTestItem', Workflow::TYPE_ON_SAVE);
     $emailMessageForm->sendAfterDurationInterval = 1;
     $emailMessageForm->sendAfterDurationType = TimeDurationUtil::DURATION_TYPE_DAY;
     $recipients = array(array('type' => WorkflowEmailMessageRecipientForm::TYPE_DYNAMIC_TRIGGERED_MODEL_USER, 'audienceType' => EmailMessageRecipient::TYPE_TO, 'dynamicUserType' => DynamicTriggeredModelUserWorkflowEmailMessageRecipientForm::DYNAMIC_USER_TYPE_CREATED_BY_USER));
     $emailMessageForm->setAttributes(array(EmailMessageForWorkflowForm::EMAIL_MESSAGE_RECIPIENTS => $recipients));
     $workflow->addEmailMessage($emailMessageForm);
     $model = new WorkflowModelTestItem();
     $model->lastName = 'lastName';
     $model->string = 'string';
     $this->assertTrue($model->save());
     $compareDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + 86400);
     WorkflowEmailMessagesUtil::processAfterSave($workflow, $model, Yii::app()->user->userModel);
     $workflowMessageInQueues = WorkflowMessageInQueue::getAll();
     $this->assertEquals(1, count($workflowMessageInQueues));
     $this->assertTrue($workflowMessageInQueues[0]->savedWorkflow->isSame(self::$savedWorkflow));
     $this->assertTrue($workflowMessageInQueues[0]->triggeredByUser->isSame(Yii::app()->user->userModel));
     $this->assertEquals($model->getClassId('Item'), $workflowMessageInQueues[0]->modelItem->getClassId('Item'));
     $this->assertEquals('WorkflowModelTestItem', $workflowMessageInQueues[0]->modelClassName);
     $this->assertEquals($compareDateTime, $workflowMessageInQueues[0]->processDateTime);
     $emailMessageData = SavedWorkflowToWorkflowAdapter::makeArrayFromEmailMessageForWorkflowFormAttributesData(array($emailMessageForm));
     $this->assertEquals(serialize($emailMessageData), $workflowMessageInQueues[0]->serializedData);
     $this->assertTrue($workflowMessageInQueues[0]->delete());
 }
Exemple #12
0
 public function testSimpleUserImportWhereAllRowsSucceed()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $tasks = Task::getAll();
     $this->assertEquals(0, count($tasks));
     $import = new Import();
     $serializedData['importRulesType'] = 'Tasks';
     $serializedData['firstRowIsHeaderRow'] = true;
     $import->serializedData = serialize($serializedData);
     $this->assertTrue($import->save());
     ImportTestHelper::createTempTableByFileNameAndTableName('simpleImportTest.csv', $import->getTempTableName(), Yii::getPathOfAlias('application.modules.tasks.tests.unit.files'));
     $this->assertEquals(4, ImportDatabaseUtil::getCount($import->getTempTableName()));
     // includes header rows.
     $mappingData = array('column_0' => ImportMappingUtil::makeStringColumnMappingData('name'), 'column_1' => ImportMappingUtil::makeDateTimeColumnMappingData('dueDateTime'), 'column_2' => ImportMappingUtil::makeDateTimeColumnMappingData('completedDateTime'), 'column_3' => ImportMappingUtil::makeBooleanColumnMappingData('completed'), 'column_4' => ImportMappingUtil::makeModelDerivedColumnMappingData('AccountDerived'), 'column_5' => ImportMappingUtil::makeModelDerivedColumnMappingData('ContactDerived'), 'column_6' => ImportMappingUtil::makeModelDerivedColumnMappingData('OpportunityDerived'), 'column_7' => ImportMappingUtil::makeTextAreaColumnMappingData('description'));
     $importRules = ImportRulesUtil::makeImportRulesByType('Tasks');
     $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);
     $actionDateTime = substr(DateTimeUtil::convertTimestampToDbFormatDateTime(time()), 0, -3);
     $messageLogger = new ImportMessageLogger();
     ImportUtil::importByDataProvider($dataProvider, $importRules, $mappingData, $importResultsUtil, new ExplicitReadWriteModelPermissions(), $messageLogger);
     $importResultsUtil->processStatusAndMessagesForEachRow();
     //Confirm that 3 models where created.
     $tasks = Task::getAll();
     $this->assertEquals(3, count($tasks));
     $tasks = Task::getByName('task1');
     $this->assertEquals(1, count($tasks[0]));
     $this->assertEquals(1, count($tasks[0]->activityItems));
     $this->assertEquals('testAccount', $tasks[0]->activityItems[0]->name);
     $this->assertEquals('Account', get_class($tasks[0]->activityItems[0]));
     $this->assertNull($tasks[0]->completed);
     $this->assertEquals($actionDateTime, substr($tasks[0]->latestDateTime, 0, -3));
     $tasks = Task::getByName('task2');
     $this->assertEquals(1, count($tasks[0]));
     $this->assertEquals(1, count($tasks[0]->activityItems));
     $this->assertEquals('testContact', $tasks[0]->activityItems[0]->firstName);
     $this->assertEquals('Contact', get_class($tasks[0]->activityItems[0]));
     $this->assertEquals(1, $tasks[0]->completed);
     $this->assertEquals('2011-12-22 06:03', substr($tasks[0]->latestDateTime, 0, -3));
     $tasks = Task::getByName('task3');
     $this->assertEquals(1, count($tasks[0]));
     $this->assertEquals(1, count($tasks[0]->activityItems));
     $this->assertEquals('testOpportunity', $tasks[0]->activityItems[0]->name);
     $this->assertEquals('Opportunity', get_class($tasks[0]->activityItems[0]));
     $this->assertNull($tasks[0]->completed);
     $this->assertEquals($actionDateTime, substr($tasks[0]->latestDateTime, 0, -3));
     //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));
 }
 /**
  * @return bool
  */
 public function generateCampaignItemsForDueCampaigns()
 {
     $nowTimestamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     // Begin Not Coding Standard
     $sql = "`generate_campaign_items`(" . Campaign::STATUS_ACTIVE . "," . Campaign::STATUS_PROCESSING . ",'{$nowTimestamp}')";
     // End Not Coding Standard
     ZurmoDatabaseCompatibilityUtil::callProcedureWithoutOuts($sql);
     Yii::app()->jobQueue->add('CampaignQueueMessagesInOutbox', 5);
     return true;
 }
 public function testInlineCreateCommentFromAjax()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $task = new Task();
     $task->name = 'aTest';
     $nowStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $this->assertTrue($task->save());
     $this->setGetArray(array('id' => $task->id, 'uniquePageId' => 'CommentInlineEditForModelView'));
     $this->runControllerWithNoExceptionsAndGetContent('tasks/default/inlineCreateCommentFromAjax');
 }
 /**
  * Only show meetings that have a start date in the past from when the mashable activity feed is run.
  * @see ActivityMashableActivityRules::resolveSearchAttributeDataForLatestActivities()
  */
 public function resolveSearchAttributeDataForLatestActivities($searchAttributeData)
 {
     assert('is_array($searchAttributeData)');
     $clausesCount = count($searchAttributeData['clauses']);
     $searchAttributeData['clauses'][$clausesCount + 1] = array('attributeName' => 'startDateTime', 'operatorType' => 'lessThan', 'value' => DateTimeUtil::convertTimestampToDbFormatDateTime(Yii::app()->timeZoneHelper->convertFromLocalTimeStampForCurrentUser(time())));
     if ($searchAttributeData['structure'] != null) {
         $searchAttributeData['structure'] .= ' and ';
     }
     $searchAttributeData['structure'] .= $clausesCount + 1;
     return $searchAttributeData;
 }
 /**
  * @param RedBeanModel $model
  */
 public function populateModel(&$model)
 {
     assert('$model instanceof Note');
     parent::populateModel($model);
     $taskRandomData = ZurmoRandomDataUtil::getRandomDataByModuleAndModelClassNames('NotesModule', 'Note');
     $description = RandomDataUtil::getRandomValueFromArray($taskRandomData['descriptions']);
     $occurredOnTimeStamp = time() - mt_rand(1, 200) * 60 * 60 * 24;
     $occurredOnDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime($occurredOnTimeStamp);
     $model->description = $description;
     $model->occurredOnDateTime = $occurredOnDateTime;
 }
 public function testCreateChecklistItemViewForTaskUsingAjax()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $task = new Task();
     $task->name = 'aTest1';
     $nowStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $this->assertTrue($task->save());
     $this->setGetArray(array('id' => $task->id, 'uniquePageId' => 'TaskCheckItemInlineEditForModelView'));
     $content = $this->runControllerWithNoExceptionsAndGetContent('tasks/taskCheckItems/inlineCreateTaskCheckItemFromAjax', false);
     $this->assertContains('TaskCheckListItem_name', $content);
 }
Exemple #18
0
 public function actionCloseTask($id)
 {
     $task = Task::getById(intval($id));
     ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($task);
     $task->completedDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $task->completed = true;
     $saved = $task->save();
     if (!$saved) {
         throw new NotSupportedException();
     }
 }
 /**
  * Given a value, attempt to convert the value to a db datetime format based on the format provided.
  * If the value does not convert properly, meaning the value is not really in the format specified, then a
  * InvalidValueToSanitizeException will be thrown.
  * @param mixed $value
  * @return sanitized value
  * @throws InvalidValueToSanitizeException
  */
 public function sanitizeValue($value)
 {
     if ($value == null) {
         return $value;
     }
     $timeStamp = CDateTimeParser::parse($value, $this->mappingRuleData['format']);
     if ($timeStamp === false || !is_int($timeStamp)) {
         throw new InvalidValueToSanitizeException(Zurmo::t('ImportModule', 'Invalid datetime format.'));
     }
     return DateTimeUtil::convertTimestampToDbFormatDateTime($timeStamp);
 }
 /**
  * @param $pageSize
  * @return array of WorkflowMessageInQueue models
  */
 public static function getModelsToProcess($pageSize)
 {
     assert('is_int($pageSize)');
     $timeStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $searchAttributeData = array();
     $searchAttributeData['clauses'] = array(1 => array('attributeName' => 'processDateTime', 'operatorType' => 'lessThan', 'value' => $timeStamp));
     $searchAttributeData['structure'] = '1';
     $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('WorkflowMessageInQueue');
     $where = RedBeanModelDataProvider::makeWhere('WorkflowMessageInQueue', $searchAttributeData, $joinTablesAdapter);
     return self::getSubset($joinTablesAdapter, null, $pageSize, $where, null);
 }
 public static function createNoteWithOwnerAndRelatedAccount($name, $owner, $account)
 {
     $occurredOnStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $note = new Note();
     $note->owner = $owner;
     $note->occurredOnDateTime = $occurredOnStamp;
     $note->description = $name;
     $note->activityItems->add($account);
     $saved = $note->save();
     assert('$saved');
     return $note;
 }
 public static function getModelsTResolveToJobQueue($pageSize, $offset, $modelClassName, $timeStamp)
 {
     assert('is_int($pageSize) || $pageSize == null');
     assert('is_int($offset)');
     assert('is_string($modelClassName)');
     assert('is_int($timeStamp)');
     $searchAttributeData = array();
     $searchAttributeData['clauses'] = array(1 => array('attributeName' => 'processDateTime', 'operatorType' => 'greaterThan', 'value' => DateTimeUtil::convertTimestampToDbFormatDateTime($timeStamp)));
     $searchAttributeData['structure'] = '1';
     $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
     $where = RedBeanModelDataProvider::makeWhere($modelClassName, $searchAttributeData, $joinTablesAdapter);
     return $modelClassName::getSubset($joinTablesAdapter, $offset, $pageSize, $where, null);
 }
Exemple #23
0
 public function testConvertTimestampToDbFormatDateTimeAndBackToTimeStamp()
 {
     $time = time();
     $timeZone = date_default_timezone_get();
     date_default_timezone_set('GMT');
     $gmtDbFormatDateTime = Yii::app()->dateFormatter->format(DatabaseCompatibilityUtil::getDateTimeFormat(), $time);
     date_default_timezone_set('America/New_York');
     $dbFormatDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime($time);
     $timeStamp = DateTimeUtil::convertDbFormatDateTimeToTimestamp($dbFormatDateTime);
     $this->assertEquals($gmtDbFormatDateTime, $dbFormatDateTime);
     $this->assertEquals($time, $timeStamp);
     date_default_timezone_set($timeZone);
 }
 /**
  * Get all imports where the modifiedDateTime was more than 1 week ago.  Then
  * delete the imports.
  * (non-PHPdoc)
  * @see BaseJob::run()
  */
 public function run()
 {
     $oneWeekAgoTimeStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60 * 60 * 24 * 7);
     $searchAttributeData = array();
     $searchAttributeData['clauses'] = array(1 => array('attributeName' => 'modifiedDateTime', 'operatorType' => 'lessThan', 'value' => $oneWeekAgoTimeStamp));
     $searchAttributeData['structure'] = '1';
     $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('Import');
     $where = RedBeanModelDataProvider::makeWhere('Import', $searchAttributeData, $joinTablesAdapter);
     $importModels = Import::getSubset($joinTablesAdapter, null, self::$pageSize, $where, null);
     foreach ($importModels as $import) {
         $import->delete();
     }
     return true;
 }
 public static function getFirstModel($user)
 {
     $industryValues = AccountListViewMergeTestHelper::getIndustryValues();
     $account = new Account();
     $account->name = 'Some Account';
     $account->owner = $user;
     assert($account->save());
     // Not Coding Standard
     $contactStates = ContactState::getByName('Qualified');
     $contact = new Contact();
     $dateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $contact->setLatestActivityDateTime($dateTime);
     $contact->owner = $user;
     $contact->title->value = 'Mr.';
     $contact->firstName = 'Super';
     $contact->lastName = 'Man';
     $contact->jobTitle = 'Superhero';
     $contact->source->value = 'Outbound';
     $contact->account = $account;
     $contact->companyName = 'Test Company';
     $contact->description = 'Some Description';
     $contact->department = 'Red Tape';
     $contact->officePhone = '1234567890';
     $contact->mobilePhone = '0987654321';
     $contact->officeFax = '1222222222';
     $contact->state = $contactStates[0];
     $contact->website = 'http://yahoo.com';
     $contact->industry->value = $industryValues[0];
     $contact->primaryEmail->emailAddress = '*****@*****.**';
     $contact->primaryEmail->optOut = 0;
     $contact->primaryEmail->isInvalid = 0;
     $contact->secondaryEmail->emailAddress = '*****@*****.**';
     $contact->secondaryEmail->optOut = 1;
     $contact->secondaryEmail->isInvalid = 1;
     $contact->primaryAddress->street1 = '129 Noodle Boulevard';
     $contact->primaryAddress->street2 = 'Apartment 6000A';
     $contact->primaryAddress->city = 'Noodleville';
     $contact->primaryAddress->state = 'New Delhi';
     $contact->primaryAddress->postalCode = '23453';
     $contact->primaryAddress->country = 'The Good Old US of A';
     $contact->secondaryAddress->street1 = '25 de Agosto 2543';
     $contact->secondaryAddress->street2 = 'Local 3';
     $contact->secondaryAddress->city = 'Ciudad de Los Fideos';
     $contact->secondaryAddress->state = 'Haryana';
     $contact->secondaryAddress->postalCode = '5123-4';
     $contact->secondaryAddress->country = 'Latinoland';
     assert($contact->save());
     // Not Coding Standard
     return $contact;
 }
Exemple #26
0
 protected function beforeSave()
 {
     if (parent::beforeSave()) {
         if (array_key_exists('completed', $this->originalAttributeValues) && $this->completed == true) {
             if ($this->completedDateTime == null) {
                 $this->completedDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
             }
             $this->unrestrictedSet('latestDateTime', $this->completedDateTime);
         }
         return true;
     } else {
         return false;
     }
 }
 public function testRun()
 {
     $quote = DatabaseCompatibilityUtil::getQuote();
     //Create 2 export items, and set one with a date over a week ago (8 days ago) for the modifiedDateTime
     $exportItem = new ExportItem();
     $exportItem->isCompleted = 0;
     $exportItem->exportFileType = 'csv';
     $exportItem->exportFileName = 'test';
     $exportItem->modelClassName = 'Account';
     $exportItem->serializedData = serialize(array('test', 'test2'));
     $this->assertTrue($exportItem->save());
     $fileContent = new FileContent();
     $fileContent->content = 'test';
     $exportFileModel = new ExportFileModel();
     $exportFileModel->fileContent = $fileContent;
     $exportFileModel->name = $exportItem->exportFileName . ".csv";
     $exportFileModel->type = 'application/octet-stream';
     $exportFileModel->size = strlen($fileContent->content);
     $this->assertTrue($exportFileModel->save());
     $exportFileModel1Id = $exportFileModel->id;
     $exportItem->exportFileModel = $exportFileModel;
     $this->assertTrue($exportItem->save());
     $modifiedDateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60 * 60 * 24 * 8);
     $sql = "Update item set modifieddatetime = '" . $modifiedDateTime . "' where id = " . $exportItem->getClassId('Item');
     ZurmoRedBean::exec($sql);
     // Second exportItem, that shouldn't be deleted.
     $exportItem2 = new ExportItem();
     $exportItem2->isCompleted = 0;
     $exportItem2->exportFileType = 'csv';
     $exportItem2->exportFileName = 'test';
     $exportItem2->modelClassName = 'Account';
     $exportItem2->serializedData = serialize(array('test', 'test2'));
     $this->assertTrue($exportItem2->save());
     $fileContent2 = new FileContent();
     $fileContent2->content = 'test';
     $exportFileModel2 = new ExportFileModel();
     $exportFileModel2->fileContent = $fileContent2;
     $exportFileModel2->name = $exportItem->exportFileName . ".csv";
     $exportFileModel2->type = 'application/octet-stream';
     $exportFileModel2->size = strlen($fileContent->content);
     $this->assertTrue($exportFileModel2->save());
     $exportFileModel2Id = $exportFileModel2->id;
     $exportItem2->exportFileModel = $exportFileModel2;
     $this->assertTrue($exportItem2->save());
     $job = new ExportCleanupJob();
     $this->assertTrue($job->run());
     $exportItems = ExportItem::getAll();
     $this->assertEquals(1, count($exportItems));
     $this->assertEquals($exportItem2->id, $exportItems[0]->id);
 }
 /**
  * Given a value, attempt to convert the value to a db datetime format based on the format provided.
  * If the value does not convert properly, meaning the value is not really in the format specified, then a
  * InvalidValueToSanitizeException will be thrown.
  * @param string $modelClassName
  * @param string $attributeName
  * @param mixed $value
  * @param array $mappingRuleData
  */
 public static function sanitizeValue($modelClassName, $attributeName, $value, $mappingRuleData)
 {
     assert('is_string($modelClassName)');
     assert('is_string($attributeName)');
     assert('isset($mappingRuleData["format"])');
     if ($value == null) {
         return $value;
     }
     $timeStamp = CDateTimeParser::parse($value, $mappingRuleData['format']);
     if ($timeStamp === false || !is_int($timeStamp)) {
         throw new InvalidValueToSanitizeException(Zurmo::t('ImportModule', 'Invalid datetime format.'));
     }
     return DateTimeUtil::convertTimestampToDbFormatDateTime($timeStamp);
 }
 public function run()
 {
     $timestamp = time() - static::DRAFT_LIFE_TIME_IN_DAYS * 24 * 60 * 60;
     $dateTime = DateTimeUtil::convertTimestampToDbFormatDateTime($timestamp);
     $searchAttributeData = array();
     $searchAttributeData['clauses'] = array(1 => array('attributeName' => 'createdDateTime', 'operatorType' => 'lessThan', 'value' => $dateTime), 2 => array('attributeName' => 'isDraft', 'operatorType' => 'equals', 'value' => 1));
     $searchAttributeData['structure'] = '1 and 2';
     $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter('EmailTemplate');
     $where = RedBeanModelDataProvider::makeWhere('EmailTemplate', $searchAttributeData, $joinTablesAdapter);
     $models = EmailTemplate::getSubset($joinTablesAdapter, null, null, $where, null);
     foreach ($models as $model) {
         $model->delete();
     }
     return true;
 }
Exemple #30
0
 public function onModified()
 {
     if (!$this->insideOnModified) {
         $this->insideOnModified = true;
         if (!($this->unrestrictedGet('id') < 0 && $this->getScenario() == 'importModel' && array_key_exists('modifiedDateTime', $this->originalAttributeValues))) {
             $this->unrestrictedSet('modifiedDateTime', DateTimeUtil::convertTimestampToDbFormatDateTime(time()));
         }
         if (Yii::app()->user->userModel != null && Yii::app()->user->userModel->id > 0) {
             if (!($this->unrestrictedGet('id') < 0 && $this->getScenario() == 'importModel' && array_key_exists('modifiedByUser', $this->originalAttributeValues))) {
                 $this->unrestrictedSet('modifiedByUser', Yii::app()->user->userModel);
             }
         }
         $this->insideOnModified = false;
     }
 }