bee_webform.module 8.45 KB
Newer Older
nicola85's avatar
nicola85 committed
1 2
<?php

3
use Drupal\Component\Utility\SafeMarkup;
nicola85's avatar
nicola85 committed
4
use Drupal\Core\Form\FormStateInterface;
5 6
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
nicola85's avatar
nicola85 committed
7 8 9 10 11 12 13
use Drupal\node\Entity\Node;

/**
 * Implements hook_form_alter().
 */
function bee_webform_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (isset($form['#webform_id'])) {
14
    $webform = \Drupal\webform\Entity\Webform::load($form['#webform_id']);
acrollet's avatar
acrollet committed
15
    foreach ($webform->getElementsDecodedAndFlattened() as $element_id => $element) {
nicola85's avatar
nicola85 committed
16 17 18 19 20 21 22
      if ($element['#type'] == 'webform_bee_reservation_form') {
        $form['actions']['submit']['#submit'][] = 'bee_webform_form_submit';
      }
    }
  }
}

acrollet's avatar
acrollet committed
23 24 25
/**
 * bee_webform submission handler.
 */
nicola85's avatar
nicola85 committed
26
function bee_webform_form_submit($form, FormStateInterface $form_state) {
acrollet's avatar
acrollet committed
27 28
  $webform = \Drupal\webform\Entity\Webform::load($form['#webform_id']);
  foreach ($webform->getElementsDecodedAndFlattened() as $element_id => $element) {
nicola85's avatar
nicola85 committed
29
    if ($element['#type'] == 'webform_bee_reservation_form') {
acrollet's avatar
acrollet committed
30 31 32
      $bee_element_id = $element_id;
    }
  }
nicola85's avatar
nicola85 committed
33

acrollet's avatar
acrollet committed
34
  $value = $form_state->getValue($bee_element_id);
35

acrollet's avatar
acrollet committed
36 37
  if ($value['content_type'] && $value['start_date'] && $value['end_date'] && $value['capacity']) {
    $webform_submission = $form_state->getFormObject()->getEntity();
nicola85's avatar
nicola85 committed
38

acrollet's avatar
acrollet committed
39 40
    $start_date = $value['start_date'];
    $end_date = $value['end_date'];
nicola85's avatar
nicola85 committed
41

acrollet's avatar
acrollet committed
42
    $max_capacity = FALSE;
nicola85's avatar
nicola85 committed
43

acrollet's avatar
acrollet committed
44
    $available_units = [];
nicola85's avatar
nicola85 committed
45

acrollet's avatar
acrollet committed
46 47
    $query = \Drupal::entityQuery('node')
      ->condition('type', $value['content_type']);
nicola85's avatar
nicola85 committed
48

acrollet's avatar
acrollet committed
49 50 51 52 53 54 55
    $nids = $query->execute();
    foreach (Node::loadMultiple($nids) as $node) {
      $values = [
        'node' => $node,
        'start_date' => $start_date,
        'end_date' => $end_date,
      ];
nicola85's avatar
nicola85 committed
56

acrollet's avatar
acrollet committed
57 58 59 60 61 62 63 64 65 66 67
      if ($node_available_units = bee_webform_get_available_units($values)) {
        if (count($node_available_units) == $value['capacity']) {
          $available_units = [$node->id() => $node_available_units];
          break;
        }
        elseif (count($node_available_units) > $value['capacity']) {
          $available_units[$node->id()] = $node_available_units;
          $max_capacity = TRUE;
        }
        elseif (!$max_capacity) {
          $available_units[$node->id()] = $node_available_units;
nicola85's avatar
nicola85 committed
68
        }
acrollet's avatar
acrollet committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
      }
    }

    uasort($available_units, function($a, $b) { return count($a) - count($b); });

    $index = 0;
    $events_created = [];

    foreach ($available_units as $nid => $node_available_units) {
      if ($max_capacity && count($node_available_units) < $value['capacity']) {
        continue;
      }

      $node = Node::load($nid);

      $bee_settings = \Drupal::config('node.type.' . $node->bundle())->get('bee');
85

acrollet's avatar
acrollet committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
      if ($bee_settings['bookable_type'] == 'daily') {
        $booked_state = bat_event_load_state_by_machine_name('bee_daily_booked');
      }
      else {
        $booked_state = bat_event_load_state_by_machine_name('bee_hourly_booked');
      }

      $start_date = new \DateTime($start_date);
      $end_date = new \DateTime($end_date);

      foreach ($node_available_units as $unit) {
        if ($bee_settings['bookable_type'] == 'daily') {
          $event = bat_event_create(['type' => 'availability_daily']);
          $event_dates = [
            'value' => $start_date->format('Y-m-d\TH:i:00'),
            'end_value' => $end_date->format('Y-m-d\TH:i:00'),
          ];
          $event->set('event_dates', $event_dates);
          $event->set('event_state_reference', $booked_state->id());
105 106
        }
        else {
acrollet's avatar
acrollet committed
107 108 109 110 111 112 113
          $event = bat_event_create(['type' => 'availability_hourly']);
          $event_dates = [
            'value' => $start_date->format('Y-m-d\TH:i:00'),
            'end_value' => $end_date->format('Y-m-d\TH:i:00'),
          ];
          $event->set('event_dates', $event_dates);
          $event->set('event_state_reference', $booked_state->id());
114
        }
acrollet's avatar
acrollet committed
115 116 117 118 119 120 121 122 123

        $event->set('field_event_webform_submission', $webform_submission->id());
        $event->set('event_bat_unit_reference', $unit);
        $event->save();

        $events_created[] = $event->id();

        if (++$index == $value['capacity']) {
          break 2;
124
        }
acrollet's avatar
acrollet committed
125 126
      }
    }
127

acrollet's avatar
acrollet committed
128 129 130 131 132 133 134 135 136
    // Send email with summary of any allocations made.
    if (count($events_created) == 0) {
      $message = t("No nodes with sufficient capacity were found, therefore no reservations were created.\nTo view the submission, please go to @submission", ['@submission' => $webform_submission->url('canonical', ['absolute' => TRUE])]);
    }
    else {
      $events = bat_event_load_multiple($events_created);
      $event_links = [];
      foreach ($events as $event) {
        $event_links[] = $event->url('canonical', ['absolute' => TRUE]);
nicola85's avatar
nicola85 committed
137
      }
acrollet's avatar
acrollet committed
138 139

      $message = t("The following BEE reservations were created for a new webform submission:\n\n@event_links\n\nTo view the submission, please go to @submission", ['@event_links' => implode("\n", $event_links), '@submission' => $webform_submission->url('canonical', ['absolute' => TRUE])]);
nicola85's avatar
nicola85 committed
140
    }
acrollet's avatar
acrollet committed
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    $mailManager = \Drupal::service('plugin.manager.mail');

    $module = 'bee_webform';
    $key = 'bee_webform_submission';
    $to = $webform->getOwner()->getEmail();
    $params['webform_title'] = $webform->get('title');
    $params['message'] = $message;
    $langcode = $webform->getOwner()->getPreferredLangcode();
    $send = TRUE;

    $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
    if ($result['result'] !== true) {
      $message = t('There was a problem sending your email notification to @email for creating a webform BEE reservation.', array('@email' => $to));
      drupal_set_message($message, 'error');
      \Drupal::logger('bee_webform')->error($message);
      return;
    }

    $message = t('An email notification has been sent to @email for creating a webform BEE reservation.', array('@email' => $to));
    drupal_set_message($message);
    \Drupal::logger('bee_webform')->notice($message);
nicola85's avatar
nicola85 committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
  }
}

