Ejemplo n.º 1
0
 public function addJob(JobInterface $job, $routingKey = self::DEFAULT_ROUTING_KEY)
 {
     $model = \Task::getById($job->getId());
     $model->broker_name = $this->name;
     $model->routing_key = $routingKey;
     return $model->save();
 }
 public function testProperlyDeletingActivityItems()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $count = ZurmoRedBean::getRow('select count(*) count from activity_item');
     $this->assertEquals(0, $count['count']);
     $account = AccountTestHelper::createAccountByNameForOwner('anAccount', Yii::app()->user->userModel);
     $deleted = $account->delete();
     $this->assertTrue($deleted);
     $count = ZurmoRedBean::getRow('select count(*) count from activity_item');
     $this->assertEquals(0, $count['count']);
     $account2 = AccountTestHelper::createAccountByNameForOwner('anAccount2', Yii::app()->user->userModel);
     $opportunity = OpportunityTestHelper::createOpportunityByNameForOwner('anOpp', Yii::app()->user->userModel);
     $task = TaskTestHelper::createTaskWithOwnerAndRelatedAccount('aTask', Yii::app()->user->userModel, $account2);
     $task->activityItems->add($opportunity);
     $this->assertTrue($task->save());
     $taskId = $task->id;
     $task->forget();
     RedBeansCache::forgetAll();
     $count = ZurmoRedBean::getRow('select count(*) count from activity_item');
     $this->assertEquals(2, $count['count']);
     $deleted = $account2->delete();
     $this->assertTrue($deleted);
     $account2->forget();
     $count = ZurmoRedBean::getRow('select count(*) count from activity_item');
     $this->assertEquals(1, $count['count']);
     RedBeansCache::forgetAll();
     //Make sure things render ok even with the account deleted.
     $content = ActivitiesUtil::renderSummaryContent(Task::getById($taskId), 'someUrl', LatestActivitiesConfigurationForm::OWNED_BY_FILTER_ALL, 'HomeModule');
 }
function renderPreviewList()
{
    $options = array('date_min' => getDateTimeFieldValue('time_start'), 'date_max' => getDateTimeFieldValue('time_end'));
    ### author
    if (intval(get('person'))) {
        $options['modified_by'] = get('person');
    }
    ### Object types
    $types = array();
    if (get('type_task') || get('type_topic')) {
        $types[] = ITEM_TASK;
    }
    if (get('type_comment')) {
        $types[] = ITEM_COMMENT;
    }
    $options['type'] = $types;
    $items = DbProjectItem::getAll($options);
    echo "<ol>";
    foreach ($items as $item) {
        if ($item->type == ITEM_COMMENT) {
            $comment = Comment::getById($item->id);
            if (get('only_spam_comments') && !isSpam($comment->name . " " . $comment->description)) {
                continue;
            }
            renderRemovalPreviewComment($comment);
        }
        if ($item->type == ITEM_TASK) {
            $task = Task::getById($item->id);
            renderRemovalPreviewTask($task);
        }
    }
    echo "</ol>";
}
Ejemplo n.º 4
0
 public function testKanbanItemSave()
 {
     $accounts = Account::getByName('anAccount');
     $user = UserTestHelper::createBasicUser('Billy');
     $task = new Task();
     $task->name = 'MyTask';
     $task->owner = $user;
     $task->requestedByUser = $user;
     $task->description = 'my test description';
     $taskCheckListItem = new TaskCheckListItem();
     $taskCheckListItem->name = 'Test Check List Item';
     $task->checkListItems->add($taskCheckListItem);
     $task->activityItems->add($accounts[0]);
     $task->status = Task::STATUS_IN_PROGRESS;
     $this->assertTrue($task->save());
     $this->assertEquals(1, KanbanItem::getCount());
     $id = $task->id;
     unset($task);
     $task = Task::getById($id);
     //KanbanItem is created after saving Task
     $kanbanItems = KanbanItem::getAll();
     $this->assertCount(1, $kanbanItems);
     $kanbanItem = $kanbanItems[0];
     $this->assertEquals(KanbanItem::TYPE_IN_PROGRESS, $kanbanItem->type);
 }
Ejemplo n.º 5
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();
     }
 }
Ejemplo n.º 6
0
 /**
  *  constructor
  */
 public function __construct(Project $project)
 {
     parent::__construct();
     $this->title = __('Folders');
     if (!$project) {
         trigger_error("ListBlock_taskfolders() needs project-object as argument", E_USER_WARNING);
     }
     $this->task_folders = $project->getFolders();
     #--- render nothing if no folders ---
     if (!count($this->task_folders)) {
         $this->hidden = true;
     }
     #--- in taskView highlight current task ---
     global $PH;
     if ($PH->cur_page_id == 'taskView') {
         $task_id = get('tsk');
         $cur_task = Task::getById($task_id);
         if (!$cur_task) {
             $PH->abortWarning("invalid task-id");
             #@@@ not good inside lists / render Exception might be more appropriate
             return;
         }
         #--- use parent, if not a folder for itself ------
         if (!$cur_task->category == TCATEGORY_FOLDER) {
             $cur_task = Task::getById($cur_task->parent_task);
         }
         if ($cur_task && is_object($cur_task)) {
             $this->cur_task_id = $cur_task->id;
         }
     }
     #--- create task for project-root---
     $task_none = new Task(array('name' => "..none::"));
     $task_none->id = 0;
     $task_none->project = $project->id;
     array_unshift($this->task_folders, $task_none);
     #--- add columns --------------------------------------------------------
     $this->add_col(new ListBlockColSelect());
     $this->add_col(new ListBlockCol_TaskName(array('use_short_names' => true, 'indention' => true, 'use_collapsed' => true, 'show_toggles' => false)));
     $this->add_col(new ListBlockColMethod(array('name' => __("Tasks"), 'tooltip' => __("Number of subtasks"), 'sort' => 0, 'func' => 'getNumSubtasks', 'style' => 'right')));
     #$this->add_col( new ListBlockCol_TaskSumEfforts());
     #--- functions ----------------------------------------
     ### functions ###
     $this->add_function(new ListFunction(array('target' => $PH->getPage('taskEdit')->id, 'name' => __('Edit'), 'id' => 'taskEdit', 'icon' => 'edit', 'context_menu' => 'submit')));
     $this->add_function(new ListFunction(array('target' => $PH->getPage('taskNewFolder')->id, 'name' => __('New'), 'id' => 'taskNewFolder', 'icon' => 'new', 'tooltip' => __('Create new folder under selected task'))));
     $this->add_function(new ListFunction(array('target' => $PH->getPage('tasksMoveToFolder')->id, 'name' => __('Move selected to folder'), 'id' => 'tasksMoveToFolder', 'context_menu' => 'submit', 'dropdown_menu' => 0)));
     $this->add_function(new ListFunction(array('target' => $PH->getPage('effortNew')->id, 'name' => __('Log hours for select tasks'), 'id' => 'effortNew', 'icon' => 'loghours', 'context_menu' => 'submit')));
 }
 public function testUpdateLatestActivityDateTimeWhenATaskIsCompleted()
 {
     $taskIdAndAccountId = $this->createTaskWithRelatedAccount('account1', 'task1');
     $task = Task::getById($taskIdAndAccountId[0]);
     //update task status to STATUS_AWAITING_ACCEPTANCE, it should not update related account
     $task->status = Task::STATUS_AWAITING_ACCEPTANCE;
     $this->assertTrue($task->save());
     $account = Account::getById($taskIdAndAccountId[0]);
     $this->assertNull($account->latestActivityDateTime);
     //update task status to STATUS_COMPLETED, now it should update the related account
     $task->status = Task::STATUS_COMPLETED;
     $this->assertTrue($task->save());
     $account = Account::getById($taskIdAndAccountId[0]);
     $this->assertNotNull($account->latestActivityDateTime);
     $dateTimeAMinuteAgo = DateTimeUtil::convertTimestampToDbFormatDateTime(time() - 60);
     $dateTimeAMinuteFromNow = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + 60);
     $this->assertTrue($account->latestActivityDateTime > $dateTimeAMinuteAgo);
     $this->assertTrue($account->latestActivityDateTime < $dateTimeAMinuteFromNow);
 }
 public function testCopy()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $accounts = Account::getByName('anAccount');
     $task = new Task();
     $task->name = 'My Task';
     $task->owner = Yii::app()->user->userModel;
     $task->completedDateTime = '0000-00-00 00:00:00';
     $task->activityItems->add($accounts[0]);
     $saved = $task->save();
     $this->assertTrue($saved);
     $taskId = $task->id;
     $task->forget();
     unset($task);
     $task = Task::getById($taskId);
     $copyToTask = new Task();
     ActivityCopyModelUtil::copy($task, $copyToTask);
     $this->assertEquals('My Task', $copyToTask->name);
     $this->assertEquals(1, $copyToTask->activityItems->count());
 }
