protected function setUp()
 {
     MockAnnotations::init($this);
     $factory = new TicketFactory('\\Diamante\\DeskBundle\\Model\\Ticket\\Ticket');
     $this->builder = new CommonTicketBuilder($factory, $this->branchRepository, $this->userService);
     $this->branchRepository->expects($this->once())->method('get')->with(self::BRANCH_ID)->will($this->returnValue($this->createBranch()));
     $this->userService->expects($this->once())->method('getByUser')->with(new User(self::ASSIGNEE_ID, User::TYPE_ORO))->will($this->returnValue($this->createAssignee()));
 }
 public function handle(MassActionHandlerArgs $args)
 {
     $iterations = 0;
     try {
         /** @var ResultRecord $result */
         foreach ($args->getResults() as $result) {
             $this->userService->resetPassword(new User($result->getValue('id'), User::TYPE_DIAMANTE));
             ++$iterations;
         }
     } catch (\Exception $e) {
         throw $e;
     }
     return $this->getResponse($args, $iterations);
 }
 public function handle(MassActionHandlerArgs $args)
 {
     $iterations = 0;
     $entities = $args->getData();
     $entities = explode(',', $entities['values']);
     try {
         foreach ($entities as $user) {
             $this->userService->resetPassword(new User($user, User::TYPE_DIAMANTE));
             ++$iterations;
         }
     } catch (\Exception $e) {
         throw $e;
     }
     return $this->getResponse($args, $iterations);
 }
 /**
  * @param string $email
  * @param int    $size
  * @param bool   $secure
  *
  * @throws \Twig_Error_Runtime
  * @return string
  */
 public function getGravatarForUser($email, $size = 58, $secure = false)
 {
     if (!$this->userService instanceof GravatarProvider) {
         throw new \Twig_Error_Runtime('Given user service is not able to provide Gravatar link');
     }
     return $this->userService->getGravatarLink($email, $size, $secure);
 }
 public function testNotifyDiamanteUser()
 {
     $ticketUniqueId = UniqueId::generate();
     $reporter = new UserAdapter(1, UserAdapter::TYPE_DIAMANTE);
     $assignee = new User();
     $assignee->setId(2);
     $assignee->setEmail('*****@*****.**');
     $author = new UserAdapter(1, UserAdapter::TYPE_DIAMANTE);
     $branch = new Branch('KEY', 'Name', 'Description');
     $ticket = new Ticket($ticketUniqueId, new TicketSequenceNumber(1), 'Subject', 'Description', $branch, $reporter, $assignee, new Source(Source::WEB), new Priority(Priority::PRIORITY_MEDIUM), new Status(Status::NEW_ONE));
     $notification = new TicketNotification((string) $ticketUniqueId, $author, 'Header', 'Subject', new \ArrayIterator(array('key' => 'value')), array('file.ext'));
     $message = new \Swift_Message();
     $this->watchersService->expects($this->once())->method('getWatchers')->will($this->returnValue([new WatcherList($ticket, 'diamante_1')]));
     $this->diamanteUserRepository->expects($this->once())->method('get')->with(1)->will($this->returnValue($assignee));
     $this->configManager->expects($this->once())->method('get')->will($this->returnValue('*****@*****.**'));
     $this->nameFormatter->expects($this->once())->method('format')->with($this->diamanteUser)->will($this->returnValue('First Last'));
     $this->mailer->expects($this->once())->method('createMessage')->will($this->returnValue($message));
     $this->ticketRepository->expects($this->once())->method('getByUniqueId')->with($ticketUniqueId)->will($this->returnValue($ticket));
     $this->userService->expects($this->once())->method('getByUser')->with($this->equalTo($author))->will($this->returnValue($this->diamanteUser));
     $this->templateResolver->expects($this->any())->method('resolve')->will($this->returnValueMap(array(array($notification, TemplateResolver::TYPE_TXT, 'txt.template.html'), array($notification, TemplateResolver::TYPE_HTML, 'html.template.html'))));
     $optionsConstraint = $this->logicalAnd($this->arrayHasKey('changes'), $this->arrayHasKey('attachments'), $this->arrayHasKey('user'), $this->arrayHasKey('header'), $this->contains($notification->getChangeList()), $this->contains($notification->getAttachments()), $this->contains('First Last'), $this->contains($notification->getHeaderText()));
     $this->twig->expects($this->at(0))->method('render')->with('txt.template.html', $optionsConstraint)->will($this->returnValue('Rendered TXT template'));
     $this->twig->expects($this->at(1))->method('render')->with('html.template.html', $optionsConstraint)->will($this->returnValue('Rendered HTML template'));
     $this->mailer->expects($this->once())->method('send')->with($this->logicalAnd($this->isInstanceOf('\\Swift_Message'), $this->callback(function (\Swift_Message $other) use($notification) {
         $to = $other->getTo();
         return false !== strpos($other->getSubject(), $notification->getSubject()) && false !== strpos($other->getSubject(), 'KEY-1') && false !== strpos($other->getBody(), 'Rendered TXT template') && array_key_exists('*****@*****.**', $to) && $other->getHeaders()->has('References') && false !== strpos($other->getHeaders()->get('References'), '*****@*****.**') && false !== strpos($other->getHeaders()->get('References'), '*****@*****.**');
     })));
     $this->messageReferenceRepository->expects($this->once())->method('findAllByTicket')->with($ticket)->will($this->returnValue(array(new MessageReference('*****@*****.**', $ticket), new MessageReference('*****@*****.**', $ticket))));
     $this->messageReferenceRepository->expects($this->once())->method('store')->with($this->logicalAnd($this->isInstanceOf('\\Diamante\\DeskBundle\\Model\\Ticket\\EmailProcessing\\MessageReference')));
     $notifier = new EmailNotifier($this->container, $this->twig, $this->mailer, $this->templateResolver, $this->ticketRepository, $this->messageReferenceRepository, $this->userService, $this->nameFormatter, $this->diamanteUserRepository, $this->configManager, $this->oroUserManager, $this->watchersService, $this->senderHost);
     $notifier->notify($notification);
 }
 /**
  * @param array $users
  * @param $type
  * @return array
  */
 protected function convertUsers(array $users, $type)
 {
     $result = array();
     foreach ($users as $user) {
         $converted = array();
         foreach ($this->properties as $property) {
             $converted[$property] = $this->getPropertyValue($property, $user);
         }
         $converted['type'] = $type;
         if (is_array($user)) {
             $converted[self::ID_FIELD_NAME] = $type . User::DELIMITER . $user[self::ID_FIELD_NAME];
         } else {
             $converted[self::ID_FIELD_NAME] = $type . User::DELIMITER . $user->getId();
         }
         if ($type === User::TYPE_DIAMANTE) {
             $converted['avatar'] = $this->userService->getGravatarLink($converted['email'], self::AVATAR_SIZE);
             $converted['type_label'] = 'customer';
         } else {
             $converted['avatar'] = $this->getPropertyValue('avatar', $user);
             $converted['type_label'] = 'admin';
         }
         $result[] = $converted;
     }
     return $result;
 }
 /**
  * @test
  */
 public function updateBranchWithAllValues()
 {
     $this->fileMock = new UploadedFileStub(self::DUMMY_LOGO_PATH, self::DUMMY_LOGO_NAME);
     $uploadedFile = $this->fileMock->move(self::DUMMY_LOGO_PATH, self::DUMMY_LOGO_NAME);
     $this->branchRepository->expects($this->once())->method('get')->will($this->returnValue($this->branch));
     $this->branch->expects($this->exactly(2))->method('getLogo')->will($this->returnValue($this->logo));
     $this->branchLogoHandler->expects($this->once())->method('remove')->with($this->equalTo($this->logo));
     $this->branchLogoHandler->expects($this->once())->method('upload')->with($this->equalTo($this->fileMock))->will($this->returnValue($uploadedFile));
     $name = 'DUMMY_NAME_UPDT';
     $description = 'DUMMY_DESC_UPDT';
     $assigneeId = 1;
     $assignee = new User($assigneeId, User::TYPE_ORO);
     $defaultAssignee = new OroUser();
     $tags = array('autocomplete' => array(), 'all' => array(), 'owner' => array());
     $this->branch->expects($this->once())->method('update')->with($this->equalTo($name), $this->equalTo($description), $this->equalTo($defaultAssignee), $this->equalTo(new Logo($uploadedFile->getFilename())));
     $this->branch->expects($this->once())->method('setTags')->with($this->equalTo($tags));
     $this->branchRepository->expects($this->once())->method('store')->with($this->equalTo($this->branch));
     $this->tagManager->expects($this->once())->method('saveTagging')->with($this->equalTo($this->branch));
     $this->authorizationService->expects($this->once())->method('isActionPermitted')->with($this->equalTo('EDIT'), $this->equalTo('Entity:DiamanteDeskBundle:Branch'))->will($this->returnValue(true));
     $this->userService->expects($this->once())->method('getbyUser')->with($this->equalTo($assignee))->will($this->returnValue($defaultAssignee));
     $command = new BranchCommand();
     $command->name = $name;
     $command->description = $description;
     $command->defaultAssignee = $assigneeId;
     $command->logoFile = $this->fileMock;
     $command->tags = $tags;
     $this->branchServiceImpl->updateBranch($command);
 }
 /**
  * Update Branch
  *
  * @param Command\BranchCommand $branchCommand
  * @return int
  */
 public function updateBranch(Command\BranchCommand $branchCommand)
 {
     $this->isGranted('EDIT', 'Entity:DiamanteDeskBundle:Branch');
     /**
      * @var $branch \Diamante\DeskBundle\Model\Branch\Branch
      */
     $branch = $this->branchRepository->get($branchCommand->id);
     if ($branchCommand->defaultAssignee) {
         $assignee = $this->userService->getByUser(new User($branchCommand->defaultAssignee, User::TYPE_ORO));
     } else {
         $assignee = null;
     }
     /** @var \Symfony\Component\HttpFoundation\File\File $file */
     $file = null;
     if ($branchCommand->isRemoveLogo()) {
         $this->branchLogoHandler->remove($branch->getLogo());
         $file = new Logo();
     } elseif ($branchCommand->logoFile) {
         if ($branch->getLogo()) {
             $this->branchLogoHandler->remove($branch->getLogo());
         }
         $logo = $this->handleLogoUpload($branchCommand->logoFile);
         $file = new Logo($logo->getFilename(), $branchCommand->logoFile->getClientOriginalName());
     }
     $branch->update($branchCommand->name, $branchCommand->description, $assignee, $file);
     $this->branchRepository->store($branch);
     //TODO: Refactor tag manipulations.
     $this->tagManager->deleteTaggingByParams($branch->getTags(), get_class($branch), $branch->getId());
     $tags = $branchCommand->tags;
     $tags['owner'] = $tags['all'];
     $branch->setTags($tags);
     $this->tagManager->saveTagging($branch);
     return $branch->getId();
 }
 /**
  * @param int $id
  * @return $this
  */
 public function setAssigneeId($id)
 {
     if (!empty($id)) {
         $assignee = $this->userService->getByUser(new User((int) $id, User::TYPE_ORO));
         $this->assignee = $assignee;
     }
     return $this;
 }
 /**
  * @param User $user
  * @return bool
  */
 public function isDiamanteUserDeleted(User $user)
 {
     if (!$user->isDiamanteUser()) {
         return false;
     }
     $diamanteUser = $this->userService->getDiamanteUser($user);
     return $diamanteUser->isDeleted();
 }
 public function testProcessWhenMessageWithReference()
 {
     $message = new Message(self::DUMMY_UNIQUE_ID, self::DUMMY_MESSAGE_ID, self::DUMMY_SUBJECT, self::DUMMY_CONTENT, $this->getDummyFrom(), self::DUMMY_MESSAGE_TO, self::DUMMY_REFERENCE);
     $diamanteUser = $this->getReporter(1);
     $this->userService->expects($this->once())->method('getUserByEmail')->with($this->equalTo(self::DUMMY_MESSAGE_FROM))->will($this->returnValue($diamanteUser));
     $reporter = $this->getReporter($diamanteUser->getId());
     $this->messageReferenceService->expects($this->once())->method('createCommentForTicket')->with($this->equalTo($message->getContent()), $reporter, $message->getReference());
     $this->ticketStrategy->process($message);
 }
 /**
  * @param Notification $notification
  *
  * @return string
  */
 private function getFormattedUserName(Notification $notification)
 {
     $user = $notification->getAuthor();
     $userId = $this->userService->verifyDiamanteUserExists($user->getEmail());
     $user = empty($userId) ? $user : new User($userId, User::TYPE_DIAMANTE);
     $user = $this->userService->getByUser($user);
     $format = $this->nameFormatter->getNameFormat();
     $name = str_replace(array('%first_name%', '%last_name%', '%prefix%', '%middle_name%', '%suffix%'), array($user->getFirstName(), $user->getLastName(), '', '', ''), $format);
     return trim($name);
 }
 /**
  * Retrieves Person (Provider or Assignee) Data based on typed ID provided
  *
  * @ApiDoc(
  *  description="Returns person data",
  *  uri="/ticket/{id}/assignee.{_format}",
  *  method="GET",
  *  resource=true,
  *  requirements={
  *       {
  *           "name"="id",
  *           "dataType"="integer",
  *           "requirement"="\d+",
  *           "description"="Ticket Id"
  *       }
  *   },
  *  statusCodes={
  *      200="Returned when successful",
  *      403="Returned when the user is not authorized to view tickets"
  *  }
  * )
  *
  * @param $id
  * @return array
  */
 public function getAssigneeForTicket($id)
 {
     $ticket = $this->loadTicket($id);
     $assignee = $ticket->getAssignee();
     $details = [];
     if (!empty($assignee)) {
         $assigneeAdapter = new User($assignee->getId(), User::TYPE_ORO);
         $details = $this->userService->fetchUserDetails($assigneeAdapter);
     }
     return $details;
 }
 /**
  * @param Notification $notification
  * @return \ArrayAccess
  */
 private function postProcessChangesList(Notification $notification)
 {
     $changes = $notification->getChangeList();
     if (isset($changes['Reporter']) && strpos($changes['Reporter'], '_')) {
         $r = $changes['Reporter'];
         $u = User::fromString($r);
         $details = $this->userService->fetchUserDetails($u);
         $changes['Reporter'] = $details->getFullName();
     }
     return $changes;
 }
 /**
  * @param int|OroUser $identity
  * @return $this
  */
 public function setAssignee($identity)
 {
     if ($identity instanceof OroUser) {
         $this->assignee = $identity;
         return $this;
     }
     if (!empty($identity)) {
         $assignee = $this->userService->getByUser(new User((int) $identity, User::TYPE_ORO));
         $this->assignee = $assignee;
     }
     return $this;
 }
 /**
  * Assign Ticket to specified User
  * @param AssigneeTicketCommand $command
  * @throws \RuntimeException if unable to load required ticket, assignee
  */
 public function assignTicket(AssigneeTicketCommand $command)
 {
     $ticket = $this->loadTicketById($command->id);
     $this->isAssigneeGranted($ticket);
     if ($command->assignee) {
         $assignee = $this->userService->getByUser(new User($command->assignee, User::TYPE_ORO));
         if (is_null($assignee)) {
             throw new \RuntimeException('Assignee loading failed, assignee not found.');
         }
         $ticket->assign($assignee);
     } else {
         $ticket->unAssign();
     }
     $this->ticketRepository->store($ticket);
     $this->dispatchEvents($ticket);
 }
 /**
  * @test
  */
 public function testTicketsAreFiltered()
 {
     $tickets = array(new Ticket(new UniqueId('unique_id'), new TicketSequenceNumber(13), self::SUBJECT, self::DESCRIPTION, $this->createBranch(), new User(1, User::TYPE_DIAMANTE), $this->createAssignee(), new Source(Source::PHONE), new Priority(Priority::PRIORITY_LOW), new Status(Status::CLOSED)), new Ticket(new UniqueId('unique_id'), new TicketSequenceNumber(12), self::SUBJECT, self::DESCRIPTION, $this->createBranch(), new User(1, User::TYPE_ORO), $this->createAssignee(), new Source(Source::PHONE), new Priority(Priority::PRIORITY_LOW), new Status(Status::CLOSED)));
     $command = new FilterTicketsCommand();
     $command->reporter = 'oro_1';
     $pagingInfo = new PagingInfo(1, new FilterPagingProperties());
     $this->ticketRepository->expects($this->once())->method('filter')->with($this->equalTo(array(array('reporter', 'eq', 'oro_1'))), $this->equalTo(new FilterPagingProperties()))->will($this->returnValue(array($tickets[1])));
     $this->apiPagingService->expects($this->once())->method('getPagingInfo')->will($this->returnValue($pagingInfo));
     $this->markTestIncomplete("This test should be completed after DIAM-553");
     $this->userService->expects($this->atLeastOnce())->method('fetchUserDetails')->with($this->createDiamanteUser())->will($this->returnValue($this->createUserDetails()));
     $retrievedTickets = $this->ticketService->listAllTickets($command);
     $this->assertNotNull($retrievedTickets);
     $this->assertTrue(is_array($retrievedTickets));
     $this->assertNotEmpty($retrievedTickets);
     $this->assertEquals($tickets[1], $retrievedTickets[0]);
 }
 /**
  * Verify permissions through Oro Platform security bundle
  *
  * @param string $operation
  * @param Comment|string $entity
  * @throws ForbiddenException
  */
 private function isGranted($operation, $entity)
 {
     // User should have ability to view all comments (except private)
     // if he is an owner of a ticket
     if ($operation === 'VIEW' && is_object($entity)) {
         if ($this->authorizationService->getLoggedUser()) {
             $loggedUser = $this->authorizationService->getLoggedUser();
             if ($loggedUser instanceof ApiUser) {
                 $loggedUser = $this->userService->getUserFromApiUser($loggedUser);
             }
             /** @var User $reporter */
             $reporter = $entity->getTicket()->getReporter();
             if ($loggedUser && $reporter && $loggedUser->getId() == $reporter->getId()) {
                 return;
             }
         }
     }
     if (!$this->authorizationService->isActionPermitted($operation, $entity)) {
         throw new ForbiddenException("Not enough permissions.");
     }
 }
 public function testNotify()
 {
     $author = new ApiUser('*****@*****.**', 'password');
     $notification = new UserNotification($author, 'Header');
     $format = '%prefix% %first_name% %middle_name% %last_name% %suffix%';
     $message = new \Swift_Message();
     $this->mailer->expects($this->once())->method('createMessage')->will($this->returnValue($message));
     $this->configManager->expects($this->once())->method('get')->will($this->returnValue('Mike The Bot'));
     $this->nameFormatter->expects($this->any())->method('format')->with($this->diamanteUser)->will($this->returnValue('First Last'));
     $this->userService->expects($this->once())->method('verifyDiamanteUserExists')->with($this->equalTo($author->getEmail()))->will($this->returnValue(1));
     $this->userService->expects($this->once())->method('getByUser')->with($this->equalTo(new UserAdapter(1, UserAdapter::TYPE_DIAMANTE)))->will($this->returnValue($this->diamanteUser));
     $this->nameFormatter->expects($this->once())->method('getNameFormat')->will($this->returnValue($format));
     $this->templateResolver->expects($this->any())->method('resolve')->will($this->returnValueMap(array(array($notification, TemplateResolver::TYPE_TXT, 'txt.template.html'), array($notification, TemplateResolver::TYPE_HTML, 'html.template.html'))));
     $optionsConstraint = $this->logicalAnd($this->arrayHasKey('user'), $this->arrayHasKey('header'), $this->contains('First  Last'), $this->contains($notification->getHeaderText()));
     $this->twig->expects($this->at(0))->method('render')->with('txt.template.html', $optionsConstraint)->will($this->returnValue('Rendered TXT template'));
     $this->twig->expects($this->at(1))->method('render')->with('html.template.html', $optionsConstraint)->will($this->returnValue('Rendered HTML template'));
     $this->mailer->expects($this->once())->method('send')->with($this->logicalAnd($this->isInstanceOf('\\Swift_Message'), $this->callback(function (\Swift_Message $other) use($notification) {
         $to = $other->getTo();
         return false !== strpos($other->getBody(), 'Rendered TXT template') && array_key_exists('*****@*****.**', $to);
     })));
     $notifier = new EmailNotifier($this->twig, $this->mailer, $this->templateResolver, $this->userService, $this->nameFormatter, $this->configManager, $this->senderEmail);
     $notifier->notify($notification);
 }
 /**
  * @param Comment $comment
  * @return array
  */
 private function getCommentData(Comment $comment)
 {
     $data = ['attachments' => $comment->getAttachments(), 'content' => $comment->getContent(), 'created_at' => $comment->getCreatedAt(), 'updated_at' => $comment->getUpdatedAt(), 'id' => $comment->getId(), 'private' => $comment->isPrivate(), 'ticket' => $comment->getTicketId(), 'author' => $this->userService->fetchUserDetails($comment->getAuthor())];
     return $data;
 }
 /**
  * Retrieves comment author data based on typed ID provided
  *
  * @ApiDoc(
  *  description="Returns person data",
  *  uri="/comment/{id}/author.{_format}",
  *  method="GET",
  *  resource=true,
  *  requirements={
  *       {
  *           "name"="id",
  *           "dataType"="integer",
  *           "requirement"="\d+",
  *           "description"="Author Id"
  *       }
  *   },
  *  statusCodes={
  *      200="Returned when successful",
  *      403="Returned when the user is not authorized to view tickets"
  *  }
  * )
  *
  * @param $id
  * @return array
  */
 public function getAuthorData($id)
 {
     $comment = $this->loadComment($id);
     $details = $this->userService->fetchUserDetails($comment->getAuthor());
     return $details;
 }
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage Assignee loading failed, assignee not found.
  */
 public function testAssignTicketWhenAssigneeDoesNotExist()
 {
     $currentUserId = 2;
     $assigneeId = 3;
     $this->ticketRepository->expects($this->once())->method('get')->with($this->equalTo(self::DUMMY_TICKET_ID))->will($this->returnValue($this->ticket));
     $this->authorizationService->expects($this->any())->method('getLoggedUserId')->will($this->returnValue($currentUserId));
     $this->authorizationService->expects($this->once())->method('isActionPermitted')->with($this->equalTo('EDIT'), $this->equalTo($this->ticket))->will($this->returnValue(true));
     $this->userService->expects($this->at(0))->method('getByUser')->with($this->equalTo(new User($assigneeId, User::TYPE_ORO)))->will($this->returnValue(null));
     $command = new AssigneeTicketCommand();
     $command->id = self::DUMMY_TICKET_ID;
     $command->assignee = $assigneeId;
     $this->ticketService->assignTicket($command);
 }
 /**
  * @test
  * @expectedException \RuntimeException
  * @expectedExceptionMessage User loading failed. User not found
  */
 public function testThrowsExceptionIfUserNotFound()
 {
     $userValueObject = new User(1, User::TYPE_DIAMANTE);
     $this->diamanteUserRepository->expects($this->once())->method('get')->with($this->equalTo($userValueObject->getId()))->will($this->returnValue(null));
     $this->diamanteUserService->getByUser($userValueObject);
 }