bee_webform.module 12.9 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
use Drupal\node\Entity\Node;
8
use Drupal\webform\Entity\Webform;
9
use Drupal\webform\Entity\WebformSubmission;
nicola85's avatar
nicola85 committed
10 11 12 13 14 15

/**
 * Implements hook_form_alter().
 */
function bee_webform_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (isset($form['#webform_id'])) {
16 17 18
    $webform = Webform::load($form['#webform_id']);

    if ($form['#form_id'] == 'webform_submission_' . $webform->id() . '_add_form') {
19 20
      if (_bee_webform_get_webform_bee_reservation_element($webform)) {
        $form['actions']['submit']['#submit'][] = 'bee_webform_form_submit';
nicola85's avatar
nicola85 committed
21 22 23 24 25
      }
    }
  }
}

acrollet's avatar
acrollet committed
26
/**
27
 * Webform submission handler.
acrollet's avatar
acrollet committed
28
 */
nicola85's avatar
nicola85 committed
29
function bee_webform_form_submit($form, FormStateInterface $form_state) {
30
  $webform = Webform::load($form['#webform_id']);
31
  $webform_submission = $form_state->getFormObject()->getEntity();
nicola85's avatar
nicola85 committed
32

33 34
  $webform_bee_element = _bee_webform_get_webform_bee_reservation_element($webform);
  $bee_element_id = $webform_bee_element['#id'];
35

36
  if ($webform->getHandlers('commerce_webform_order')->count()) {
37 38
    bee_webform_add_reservation_to_cart($webform, $webform_submission, $bee_element_id);
  }
nicola85's avatar
nicola85 committed
39

40 41
  if (empty($webform_bee_element['#only_check_availability'])) {
    $value = $form_state->getValue($bee_element_id);
nicola85's avatar
nicola85 committed
42

43 44 45
    if ($value['content_type'] && $value['start_date'] && $value['end_date'] && $value['capacity']) {
      $start_date = $value['start_date'];
      $end_date = $value['end_date'];
nicola85's avatar
nicola85 committed
46

47
      $max_capacity = FALSE;
nicola85's avatar
nicola85 committed
48

49
      $available_units = [];
50

51
      $nids = _bee_webform_get_nodeids_by_type($webform_submission, $bee_element_id);
52

53 54
      foreach ($nids as $nid) {
        $node = node_load($nid);
55

56
        if ($node_available_units = bee_webform_get_available_units_for_node($node, $webform_submission, $bee_element_id)) {
57

58 59 60 61 62 63 64 65 66 67 68
          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
69
        }
acrollet's avatar
acrollet committed
70 71
      }

72
      uasort($available_units, function($a, $b) { return count($a) - count($b); });
acrollet's avatar
acrollet committed
73

74 75
      $index = 0;
      $events_created = [];
acrollet's avatar
acrollet committed
76

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

82
        $node = Node::load($nid);
acrollet's avatar
acrollet committed
83

84
        $bee_settings = \Drupal::config('node.type.' . $node->bundle())->get('bee');
acrollet's avatar
acrollet committed
85 86

        if ($bee_settings['bookable_type'] == 'daily') {
87
          $booked_state = bat_event_load_state_by_machine_name('bee_daily_booked');
88
          $event_type = 'availability_daily';
89 90
        }
        else {
91
          $booked_state = bat_event_load_state_by_machine_name('bee_hourly_booked');
92
          $event_type = 'availability_hourly';
93
        }
acrollet's avatar
acrollet committed
94

95 96 97 98
        $start_date = new \DateTime($start_date);
        $end_date = new \DateTime($end_date);

        foreach ($node_available_units as $unit) {
99 100 101 102 103 104 105
          $event = bat_event_create(['type' => $event_type]);
          $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());
106 107 108 109 110 111 112 113 114 115

          $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;
          }
116
        }
acrollet's avatar
acrollet committed
117
      }
118

119 120 121
      // 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])]);
nicola85's avatar
nicola85 committed
122
      }
123 124 125 126 127 128
      else {
        $events = bat_event_load_multiple($events_created);
        $event_links = [];
        foreach ($events as $event) {
          $event_links[] = $event->url('canonical', ['absolute' => TRUE]);
        }
acrollet's avatar
acrollet committed
129

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        $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])]);
      }
      $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;
      }
acrollet's avatar
acrollet committed
149

150 151 152 153
      $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
154 155 156 157 158 159 160 161 162 163 164
  }
}

/**
 * Get available Units.
 *
 * @param $values
 *
 * return array
 */