Ejemplo n.º 9
0
 /**
  * query if editable for current user
  */
 static function getEditableById($id)
 {
     if ($t = Task::getById($id)) {
         if ($p = Project::getById($t->project)) {
             if ($p->validateEditItem($t, false)) {
                 return $t;
             }
         }
     }
     return NULL;
 }
 /**
  * Process task copy
  * @param string $id
  * @return Task
  */
 private function processTaskCopy($id)
 {
     $copyToTask = new Task();
     $task = Task::getById(intval($id));
     ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($task);
     TaskActivityCopyModelUtil::copy($task, $copyToTask);
     $copyToTask = $this->attemptToSaveModelFromPost($copyToTask, null, false);
     return $copyToTask;
 }
Ejemplo n.º 11
0
 public function testAddCommentsToTask()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     $task = new Task();
     $task->name = 'MyTest2';
     $nowStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $this->assertTrue($task->save());
     $comment = new Comment();
     $comment->description = 'My Description';
     $task->comments->add($comment);
     $this->assertTrue($task->save());
     $task = Task::getById($task->id);
     $this->assertEquals(1, $task->comments->count());
     $fetchedComment = $task->comments[0];
     $this->assertEquals('My Description', $fetchedComment->description);
 }
Ejemplo n.º 12
0
/**
* save field value of an item which has been edited inplace
* and return formatted html code.
* 
* If only a chapter has been edited,  number defined in "chapter"
*/
function itemSaveField()
{
    header("Content-type: text/html; charset=utf-8");
    ### disable page caching ###
    header("Expires: -1");
    header("Cache-Control: post-check=0, pre-check=0");
    header("Pragma: no-cache");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    $value = get('value');
    if (is_null($value)) {
        return;
    }
    if (!($item_id = get('item'))) {
        print "Failure";
        return;
    }
    global $g_wiki_project;
    if (!($item = DbProjectItem::getEditableById($item_id))) {
        print "Failure";
        return;
    }
    if (!($object = DbProjectItem::getObjectById($item_id))) {
        print "Failure";
        return;
    }
    if ($item->type == ITEM_PROJECT) {
        if (!($project = Project::getVisibleById($item->id))) {
            print "Failure getting project";
            return;
        }
    } else {
        if (!($project = Project::getVisibleById($item->project))) {
            print "Failure getting project";
            return;
        }
    }
    $g_wiki_project = $project;
    $field_name = 'description';
    if (get('field')) {
        $field_name = asCleanString(get('field'));
    }
    if (!isset($object->fields[$field_name])) {
        return NULL;
    }
    require_once confGet('DIR_STREBER') . 'render/render_wiki.inc.php';
    $chapter = intVal(get('chapter'));
    ### replace complete field ###
    if (is_null($chapter)) {
        $object->{$field_name} = $value;
    } else {
        require_once confGet('DIR_STREBER') . 'render/render_wiki.inc.php';
        /**
         * split originial wiki block into chapters
         * start with headline and belonging text
         */
        $org = $object->{$field_name};
        if ($object->type == ITEM_TASK) {
            global $g_wiki_task;
            $g_wiki_task = $object;
        }
        $parts = getWikiChapters($org);
        ### replace last line return (added by textarea) ###
        if (!preg_match("/\n\$/", $value)) {
            $value .= "\n";
        }
        #$value= str_replace("\\'", "'", $value);
        #$value= str_replace('\\"', "\"", $value);
        $parts[$chapter] = $value;
        $new_wiki_text = implode('', $parts);
        $object->{$field_name} = $new_wiki_text;
    }
    ### update
    $object->update(array($field_name));
    ### mark parent of comment as changes
    if ($item->type == ITEM_COMMENT) {
        if ($parent_task = Task::getById($object->task)) {
            print "calling now changed by user";
            $parent_task->nowChangedByUser();
        }
    }
    print wiki2purehtml($object->{$field_name});
    $item->nowChangedByUser();
}
Ejemplo n.º 13
0
 function render_tr(&$obj, $style = "")
 {
     global $PH;
     $str = "";
     if (isset($obj->task)) {
         if ($task = Task::getById($obj->task)) {
             $str = $PH->getLink('taskView', $task->getShort(), array('tsk' => $task->id));
         }
     }
     print "<td><nobr>{$str}</nobr></td>";
 }
Ejemplo n.º 14
0
 /**
  * @covers resolveAndRenderTaskCardDetailsSubscribersContent
  */
 public function testResolveAndRenderTaskCardDetailsSubscribersContent()
 {
     $hellodear = UserTestHelper::createBasicUser('hellodear');
     $task = new Task();
     $task->name = 'MyCardTest';
     $task->owner = $hellodear;
     $this->assertTrue($task->save());
     $task = Task::getById($task->id);
     $user = Yii::app()->user->userModel;
     TasksUtil::addSubscriber($hellodear, $task);
     $this->assertTrue($task->save());
     $content = TasksUtil::resolveAndRenderTaskCardDetailsSubscribersContent($task);
     $this->assertContains('gravatar', $content);
     $this->assertContains('users/default/details', $content);
     $this->assertContains('hellodear', $content);
     $this->assertContains('task-owner', $content);
 }
 public function testResolveRelatedContactsAndSetLatestActivityDateTime()
 {
     $contact = ContactTestHelper::createContactByNameForOwner('contact2', Yii::app()->user->userModel);
     $this->assertNull($contact->latestActivityDateTime);
     $contact2 = ContactTestHelper::createContactByNameForOwner('contact3', Yii::app()->user->userModel);
     $this->assertNull($contact2->latestActivityDateTime);
     $task = TaskTestHelper::createTaskByNameForOwner('task3', Yii::app()->user->userModel);
     $task->activityItems->add($contact);
     $task->activityItems->add($contact2);
     $this->assertTrue($task->save());
     $this->assertNull($task->activityItems[0]->latestActivityDateTime);
     $this->assertNull($task->activityItems[1]->latestActivityDateTime);
     $taskId = $task->id;
     $contactId = $contact->id;
     $contact2Id = $contact2->id;
     $task->forget();
     $contact->forget();
     $contact2->forget();
     //Retrieve the task, so the related activity item is an Item and needs to be casted down
     $task = Task::getById($taskId);
     $dateTime = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     ContactLatestActivityDateTimeObserver::resolveRelatedModelsAndSetLatestActivityDateTime($task->activityItems, $dateTime, 'Contact');
     $task->forget();
     $contact = Contact::getById($contactId);
     $this->assertEquals($dateTime, $contact->latestActivityDateTime);
     $contact2 = Contact::getById($contact2Id);
     $this->assertEquals($dateTime, $contact2->latestActivityDateTime);
 }
