You are here

protected function MaestroEngine::doProductionAssignmentNotifications in Maestro 8.2

Same name and namespace in other branches
  1. 3.x src/Engine/MaestroEngine.php \Drupal\maestro\Engine\MaestroEngine::doProductionAssignmentNotifications()

Internal method to do production assignment notifications.

2 calls to MaestroEngine::doProductionAssignmentNotifications()
MaestroEngine::cleanQueue in src/Engine/MaestroEngine.php
CleanQueue method This is the core method used by the orchestrator to move the process forward and to determine assignments and next steps.
MaestroEngine::createProductionTask in src/Engine/MaestroEngine.php
Creates a task in the Maestro Queue table.

File

src/Engine/MaestroEngine.php, line 1821

Class

MaestroEngine
Class MaestroEngine.

Namespace

Drupal\maestro\Engine

Code

protected function doProductionAssignmentNotifications($templateMachineName, $taskMachineName, $queueID, $notificationType = 'assignment') {
  $config = \Drupal::config('maestro.settings');
  $templateTask = $this
    ->getTemplateTaskByID($templateMachineName, $taskMachineName);
  $notificationList = [];
  if (array_key_exists('notifications', $templateTask) && array_key_exists('notification_assignments', $templateTask['notifications'])) {
    $notifications = explode(',', $templateTask['notifications']['notification_assignments']);
    foreach ($notifications as $notification) {

      // We will assume that WE are the ones doing the notification.  Otherwise we're offloading to a different module to do so.
      $doNotification = TRUE;

      // [0] is to what type of entity, [1] is fixed or variable, [2] is entity or variable, [3] is type
      $thisNotification = explode(':', $notification);

      // Works for any assignment type passed in.
      if ($thisNotification[3] == $notificationType) {
        $entity = '';
        if ($thisNotification[1] == 'fixed') {
          $entity = $thisNotification[2];
        }
        elseif ($thisNotification[1] == 'variable') {

          // Variable is in [2].  Need to get its value.
          $processID = MaestroEngine::getProcessIdFromQueueId($queueID);
          $variableValue = MaestroEngine::getProcessVariable($thisNotification[2], $processID);

          // Assumption here is that these values are actual names of users or roles or whatever other entity.
          $entity = $variableValue;
        }
        else {
          $doNotification = FALSE;
        }
        if ($thisNotification[0] == 'user' && $doNotification) {

          // Load the user(s) by name and get their email addr.
          $users = explode(',', $entity);
          foreach ($users as $accountName) {
            if ($accountName != '') {
              $account = user_load_by_name($accountName);
              if ($account) {
                $notificationList[$account
                  ->get('mail')
                  ->getString()] = $account
                  ->get('mail')
                  ->getString();
              }
              else {
                throw new MaestroGeneralException('Unknown account name identified when attempting a notification.');
              }
            }
          }
        }
        elseif ($thisNotification[0] == 'role' && $doNotification) {

          // Have to parse out WHO is in the role and then get their email addr.
          $roles = explode(',', $entity);
          foreach ($roles as $roleName) {
            if ($roleName != '') {
              $ids = \Drupal::entityQuery('user')
                ->condition('status', 1)
                ->condition('roles', $roleName)
                ->execute();
              $users = User::loadMultiple($ids);
              foreach ($users as $account) {
                $notificationList[$account
                  ->get('mail')
                  ->getString()] = $account
                  ->get('mail')
                  ->getString();
              }
            }
          }
        }
        else {

          // TODO: does this need to be declared differently?  You can get the template and template task from the queueID.
          \Drupal::moduleHandler()
            ->invokeAll('maestro_production_' . $notificationType . '_notification', [
            $queueID,
            $thisNotification,
            &$notificationList,
          ]);
        }
      }
    }

    //end foreach over each assignment

    // ok, now we can check to see if we have any assignments.
    if (count($notificationList) > 0) {
      $notificationMessage = '';
      if (array_key_exists('notification_' . $notificationType, $templateTask['notifications']) && $templateTask['notifications']['notification_' . $notificationType] != '') {
        $notificationMessage = $templateTask['notifications']['notification_' . $notificationType];

        // Now do a token replacement
        // TODO: token replacement  Use hook token?  https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Utility!token.api.php/function/hook_tokens/8.2.x
        $tokenService = \Drupal::token();
        $notificationMessage = $tokenService
          ->replace($notificationMessage, [
          'maestro' => [
            'task' => $templateTask,
            'queueID' => $queueID,
          ],
        ]);
        if ($notificationType == 'assignment') {
          $subject = array_key_exists('notification_assignment_subject', $templateTask['notifications']) ? $tokenService
            ->replace($templateTask['notifications']['notification_assignment_subject'], [
            'maestro' => [
              'task' => $templateTask,
              'queueID' => $queueID,
            ],
          ]) : 'You have a new task assignment';
        }
        elseif ($notificationType == 'reminder') {
          $subject = array_key_exists('notification_reminder_subject', $templateTask['notifications']) ? $tokenService
            ->replace($templateTask['notifications']['notification_reminder_subject'], [
            'maestro' => [
              'task' => $templateTask,
              'queueID' => $queueID,
            ],
          ]) : 'You have a new task assignment';
        }
        elseif ($notificationType == 'escalation') {
          $subject = array_key_exists('notification_escalation_subject', $templateTask['notifications']) ? $tokenService
            ->replace($templateTask['notifications']['notification_escalation_subject'], [
            'maestro' => [
              'task' => $templateTask,
              'queueID' => $queueID,
            ],
          ]) : 'You have a new task assignment';
        }
      }
      else {

        // TODO: create a sitewide default email in the Maestro config.
        // Strip off a trailing slash as we're going to add it ourselves.
        $redirectionLocation = rtrim($config
          ->get('maestro_task_console_location'), '/');
        if ($redirectionLocation == '') {
          $redirectionLocation = '/taskconsole';
        }
        $queueRecord = MaestroEngine::getQueueEntryById($queueID);
        if ($notificationType == 'assignment') {
          $notificationMessage = t('A new task titled:') . ' ' . $queueRecord->task_label
            ->getString() . ' ' . t('has been assigned to you.');
          $notificationMessage .= t('Click here to go to see your tasks:') . ' ' . '<a href="' . Url::fromUserInput($redirectionLocation . '/' . $queueID, [
            'absolute' => TRUE,
          ])
            ->toString() . '">Task Console</a>';
        }
        elseif ($notificationType == 'reminder') {
          $notificationMessage = t('A reminder you have open tasks.  Please review the task:') . ' ' . $queueRecord->task_label
            ->getString();
          $notificationMessage .= t('Click here to go to your tasks:') . ' <a href="' . Url::fromUserInput($redirectionLocation . '/' . $queueID, [
            'absolute' => TRUE,
          ])
            ->toString() . '">Task Console</a>';
        }
        elseif ($notificationType == 'escalation') {
          $notificationMessage = t('An escalation for an overdue task has been generated for the task:') . ' ' . $queueRecord->task_label
            ->getString();

          // The escalation will have to have more information associated with it.. who is assigned, when it was assigned etc etc.
          // TODO:  need the list of assigned users/roles/whatever.
          $notificationMessage .= t('Assigned To:') . ' ';
          $notificationMessage .= t('Queue ID:') . ' ' . $queueID;
          $notificationMessage .= t('Process IDr:') . ' ' . $queueRecord->process_id
            ->getString();
        }
      }
      $mailManager = \Drupal::service('plugin.manager.mail');
      $langcode = \Drupal::languageManager()
        ->getCurrentLanguage()
        ->getId();
      $params = [];
      $params['queueID'] = $queueID;
      $tokenService = \Drupal::token();
      $params['subject'] = isset($subject) ? $subject : t('You have a new task assignment');
      $params['message'] = $notificationMessage;
      foreach ($notificationList as $email) {
        $result = $mailManager
          ->mail('maestro', $notificationType . '_notification', $email, $langcode, $params, NULL, TRUE);
      }
    }

    // End of actual mail sending routine.
  }
}