function bee_webform_get_available_units($values) {
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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
  $start_date = $values['start_date'];
  $end_date = $values['end_date'];
  $content_type = $values['content_type'];

  $bee_settings = \Drupal::config('node.type.' . $content_type)->get('bee');
  $availability_type = $bee_settings['bookable_type'];

  $units_by_nid = [];
  $query = \Drupal::entityQuery('node')
    ->condition('type', $content_type);
  $nids = $query->execute();

  // Allow other modules to alter the available units for this node.
  $context = [
    'form_values' => $values,
    'nids' => $nids,
  ];
  \Drupal::moduleHandler()->alter('bee_webform_available_node_ids', $nids, $context);

  $field_name = 'field_availability_' . $availability_type . '_target_id';
  $query = \Drupal::database()->select('node__field_availability_' . $availability_type, 'nfa');
  $query->addField('nfa', $field_name);
  $query->condition('nfa.entity_id', $nids, 'IN');
  $unit_ids = $query->execute()->fetchCol();

  $drupal_units = bat_unit_load_multiple($unit_ids);
  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', FALSE, $drupal_units);
  }
  else {
    $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_hourly_available'], $bee_settings['type_id'], 'availability_hourly', FALSE, $drupal_units);
  }

  // Remove unavailable units from mapping.
  $units = array_intersect($unit_ids, $available_units_ids);

  return $units;
}

/**
 * Get available Units for a given node.
 *
215 216 217
 * @param $node
 * @param WebformSubmission $webform_submission
 * @param $bee_element_id
218 219 220
 *
 * return array
 */
221 222 223 224 225
function bee_webform_get_available_units_for_node($node, WebformSubmission $webform_submission, $bee_element_id) {
  $data = $webform_submission->getData();

  $start_date = $data[$bee_element_id]['start_date'];
  $end_date = $data[$bee_element_id]['end_date'];
nicola85's avatar
nicola85 committed
226 227 228

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

229
  $drupal_units = [];
nicola85's avatar
nicola85 committed
230
  foreach ($node->get('field_availability_' . $bee_settings['bookable_type']) as $unit) {
231
    $drupal_units[$unit->entity->id()] = $unit->entity;
nicola85's avatar
nicola85 committed
232 233 234 235 236 237 238
  }

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

239
    $available_units_ids = bat_event_get_matching_units($start_date, $end_date, ['bee_daily_available'], $bee_settings['type_id'], 'availability_daily', FALSE, $drupal_units);
nicola85's avatar
nicola85 committed
240 241
  }
  else {
acrollet's avatar
acrollet committed
242 243
    $start_date = new \DateTime($start_date);
    $end_date = new \DateTime($end_date);
nicola85's avatar
nicola85 committed
244 245
    $end_date->sub(new \DateInterval('PT1M'));

246
    $available_units_ids = bat_event_get_matching_units($start_date, $end_date, ['bee_hourly_available'], $bee_settings['type_id'], 'availability_hourly', FALSE, $drupal_units);
nicola85's avatar
nicola85 committed
247 248
  }

249
  return $available_units_ids;
nicola85's avatar
nicola85 committed
250
}
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

/**
 * @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();
  }
}
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

/**
 * 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;
  }
}
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

/**
 * @param Webform $webform
 *
 * @return array|false
 */
function _bee_webform_get_webform_bee_reservation_element(Webform $webform) {
  foreach ($webform->getElementsDecodedAndFlattened() as $element_id => $element) {
    if ($element['#type'] == 'webform_bee_reservation_form') {
      $element['#id'] = $element_id;

      return $element;
    }
  }

  return FALSE;
}

/**
 * @param WebformSubmission $webform_submission
 * @param $bee_element_id
 *
 * @return array
 */
function _bee_webform_get_nodeids_by_type(WebformSubmission $webform_submission, $bee_element_id) {
  $data = $webform_submission->getData();

  $query = \Drupal::entityQuery('node')
    ->condition('type', $data[$bee_element_id]['content_type']);

  $nids = $query->execute();

  // Allow other modules to alter the available units for this node.
  $context = [
    'webform_submission' => $webform_submission,
    'nids' => $nids,
  ];
  \Drupal::moduleHandler()->alter('bee_webform_available_node_ids', $nids, $context);

  return $nids;
}

/**
 * @param Webform $webform
 * @param WebformSubmission $webform_submission
 * @param $bee_element_id
 */
function bee_webform_add_reservation_to_cart(Webform $webform, WebformSubmission $webform_submission, $bee_element_id) {
  $data = $webform_submission->getData();

  $store = \Drupal::service('commerce_store.current_store')->getStore();

  $cart_provider = \Drupal::service('commerce_cart.cart_provider');
  $cart = $cart_provider->getCart('default', $store);

  $start_date = new \DateTime($data[$bee_element_id]['start_date']);
  $end_date = new \DateTime($data[$bee_element_id]['end_date']);

  foreach ($cart->getItems() as $order_item) {
    if ($order_item->bundle() == 'bee') {
      $nids = _bee_webform_get_nodeids_by_type($webform_submission, $bee_element_id);

      foreach ($nids as $nid) {
        $node = node_load($nid);

        if (bee_webform_get_available_units_for_node($node, $webform_submission, $bee_element_id)) {
          $booking = bat_booking_create([
            'type' => 'bee',
            'label' => $node->label(),
          ]);
376 377 378
          $booking->set('booking_start_date', $start_date->format('Y-m-d\TH:i:s'));
          $booking->set('booking_end_date', $end_date->format('Y-m-d\TH:i:s'));
          $booking->set('booking_capacity', $data[$bee_element_id]['capacity']);
379 380 381 382 383 384 385 386 387 388 389 390
          $booking->save();

          $order_item->set('field_booking', $booking);
          $order_item->set('field_node', $node);
          $order_item->save();

          break;
        }
      }
    }
  }
}