Ejemplo n.º 16
0
/**
* Submit changes to a task
*
* @ingroup pages
*/
function taskEditSubmit()
{
    global $PH;
    global $auth;
    require_once confGet('DIR_STREBER') . 'db/class_taskperson.inc.php';
    /**
     * keep a list of items linking to this task, task is new
     * we have to change the linking id after(!) inserting the task
     */
    $link_items = array();
    ### temporary object or from database? ###
    $tsk_id = getOnePassedId('tsk', '', true, 'invalid id');
    if ($tsk_id == 0) {
        $task = new Task(array('id' => 0, 'project' => get('task_project')));
        $was_category = 0;
        # undefined category for new tasks
        $was_resolved_version = 0;
    } else {
        if (!($task = Task::getVisiblebyId($tsk_id))) {
            $PH->abortWarning("invalid task-id");
        }
        $was_category = $task->category;
        $was_resolved_version = $task->resolved_version;
        $task->validateEditRequestTime();
    }
    ### cancel? ###
    if (get('form_do_cancel')) {
        if (!$PH->showFromPage()) {
            $PH->show('taskView', array('tsk' => $task->id));
        }
        exit;
    }
    ### Validate integrety ###
    if (!validateFormCrc()) {
        $PH->abortWarning(__('Invalid checksum for hidden form elements'));
    }
    validateFormCaptcha(true);
    $was_a_folder = $task->category == TCATEGORY_FOLDER ? true : false;
    $was_released_as = $task->is_released;
    ### get project ###
    if (!($project = Project::getVisiblebyId($task->project))) {
        $PH->abortWarning("task without project?");
    }
    /**
     * adding comment (from quick edit) does only require view right...
     */
    $added_comment = false;
    ### check for request feedback
    if ($request_feedback = get('request_feedback')) {
        $team_members_by_nickname = array();
        foreach ($project->getProjectPeople() as $pp) {
            $team_members_by_nickname[$pp->getPerson()->nickname] = $pp->getPerson();
        }
        $requested_people = array();
        foreach (explode('\\s*,\\s*', $request_feedback) as $nickname) {
            ### now check if this nickname is a team member
            if ($nickname = trim($nickname)) {
                if (isset($team_members_by_nickname[$nickname])) {
                    $person = $team_members_by_nickname[$nickname];
                    ### update to itemperson table...
                    if ($view = ItemPerson::getAll(array('person' => $person->id, 'item' => $task->id))) {
                        $view[0]->feedback_requested_by = $auth->cur_user->id;
                        $view[0]->update();
                    } else {
                        $new_view = new ItemPerson(array('item' => $task->id, 'person' => $person->id, 'feedback_requested_by' => $auth->cur_user->id));
                        $new_view->insert();
                    }
                    $requested_people[] = "<b>" . asHtml($nickname) . "</b>";
                } else {
                    new FeedbackWarning(sprintf(__("Nickname not known in this project: %s"), "<b>" . asHtml($nickname) . "</b>"));
                }
            }
        }
        if ($requested_people) {
            new FeedbackMessage(sprintf(__('Requested feedback from: %s.'), join($requested_people, ", ")));
        }
    }
    ### only insert the comment, when comment name or description are valid
    if (get('comment_name') || get('comment_description')) {
        require_once confGet('DIR_STREBER') . 'pages/comment.inc.php';
        $valid_comment = true;
        ### new object? ###
        $comment = new Comment(array('name' => get('comment_name'), 'description' => get('comment_description'), 'project' => $task->project, 'task' => $task->id));
        validateNotSpam($comment->name . $comment->description);
        ### write to db ###
        if ($valid_comment) {
            if (!$comment->insert()) {
                new FeedbackWarning(__("Failed to add comment"));
            } else {
                ### change task update modification date ###
                if (isset($task)) {
                    ### Check if now longer new ###
                    if ($task->status == STATUS_NEW) {
                        global $auth;
                        if ($task->created < $auth->cur_user->last_login) {
                            $task->status = STATUS_OPEN;
                        }
                    }
                    $task->update(array('modified', 'status'));
                }
                $added_comment = true;
            }
        }
    }
    if ($task->id != 0 && !Task::getEditableById($task->id)) {
        if ($added_comment) {
            ### display taskView ####
            if (!$PH->showFromPage()) {
                $PH->show('home', array());
            }
            exit;
        } else {
            $PH->abortWarning(__("Not enough rights to edit task"));
        }
    }
    $task->validateEditRequestTime();
    $status_old = $task->status;
    # retrieve all possible values from post-data (with field->view_in_forms == true)
    # NOTE:
    # - this could be an security-issue.
    # @@@ TODO: as some kind of form-edit-behaviour to field-definition
    foreach ($task->fields as $f) {
        $name = $f->name;
        $f->parseForm($task);
    }
    $task->fields['parent_task']->parseForm($task);
    ### category ###
    $was_of_category = $task->category;
    if (!is_null($c = get('task_category'))) {
        global $g_tcategory_names;
        if (isset($g_tcategory_names[$c])) {
            $task->category = $c;
        } else {
            trigger_error("ignoring unknown task category '{$c}'", E_USER_NOTICE);
        }
    }
    /**
     * @@@pixtur 2006-11-17: actually this has been depreciated. is_folder updated
     * for backward compatibility only.
     */
    $task->is_folder = $task->category == TCATEGORY_FOLDER ? 1 : 0;
    ### Check if now longer new ###
    if ($status_old == $task->status && $task->status == STATUS_NEW) {
        global $auth;
        if ($task->created < $auth->cur_user->last_login) {
            $task->status = STATUS_OPEN;
        }
    }
    $assigned_people = array();
    $task_assignments = array();
    if ($task->id) {
        foreach ($task->getAssignedPeople() as $p) {
            $assigned_people[$p->id] = $p;
        }
        foreach ($task->getAssignments() as $ta) {
            $task_assignments[$ta->person] = $ta;
        }
    }
    $team = array();
    foreach ($project->getPeople() as $p) {
        $team[$p->id] = $p;
    }
    $new_task_assignments = array();
    # store assigments after(!) validation
    $forwarded = 0;
    $forward_comment = '';
    $old_task_assignments = array();
    if (isset($task_assignments)) {
        foreach ($task_assignments as $id => $t_old) {
            $id_new = get('task_assigned_to_' . $id);
            $forward_state = get('task_forward_to_' . $id);
            if ($forward_state) {
                $forwarded = 1;
            } else {
                $forwarded = 0;
            }
            $forward_comment = get('task_forward_comment_to_' . $id);
            if ($id_new === NULL) {
                log_message("failure. Can't change no longer existing assigment (person-id={$id} item-id={$t_old->id})", LOG_MESSAGE_DEBUG);
                #$PH->abortWarning("failure. Can't change no longer existing assigment",ERROR_NOTE);
                continue;
            }
            if ($id == $id_new) {
                if ($tp = TaskPerson::getTaskPeople(array('person' => $id, 'task' => $task->id))) {
                    $tp[0]->forward = $forwarded;
                    $tp[0]->forward_comment = $forward_comment;
                    $old_task_assignments[] = $tp[0];
                }
                #echo " [$id] {$team[$id]->name} still assigned<br>";
                continue;
            }
            if ($id_new == 0) {
                if (!$t_old) {
                    continue;
                }
                #echo " [$id] {$team[$id]->name} unassigned<br>";
                $t_old->delete();
                continue;
            }
            #$t_new= $task_assignments[$id_new];
            $p_new = @$team[$id_new];
            if (!isset($p_new)) {
                $PH->abortWarning("failure during form-value passing", ERROR_BUG);
            }
            #echo " [$id] assignment changed from {$team[$id]->name} to {$team[$id_new]->name}<br>";
            $t_old->comment = sprintf(__("unassigned to %s", "task-assignment comment"), $team[$id_new]->name);
            $t_old->update();
            $t_old->delete();
            $new_assignment = new TaskPerson(array('person' => $team[$id_new]->id, 'task' => $task->id, 'comment' => sprintf(__("formerly assigned to %s", "task-assigment comment"), $team[$id]->name), 'project' => $project->id, 'forward' => $forwarded, 'forward_comment' => $forward_comment));
            $new_task_assignments[] = $new_assignment;
            $link_items[] = $new_assignment;
        }
    }
    ### check new assigments ###
    $count = 0;
    while ($id_new = get('task_assign_to_' . $count)) {
        $forward_state = get('task_forward_to_' . $count);
        if ($forward_state) {
            $forwarded = 1;
        } else {
            $forwarded = 0;
        }
        $forward_comment = get('task_forward_comment_to_' . $count);
        $count++;
        ### check if already assigned ###
        if (isset($task_assignments[$id_new])) {
            if ($tp = TaskPerson::getTaskPeople(array('person' => $id_new, 'task' => $task->id))) {
                $tp[0]->forward = $forwarded;
                $tp[0]->forward_comment = $forward_comment;
                $old_task_assignments[] = $tp[0];
            }
            #new FeedbackMessage(sprintf(__("task was already assigned to %s"),$team[$id_new]->name));
        } else {
            if (!isset($team[$id_new])) {
                $PH->abortWarning("unknown person id {$id_new}", ERROR_DATASTRUCTURE);
            }
            $new_assignment = new TaskPerson(array('person' => $team[$id_new]->id, 'task' => $task->id, 'comment' => "", 'project' => $project->id, 'forward' => $forwarded, 'forward_comment' => $forward_comment));
            /**
             * BUG?
             * - inserting the new assigment before sucessfully validating the
             *   task will lead to double-entries in the database.
             */
            $new_task_assignments[] = $new_assignment;
            #$new_assignment->insert();
            $link_items[] = $new_assignment;
        }
    }
    if ($task->isOfCategory(array(TCATEGORY_VERSION, TCATEGORY_MILESTONE))) {
        if ($is_released = get('task_is_released')) {
            if (!is_null($is_released)) {
                $task->is_released = $is_released;
            }
        }
    }
    ### pub level ###
    if ($pub_level = get('task_pub_level')) {
        if ($task->id) {
            if ($pub_level > $task->getValidUserSetPublicLevels()) {
                $PH->abortWarning('invalid data', ERROR_RIGHTS);
            }
        }
        #else {
        #    #@@@ check for person create rights
        #}
        $task->pub_level = $pub_level;
    }
    ### check project ###
    if ($task->id == 0) {
        if (!($task->project = get('task_project'))) {
            $PH->abortWarning("task requires project to be set");
        }
    }
    ### get parent_task ###
    $is_ok = true;
    $parent_task = NULL;
    if ($task->parent_task) {
        $parent_task = Task::getVisibleById($task->parent_task);
    }
    ### validate ###
    if (!$task->name) {
        new FeedbackWarning(__("Task requires name"));
        $task->fields['name']->required = true;
        $task->fields['name']->invalid = true;
        $is_ok = false;
    } else {
        if ($task->id == 0) {
            $other_tasks = array();
            if ($parent_task) {
                $other_tasks = Task::getAll(array('project' => $project->id, 'parent_task' => $parent_task->id, 'status_min' => STATUS_NEW, 'status_max' => STATUS_CLOSED, 'visible_only' => false));
            } else {
                $other_tasks = Task::getAll(array('project' => $project->id, 'parent_task' => 0, 'status_min' => STATUS_NEW, 'status_max' => STATUS_CLOSED, 'visible_only' => false));
            }
            foreach ($other_tasks as $ot) {
                if (!strcasecmp($task->name, $ot->name)) {
                    $is_ok = false;
                    new FeedbackWarning(sprintf(__('Task called %s already exists'), $ot->getLink(false)));
                    break;
                }
            }
        }
    }
    ### automatically close resolved tasks ###
    if ($task->resolve_reason && $task->status < STATUS_COMPLETED) {
        $task->status = STATUS_COMPLETED;
        new FeedbackMessage(sprintf(__('Because task is resolved, its status has been changed to completed.')));
    }
    ### Check if resolved tasks should be completed ###
    if ($task->resolved_version != 0 && $task->status < STATUS_COMPLETED) {
        new FeedbackWarning(sprintf(__('Task has resolved version but is not completed?')));
        $task->fields['resolved_version']->invalid = true;
        $task->fields['status']->invalid = true;
        $is_ok = false;
    }
    ### Check if completion should be 100% ###
    if ($task->status >= STATUS_COMPLETED) {
        $task->completion = 100;
    }
    ### repeat form if invalid data ###
    if (!$is_ok) {
        $PH->show('taskEdit', NULL, $task);
        exit;
    }
    #--- write to database -----------------------------------------------------------------------
    #--- be sure parent-task is folder ---
    if ($parent_task) {
        if ($parent_task->isMilestoneOrVersion()) {
            if ($parent_task->is_folder) {
                $parent_task->is_folder = 0;
                $parent_task->update(array('is_folder'), false);
            }
            $PH->abortWarning(__("Milestones may not have sub tasks"));
        } else {
            if ($parent_task->category != TCATEGORY_FOLDER) {
                $parent_task->category = TCATEGORY_FOLDER;
                $parent_task->is_folder = 1;
                if ($parent_task->update()) {
                    new FeedbackMessage(__("Turned parent task into a folder. Note, that folders are only listed in tree"));
                } else {
                    trigger_error(__("Failed, adding to parent-task"), E_USER_WARNING);
                    $PH->abortWarning(__("Failed, adding to parent-task"));
                }
            }
        }
    }
    ### ungroup child tasks? ###
    if ($was_a_folder && $task->category != TCATEGORY_FOLDER) {
        $num_subtasks = $task->ungroupSubtasks();
        # @@@ does this work???
        /**
         * note: ALSO invisible tasks should be updated, so do not check for visibility here.
         */
        $parent = Task::getById($task->parent_task);
        $parent_str = $parent ? $parent->name : __('Project');
        if ($num_subtasks) {
            new FeedbackMessage(sprintf(__("NOTICE: Ungrouped %s subtasks to <b>%s</b>"), $num_subtasks, $parent_str));
        }
    }
    if ($task->id && !get('task_issue_report')) {
        $task_issue_report = $task->issue_report;
    } else {
        if ($task->issue_report != get('task_issue_report')) {
            trigger_error("Requesting invalid issue report id for task!", E_USER_WARNING);
            $task_issue_report = get('task_issue_report');
        } else {
            $task_issue_report = 0;
        }
    }
    ### consider issue-report? ###
    #$task_issue_report= get('task_issue_report');
    if ($task->category == TCATEGORY_BUG || isset($task_issue_report) && $task_issue_report) {
        ### new report as / temporary ###
        if ($task_issue_report == 0 || $task_issue_report == -1) {
            $issue = new Issue(array('id' => 0, 'project' => $project->id, 'task' => $task->id));
            ### querry form-information ###
            foreach ($issue->fields as $f) {
                $name = $f->name;
                $f->parseForm($issue);
            }
            global $g_reproducibility_names;
            if (!is_null($rep = get('issue_reproducibility'))) {
                if (isset($g_reproducibility_names[$rep])) {
                    $issue->reproducibility = intval($rep);
                } else {
                    $issue->reproducibility = REPRODUCIBILITY_UNDEFINED;
                }
            }
            global $g_severity_names;
            if (!is_null($sev = get('issue_severity'))) {
                if (isset($g_severity_names[$sev])) {
                    $issue->severity = intval($sev);
                } else {
                    $issue->severity = SEVERITY_UNDEFINED;
                }
            }
            ### write to db ###
            if (!$issue->insert()) {
                trigger_error("Failed to insert issue to db", E_USER_WARNING);
            } else {
                $link_items[] = $issue;
                $task->issue_report = $issue->id;
            }
        } else {
            if ($issue = Issue::getById($task_issue_report)) {
                ### querry form-information ###
                foreach ($issue->fields as $f) {
                    $name = $f->name;
                    $f->parseForm($issue);
                }
                global $g_reproducibility_names;
                if (!is_null($rep = get('issue_reproducibility'))) {
                    if (isset($g_reproducibility_names[$rep])) {
                        $issue->reproducibility = intval($rep);
                    } else {
                        $issue->reproducibility = REPRODUCIBILITY_UNDEFINED;
                    }
                }
                global $g_severity_names;
                if (!is_null($sev = get('issue_severity'))) {
                    if (isset($g_severity_names[$sev])) {
                        $issue->severity = intval($sev);
                    } else {
                        $issue->severity = SEVERITY_UNDEFINED;
                    }
                }
                ### write to db ###
                if (!$issue->update()) {
                    trigger_error("Failed to write issue to DB (id={$issue->id})", E_USER_WARNING);
                }
                if ($task->issue_report != $issue->id) {
                    # additional check, actually not necessary
                    trigger_error("issue-report as invalid id ({$issue->id}). Should be ({$task->issue_report}) Please report this bug.", E_USER_WARNING);
                }
            } else {
                trigger_error("Could not get issue with id {$task->issue_report} from database", E_USER_WARNING);
            }
        }
    }
    ### write to db ###
    if ($task->id == 0) {
        $task->insert();
        ### write task-assigments ###
        foreach ($new_task_assignments as $nta) {
            $nta->insert();
        }
        ### now we now the id of the new task, link the other items
        foreach ($link_items as $i) {
            $i->task = $task->id;
            $i->update();
        }
        new FeedbackMessage(sprintf(__("Created %s %s with ID %s", "Created <type> <name> with ID <id>..."), $task->getLabel(), $task->getLink(false), $task->id));
    } else {
        ### write task-assigments ###
        foreach ($new_task_assignments as $nta) {
            $nta->insert();
        }
        foreach ($old_task_assignments as $ota) {
            $ota->update();
        }
        new FeedbackMessage(sprintf(__("Changed %s %s with ID %s", "type,link,id"), $task->getLabel(), $task->getLink(false), $task->id));
        $task->update();
        $project->update(array(), true);
    }
    ### add any recently resolved tasks if this is a just released version  ###
    if ($task->category == TCATEGORY_VERSION && $was_category != TCATEGORY_VERSION) {
        if ($resolved_tasks = Task::getAll(array('project' => $task->project, 'status_min' => 0, 'status_max' => 10, 'resolved_version' => RESOLVED_IN_NEXT_VERSION))) {
            foreach ($resolved_tasks as $rt) {
                $rt->resolved_version = $task->id;
                $rt->update(array('resolved_version'));
            }
            new FeedbackMessage(sprintf(__('Marked %s tasks to be resolved in this version.'), count($resolved_tasks)));
        }
    }
    ### notify on change ###
    $task->nowChangedByUser();
    ### create another task ###
    if (get('create_another')) {
        ### build dummy form ###
        $newtask = new Task(array('id' => 0, 'name' => __('Name'), 'project' => $task->project, 'state' => 1, 'prio' => $task->prio, 'label' => $task->label, 'parent_task' => $task->parent_task, 'for_milestone' => $task->for_milestone, 'category' => $task->category));
        $PH->show('taskEdit', array('tsk' => $newtask->id), $newtask);
    } else {
        ### go to task, if new
        if ($tsk_id == 0) {
            $PH->show('taskView', array('tsk' => $task->id));
            exit;
        } else {
            if (!$PH->showFromPage()) {
                $PH->show('home', array());
            }
        }
    }
}
Ejemplo n.º 17
0
 /**
  * @depends testDeleteTask
  */
 public function testAutomatedCompletedDateTimeAndLatestDateTimeChanges()
 {
     Yii::app()->user->userModel = User::getByUsername('super');
     //Creating a new task that is not completed. LatestDateTime should default to now, and
     //completedDateTime should be null.
     $task = new Task();
     $task->name = 'aTest';
     $nowStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time());
     $this->assertTrue($task->save());
     $this->assertEquals(null, $task->completedDateTime);
     $this->assertEquals($nowStamp, $task->latestDateTime);
     //Modify the task. Complete the task. The CompletedDateTime should show as now.
     $task = Task::getById($task->id);
     $this->assertNull($task->completed);
     $task->completed = true;
     $this->assertEquals($nowStamp, $task->latestDateTime);
     $completedStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + 1);
     $this->assertNotEquals($nowStamp, $completedStamp);
     sleep(1);
     //Some servers are too fast and the test will fail if we don't have this.
     $this->assertTrue($task->save());
     $this->assertNotEquals($nowStamp, $task->completedDateTime);
     $this->assertNotEquals($nowStamp, $task->latestDateTime);
     $this->assertTrue($task->completedDateTime == $task->latestDateTime);
     $existingStamp = $task->completedDateTime;
     //Modify the task. CompletedDateTime and LatestDateTime should remain the same.
     $newStamp = DateTimeUtil::convertTimestampToDbFormatDateTime(time() + 1);
     $this->assertNotEquals($existingStamp, $newStamp);
     $task = Task::getById($task->id);
     $task->name = 'aNewName';
     sleep(1);
     //Some servers are too fast and the test will fail if we don't have this.
     $this->assertTrue($task->save());
     $this->assertEquals($existingStamp, $task->completedDateTime);
     $this->assertEquals($existingStamp, $task->latestDateTime);
 }