/**
 * Get available Units.
 *
 * @param $values
 *
 * return array
 */
function bee_webform_get_available_units($values) {
  $node = $values['node'];
  $start_date = $values['start_date'];
  $end_date = $values['end_date'];

  $bee_settings = \Drupal::config('node.type.' . $node->bundle())->get('bee');

  $units_ids = [];
  foreach ($node->get('field_availability_' . $bee_settings['bookable_type']) as $unit) {
    $units_ids[] = $unit->entity->id();
  }

  if ($bee_settings['bookable_type'] == 'daily') {
    $start_date = new \DateTime($start_date);
    $end_date = new \DateTime($end_date);
    $end_date->sub(new \DateInterval('PT1M'));

    $available_units_ids = bat_event_get_matching_units($start_date, $end_date, ['bee_daily_available'], $bee_settings['type_id'], 'availability_daily');
  }
  else {
acrollet's avatar
acrollet committed
192 193
    $start_date = new \DateTime($start_date);
    $end_date = new \DateTime($end_date);
nicola85's avatar
nicola85 committed
194 195 196 197 198 199 200
    $end_date->sub(new \DateInterval('PT1M'));

    $available_units_ids = bat_event_get_matching_units($start_date, $end_date, ['bee_hourly_available'], $bee_settings['type_id'], 'availability_hourly');
  }

  return array_intersect($units_ids, $available_units_ids);
}
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

/**
 * @param $field_name
 * @param $event_type
 */
function bee_webform_add_event_webform_reference_field($field_name, $event_type) {
  $field_storage = FieldStorageConfig::loadByName('bat_event', $field_name);
  $field = FieldConfig::loadByName('bat_event', $event_type, $field_name);

  if (empty($field_storage)) {
    $field_storage = FieldStorageConfig::create([
      'field_name' => $field_name,
      'entity_type' => 'bat_event',
      'type' => 'entity_reference',
      'cardinality' => 1,
      'locked' => 1,
      'settings' => [
        'target_type' => 'webform_submission',
      ],
    ]);
    $field_storage->save();
  }

  if (empty($field)) {
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'entity_type' => 'bat_event',
      'label' => 'Webform',
      'bundle' => $event_type,
      'required' => FALSE,
      'settings' => [
        'handler' => 'default',
        'handler_settings' => [],
      ],
    ]);
    $field->save();
  }
}
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

/**
 * Implements hook_mail().
 */
function bee_webform_mail($key, &$message, $params) {
  $options = array(
    'langcode' => $message['langcode'],
  );

  switch ($key) {
    case 'bee_webform_submission':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('Reservations created from webform @title', array('@title' => $params['webform_title']), $options);
      $message['body'][] = SafeMarkup::checkPlain($params['message']);
      break;
  }
}