function revertDateOfCommentParent($comment)
{
    if ($parent_task = Task::getById($comment->task)) {
        revertDateOfCommentParentItem($parent_task, $comment);
    }
}
 public function testTaskAddCommentWithExtraSubscribers()
 {
     $task = new Task();
     $task->name = 'Her Task';
     $task->owner = self::$sally;
     $task->requestedByUser = self::$katie;
     $notificationSubscriber = new NotificationSubscriber();
     $notificationSubscriber->person = self::$steve;
     $notificationSubscriber->hasReadLatest = false;
     $task->notificationSubscribers->add($notificationSubscriber);
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Notification::getCount());
     $this->assertTrue($task->save());
     $this->assertEquals(1, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(1, Notification::getCount());
     EmailMessage::deleteAll();
     Notification::deleteAll();
     $taskId = $task->id;
     $task->forget();
     $task = Task::getById($taskId);
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Notification::getCount());
     //Now add comment
     $comment = new Comment();
     $comment->description = 'some comment';
     $task->comments->add($comment);
     $this->assertTrue($task->save());
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Notification::getCount());
     TasksNotificationUtil::submitTaskNotificationMessage($task, TasksNotificationUtil::TASK_NEW_COMMENT, self::$super, $comment);
     $this->assertEquals(3, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(3, Notification::getCount());
     $emailMessages = EmailMessage::getAllByFolderType(EmailFolder::TYPE_OUTBOX);
     $this->assertCount(3, $emailMessages);
     $this->assertTrue('*****@*****.**' == $emailMessages[0]->recipients[0]->toAddress || '*****@*****.**' == $emailMessages[1]->recipients[0]->toAddress || '*****@*****.**' == $emailMessages[2]->recipients[0]->toAddress);
     $this->assertTrue('*****@*****.**' == $emailMessages[0]->recipients[0]->toAddress || '*****@*****.**' == $emailMessages[1]->recipients[0]->toAddress || '*****@*****.**' == $emailMessages[2]->recipients[0]->toAddress);
     $this->assertTrue('*****@*****.**' == $emailMessages[0]->recipients[0]->toAddress || '*****@*****.**' == $emailMessages[1]->recipients[0]->toAddress || '*****@*****.**' == $emailMessages[2]->recipients[0]->toAddress);
 }
Ejemplo n.º 20
0
 function render_tr(&$obj, $style = "")
 {
     global $PH;
     $str_url = "";
     $str_name = "";
     $isDone = "";
     $html_details = "";
     $link = "";
     #if($task = Task::getVisibleById($obj->task)) {
     if ($task = Task::getById($obj->task)) {
         $str_name = asHtml($task->name);
         $str_url = $PH->getUrl('taskView', array('tsk' => $task->id));
         if ($task->status >= STATUS_COMPLETED) {
             $isDone = "class=isDone";
         }
         #if($prj = Project::getVisibleById($task->project)) {
         if ($prj = Project::getById($task->project)) {
             $link = $PH->getLink('projView', $prj->getShort(), array('prj' => $prj->id));
             $html_details .= __('in', 'very short for IN folder...') . ' ' . $link;
             if ($tmp = $task->getFolderLinks()) {
                 $html_details .= ' > ' . $tmp;
             }
         }
     }
     if ($str_name) {
         print "<td class='nowrap'><span {$isDone}><a href='{$str_url}'>{$str_name}</a></span>";
         if ($html_details) {
             print "<br><span class='sub who'>{$html_details}</span>";
         }
         print "</td>";
     } else {
         $PH->abortWarning("Could not get type of the element.", ERROR_BUG);
         print "<td>&nbsp;</td>";
     }
 }
 /**
  * @depends testUpdateStatusOnDragInKanbanView
  */
 public function testUpdateStatusInKanbanView()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     $tasks = Task::getByName('My Kanban Task');
     $task = $tasks[0];
     $taskId = $task->id;
     $this->setGetArray(array('targetStatus' => Task::STATUS_AWAITING_ACCEPTANCE, 'taskId' => $task->id, 'sourceKanbanType' => KanbanItem::TYPE_IN_PROGRESS));
     $this->runControllerWithNoExceptionsAndGetContent('tasks/default/updateStatusInKanbanView', false);
     $task = Task::getById($taskId);
     $this->assertEquals(Task::STATUS_AWAITING_ACCEPTANCE, $task->status);
 }
 function render_tr(&$obj, $style = "")
 {
     if (!isset($obj) || !$obj instanceof Project) {
         trigger_error("ListBlock->render_tr() called without valid object", E_USER_WARNING);
         return;
     }
     $sum = 0.0;
     $sum_sal = 0.0;
     $sum_all = 0.0;
     $sum_cal = 0.0;
     $diff_value = false;
     if ($effort_people = Effort::getEffortPeople(array('project' => $obj->id))) {
         foreach ($effort_people as $ep) {
             if ($person = Person::getVisibleById($ep->person)) {
                 /*if($obj->getStatus()){
                 			$sum_sal = Effort::getSumEfforts(array('project'=>$obj->id, 'person'=>$person->id, 'status'=>$obj->status));
                 		}
                 		else{*/
                 $sum_sal = Effort::getSumEfforts(array('project' => $obj->id, 'person' => $person->id));
                 #}
                 if ($sum_sal) {
                     $sum = round($sum_sal / 60 / 60, 1) * 1.0;
                     if ($pp = $obj->getProjectPeople(array('person_id' => $person->id))) {
                         if ($pp[0]->salary_per_hour) {
                             $sum_all = $sum * $pp[0]->salary_per_hour;
                         } else {
                             $sum_all = $sum * $person->salary_per_hour;
                         }
                     } else {
                         $sum_all = $sum * $person->salary_per_hour;
                     }
                     //$sum_all += ($sum * $person->salary_per_hour);
                 }
             }
         }
     }
     if ($effort_tasks = Effort::getEffortTasks(array('project' => $obj->id))) {
         foreach ($effort_tasks as $et) {
             if ($task = Task::getById($et->task)) {
                 if ($task->calculation) {
                     $sum_cal += $task->calculation;
                 }
             }
         }
     }
     if ($sum_all && $sum_cal) {
         $max_length_value = 3;
         $get_percentage = $sum_all / $sum_cal * 100;
         if ($get_percentage > 100) {
             $diff = $get_percentage - 100;
             $get_percentage = 100;
             $diff_value = true;
         }
         $show_rate = $get_percentage * $max_length_value;
         echo "<td>";
         echo "<nobr>";
         echo "<img src='" . getThemeFile("img/pixel.gif") . "' style='width:{$show_rate}px;height:12px;background-color:#f00;'>";
         if ($diff_value) {
             $show_rate = $diff * $max_length_value;
             echo "<img src='" . getThemeFile("img/pixel.gif") . "' style='width:{$show_rate}px;height:12px;background-color:#ff9900;'>";
             echo " " . round($get_percentage, 1) . "% / " . round($diff, 1) . " %";
         } else {
             echo " " . round($get_percentage, 1) . "%";
         }
         echo "</nobr>";
         echo "</td>";
     } else {
         echo "<td>-</td>";
     }
 }
 /**
  * Delete checklist item
  */
 public function actionDeleteCheckListItem($id, $taskId)
 {
     $task = Task::getById((int) $taskId);
     $taskCheckListItem = TaskCheckListItem::getById(intval($id));
     $task->checkListItems->remove($taskCheckListItem);
     $saved = $task->save();
     if (!$saved) {
         throw new FailedToSaveModelException();
     }
     $getParams = array('uniquePageId' => null, 'relatedModelId' => $task->id, 'relatedModelClassName' => 'Task', 'relatedModelRelationName' => 'checkListItems');
     $url = Yii::app()->createUrl('tasks/taskCheckItems/ajaxCheckItemListForRelatedTaskModel', $getParams);
     $this->redirect($url);
 }
 function render_tr(&$obj, $style = "")
 {
     if (!isset($obj) || !$obj instanceof Effort) {
         trigger_error("ListBlock->render_tr() called without valid object", E_USER_WARNING);
         return;
     }
     $sum = 0.0;
     if (isset($obj->task)) {
         if ($task = Task::getById($obj->task)) {
             if ($task->calculation) {
                 $sum = $task->calculation;
             }
         }
     }
     print "<td><nobr>" . $sum . "</nobr></td>";
 }
 /**
  * Add demo tasks for the project
  * @param type $project
  */
 protected static function addDemoTasks($project, $taskInputCount = 1, &$demoDataHelper)
 {
     $randomTasks = self::getRandomTasks();
     for ($i = 0; $i < count($randomTasks); $i++) {
         $task = new Task();
         $task->name = $randomTasks[$i]['name'];
         $task->owner = $demoDataHelper->getRandomByModelName('User');
         $task->requestedByUser = $demoDataHelper->getRandomByModelName('User');
         $task->completedDateTime = '0000-00-00 00:00:00';
         $task->project = $project;
         $task->status = Task::STATUS_NEW;
         $task->save();
         //Notification subscriber
         $notificationSubscriber = new NotificationSubscriber();
         $notificationSubscriber->person = $demoDataHelper->getRandomByModelName('User');
         $notificationSubscriber->hasReadLatest = false;
         //Task check list items
         $task->notificationSubscribers->add($notificationSubscriber);
         $taskCheckListItems = $randomTasks[$i]['checkListItems'];
         foreach ($taskCheckListItems as $itemKey => $name) {
             $taskCheckListItem = new TaskCheckListItem();
             $taskCheckListItem->name = $name;
             if ($itemKey * $i * rand(5, 100) % 3 == 0) {
                 $taskCheckListItem->completed = true;
             }
             $task->checkListItems->add($taskCheckListItem);
             ProjectsUtil::logTaskCheckItemEvent($task, $taskCheckListItem);
         }
         //Comments
         $commentItems = $randomTasks[$i]['comments'];
         foreach ($commentItems as $description) {
             $comment = new Comment();
             $comment->description = $description;
             $comment->setScenario('importModel');
             $comment->createdByUser = $demoDataHelper->getRandomByModelName('User');
             $task->comments->add($comment);
             ProjectsUtil::logAddCommentEvent($task, strval($comment));
         }
         //Add Super user
         $comment = new Comment();
         $comment->description = 'Versatile idea regarding the task';
         $task->comments->add($comment);
         $task->addPermissions(Group::getByName(Group::EVERYONE_GROUP_NAME), Permission::READ_WRITE_CHANGE_PERMISSIONS_CHANGE_OWNER);
         $task->save();
         $currentStatus = $task->status;
         ProjectsUtil::logAddTaskEvent($task);
         $task = Task::getById($task->id);
         $task->status = RandomDataUtil::getRandomValueFromArray(self::getTaskStatusOptions());
         $task->save();
         AllPermissionsOptimizationUtil::securableItemGivenPermissionsForGroup($task, Group::getByName(Group::EVERYONE_GROUP_NAME));
         $task->save();
         ProjectsUtil::logTaskStatusChangeEvent($task, Task::getStatusDisplayName($currentStatus), Task::getStatusDisplayName(intval($task->status)));
     }
 }
 public function testProcessForActivityItems()
 {
     $account = AccountTestHelper::createAccountByNameForOwner('testAccount', Yii::app()->user->userModel);
     $task = TaskTestHelper::createTaskWithOwnerAndRelatedAccount('testTask', Yii::app()->user->userModel, $account);
     $meeting = MeetingTestHelper::createMeetingWithOwnerAndRelatedAccount('testMeetig', Yii::app()->user->userModel, $account);
     $contact = ContactTestHelper::createContactByNameForOwner('testContact', Yii::app()->user->userModel);
     $opportunity = OpportunityTestHelper::createOpportunityByNameForOwner('testOpportunity', Yii::app()->user->userModel);
     $task->activityItems->add($contact);
     $task->activityItems->add($opportunity);
     $meeting->activityItems->add($contact);
     $meeting->activityItems->add($opportunity);
     $this->assertTrue($task->save());
     $this->assertTrue($meeting->save());
     $emailTemplate = new EmailTemplate();
     $emailTemplate->builtType = EmailTemplate::BUILT_TYPE_PASTED_HTML;
     $emailTemplate->modelClassName = 'Task';
     $emailTemplate->type = 1;
     $emailTemplate->name = 'some template';
     $emailTemplate->subject = 'some subject [[NAME]]';
     $emailTemplate->htmlContent = 'Account: [[ACCOUNT__NAME]] Contact: [[CONTACT__FIRST^NAME]] Opportunity: [[OPPORTUNITY__NAME]]';
     $emailTemplate->textContent = 'Account: [[ACCOUNT__NAME]] Contact: [[CONTACT__FIRST^NAME]] Opportunity: [[OPPORTUNITY__NAME]]';
     $this->assertTrue($emailTemplate->save());
     $message = new EmailMessageForWorkflowForm('Task', Workflow::TYPE_ON_SAVE);
     $recipients = array(array('type' => WorkflowEmailMessageRecipientForm::TYPE_DYNAMIC_TRIGGERED_MODEL_USER, 'audienceType' => EmailMessageRecipient::TYPE_TO, 'dynamicUserType' => DynamicTriggeredModelUserWorkflowEmailMessageRecipientForm::DYNAMIC_USER_TYPE_CREATED_BY_USER));
     $message->emailTemplateId = $emailTemplate->id;
     $message->sendFromType = EmailMessageForWorkflowForm::SEND_FROM_TYPE_CUSTOM;
     $message->sendFromAddress = '*****@*****.**';
     $message->sendFromName = 'Jason';
     $message->setAttributes(array(EmailMessageForWorkflowForm::EMAIL_MESSAGE_RECIPIENTS => $recipients));
     $helper = new WorkflowEmailMessageProcessingHelper($message, $task, Yii::app()->user->userModel);
     $this->assertEquals(0, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Yii::app()->emailHelper->getSentCount());
     $helper->process();
     $this->assertEquals(1, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Yii::app()->emailHelper->getSentCount());
     $emailMessages = EmailMessage::getAllByFolderType(EmailFolder::TYPE_OUTBOX);
     $this->assertEquals('some subject testTask', $emailMessages[0]->subject);
     $this->assertEquals('Account: testAccount Contact: testContact Opportunity: testOpportunity', $emailMessages[0]->content->textContent);
     $this->assertEquals('Account: testAccount Contact: testContact Opportunity: testOpportunity', $emailMessages[0]->content->htmlContent);
     $this->assertEquals('Jason', $emailMessages[0]->sender->fromName);
     $this->assertEquals('*****@*****.**', $emailMessages[0]->sender->fromAddress);
     $this->assertEquals(1, $emailMessages[0]->recipients->count());
     $this->assertEquals('*****@*****.**', $emailMessages[0]->recipients[0]->toAddress);
     $taskId = $task->id;
     $task->forgetAll();
     $task = Task::getById($taskId);
     $message = new EmailMessageForWorkflowForm('Task', Workflow::TYPE_ON_SAVE);
     $recipients = array(array('type' => WorkflowEmailMessageRecipientForm::TYPE_DYNAMIC_TRIGGERED_MODEL_USER, 'audienceType' => EmailMessageRecipient::TYPE_TO, 'dynamicUserType' => DynamicTriggeredModelUserWorkflowEmailMessageRecipientForm::DYNAMIC_USER_TYPE_CREATED_BY_USER));
     $message->emailTemplateId = $emailTemplate->id;
     $message->sendFromType = EmailMessageForWorkflowForm::SEND_FROM_TYPE_CUSTOM;
     $message->sendFromAddress = '*****@*****.**';
     $message->sendFromName = 'Jason';
     $message->setAttributes(array(EmailMessageForWorkflowForm::EMAIL_MESSAGE_RECIPIENTS => $recipients));
     $helper = new WorkflowEmailMessageProcessingHelper($message, $task, Yii::app()->user->userModel);
     $this->assertEquals(1, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Yii::app()->emailHelper->getSentCount());
     $helper->process();
     $this->assertEquals(2, Yii::app()->emailHelper->getQueuedCount());
     $this->assertEquals(0, Yii::app()->emailHelper->getSentCount());
     $emailMessages = EmailMessage::getAllByFolderType(EmailFolder::TYPE_OUTBOX);
     $this->assertEquals('some subject testTask', $emailMessages[1]->subject);
     $this->assertEquals('Account: testAccount Contact: testContact Opportunity: testOpportunity', $emailMessages[1]->content->textContent);
     $this->assertEquals('Account: testAccount Contact: testContact Opportunity: testOpportunity', $emailMessages[1]->content->htmlContent);
     $this->assertEquals('Jason', $emailMessages[1]->sender->fromName);
     $this->assertEquals('*****@*****.**', $emailMessages[1]->sender->fromAddress);
     $this->assertEquals(1, $emailMessages[1]->recipients->count());
     $this->assertEquals('*****@*****.**', $emailMessages[1]->recipients[0]->toAddress);
     $emailMessages[0]->delete();
     $emailMessages[1]->delete();
 }
 /**
  * Renders notification subscribers
  * @param string $form
  * @return string
  */
 protected function renderNotificationSubscribersContent()
 {
     $task = Task::getById($this->model->id);
     $content = '<div id="task-subscriber-box">';
     $content .= ZurmoHtml::tag('h4', array(), Zurmo::t('TasksModule', 'Who is receiving notifications'));
     $content .= '<div id="subscriberList" class="clearfix">';
     if ($task->notificationSubscribers->count() > 0) {
         $content .= TasksUtil::getTaskSubscriberData($task);
     }
     $content .= TasksUtil::getDetailSubscriptionLink($task, 0);
     $content .= '</div>';
     $content .= '</div>';
     TasksUtil::registerSubscriptionScript($this->model->id);
     TasksUtil::registerUnsubscriptionScript($this->model->id);
     return $content;
 }
 /**
  * @depends testEditOfTheTaskForTheTagCloudFieldAfterRemovingAllTagsPlacedForTasksModule
  */
 public function testEditOfTheTaskForTheCustomFieldsPlacedForTasksModule()
 {
     $super = $this->logoutCurrentUserLoginNewUserAndGetByUsername('super');
     //Retrieve the task Id.
     $task = Task::getByName('myEditTask');
     //Set the date and datetime variable values here.
     $date = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateFormat(), time());
     $dateAssert = date('Y-m-d');
     $datetime = Yii::app()->dateFormatter->format(DateTimeUtil::getLocaleDateTimeFormat(), time());
     $datetimeAssert = date('Y-m-d H:i:') . "00";
     //Get the super user, account, opportunity and contact id.
     $superUserId = $super->id;
     $superAccount = Account::getByName('superAccount');
     $superContactId = self::getModelIdByModelNameAndName('Contact', 'superContact2 superContact2son');
     $superOpportunityId = self::getModelIdByModelNameAndName('Opportunity', 'superOpp');
     $baseCurrency = Currency::getByCode(Yii::app()->currencyHelper->getBaseCode());
     $explicitReadWriteModelPermission = ExplicitReadWriteModelPermissionsUtil::MIXED_TYPE_EVERYONE_GROUP;
     //Edit the task based on the custom fields and the task id.
     $this->setGetArray(array('id' => $task[0]->id));
     $this->setPostArray(array('Task' => array('name' => 'myEditTask', 'dueDateTime' => $datetime, 'completed' => '1', 'completedDateTime' => $datetime, 'description' => 'This is edit task Description', 'owner' => array('id' => $superUserId), 'explicitReadWriteModelPermissions' => array('type' => $explicitReadWriteModelPermission), 'checkboxCstm' => '0', 'currencyCstm' => array('value' => 40, 'currency' => array('id' => $baseCurrency->id)), 'dateCstm' => $date, 'datetimeCstm' => $datetime, 'decimalCstm' => '12', 'picklistCstm' => array('value' => 'b'), 'multiselectCstm' => array('values' => array('gg', 'hh')), 'tagcloudCstm' => array('values' => array('reading', 'surfing')), 'countrylistCstm' => array('value' => 'aaaa'), 'statelistCstm' => array('value' => 'aaa1'), 'citylistCstm' => array('value' => 'ab1'), 'integerCstm' => '11', 'phoneCstm' => '259-784-2069', 'radioCstm' => array('value' => 'e'), 'textCstm' => 'This is a test Edit Text', 'textareaCstm' => 'This is a test Edit TextArea', 'urlCstm' => 'http://wwww.abc-edit.com'), 'ActivityItemForm' => array('Account' => array('id' => $superAccount[0]->id), 'Contact' => array('id' => $superContactId), 'Opportunity' => array('id' => $superOpportunityId)), 'save' => 'Save'));
     $this->runControllerWithRedirectExceptionAndGetUrl('tasks/default/edit');
     //Check the details if they are saved properly for the custom fields.
     $task = Task::getByName('myEditTask');
     //Retrieve the permission of the task.
     $explicitReadWriteModelPermissions = ExplicitReadWriteModelPermissionsUtil::makeBySecurableItem(Task::getById($task[0]->id));
     $readWritePermitables = $explicitReadWriteModelPermissions->getReadWritePermitables();
     $readOnlyPermitables = $explicitReadWriteModelPermissions->getReadOnlyPermitables();
     $this->assertEquals($task[0]->name, 'myEditTask');
     $this->assertEquals($task[0]->dueDateTime, $datetimeAssert);
     $this->assertEquals($task[0]->completed, '1');
     $this->assertEquals($task[0]->completedDateTime, $datetimeAssert);
     $this->assertEquals($task[0]->description, 'This is edit task Description');
     $this->assertEquals($task[0]->owner->id, $superUserId);
     $this->assertEquals($task[0]->activityItems->count(), 3);
     $this->assertEquals(1, count($readWritePermitables));
     $this->assertEquals(0, count($readOnlyPermitables));
     $this->assertEquals($task[0]->checkboxCstm, '0');
     $this->assertEquals($task[0]->currencyCstm->value, 40);
     $this->assertEquals($task[0]->currencyCstm->currency->id, $baseCurrency->id);
     $this->assertEquals($task[0]->dateCstm, $dateAssert);
     $this->assertEquals($task[0]->datetimeCstm, $datetimeAssert);
     $this->assertEquals($task[0]->decimalCstm, '12');
     $this->assertEquals($task[0]->picklistCstm->value, 'b');
     $this->assertEquals($task[0]->integerCstm, 11);
     $this->assertEquals($task[0]->phoneCstm, '259-784-2069');
     $this->assertEquals($task[0]->radioCstm->value, 'e');
     $this->assertEquals($task[0]->textCstm, 'This is a test Edit Text');
     $this->assertEquals($task[0]->textareaCstm, 'This is a test Edit TextArea');
     $this->assertEquals($task[0]->urlCstm, 'http://wwww.abc-edit.com');
     $this->assertEquals($task[0]->countrylistCstm->value, 'aaaa');
     $this->assertEquals($task[0]->statelistCstm->value, 'aaa1');
     $this->assertEquals($task[0]->citylistCstm->value, 'ab1');
     $this->assertContains('gg', $task[0]->multiselectCstm->values);
     $this->assertContains('hh', $task[0]->multiselectCstm->values);
     $this->assertContains('reading', $task[0]->tagcloudCstm->values);
     $this->assertContains('surfing', $task[0]->tagcloudCstm->values);
     $metadata = CalculatedDerivedAttributeMetadata::getByNameAndModelClassName('calcnumber', 'Task');
     $testCalculatedValue = CalculatedNumberUtil::calculateByFormulaAndModelAndResolveFormat($metadata->getFormula(), $task[0]);
     $this->assertEquals(132, $testCalculatedValue);
 }
Ejemplo n.º 29
0
 /**
  * Process kanban item update on button click on kanban board
  * @param int $targetStatus
  * @param int $taskId
  * @param int $sourceKanbanType
  */
 public static function processKanbanItemUpdateOnButtonAction($targetStatus, $taskId, $sourceKanbanType)
 {
     assert('is_int($targetStatus)');
     assert('is_int($taskId)');
     assert('is_int($sourceKanbanType)');
     $task = Task::getById($taskId);
     $kanbanItem = KanbanItem::getByTask($taskId);
     $targetKanbanType = null;
     if ($sourceKanbanType == KanbanItem::TYPE_SOMEDAY || $sourceKanbanType == KanbanItem::TYPE_TODO) {
         $targetKanbanType = KanbanItem::TYPE_IN_PROGRESS;
     } elseif ($sourceKanbanType == KanbanItem::TYPE_IN_PROGRESS) {
         if ($targetStatus == Task::STATUS_AWAITING_ACCEPTANCE || $targetStatus == Task::STATUS_REJECTED || $targetStatus == Task::STATUS_IN_PROGRESS) {
             $targetKanbanType = KanbanItem::TYPE_IN_PROGRESS;
         } elseif (intval($targetStatus) == Task::STATUS_COMPLETED) {
             $targetKanbanType = KanbanItem::TYPE_COMPLETED;
         }
     }
     //If kanbantype is changed, do the sort
     if ($sourceKanbanType != $targetKanbanType) {
         //Set the sort and type for target
         $sortOrder = self::resolveAndGetSortOrderForTaskOnKanbanBoard($targetKanbanType, $task);
         $kanbanItem->sortOrder = $sortOrder;
         $kanbanItem->type = $targetKanbanType;
         if (!$kanbanItem->save()) {
             throw new FailedToSaveModelException();
         }
         //Resort the source one
         if ($task->project->id > 0) {
             TasksUtil::sortKanbanColumnItems($sourceKanbanType, $task->project);
         } else {
             TasksUtil::sortKanbanColumnItems($sourceKanbanType, $task->activityItems->offsetGet(0));
         }
     }
 }