You are here

protected function Cron::enqueueOrders in Commerce Recurring Framework 8

Enqueues ended recurring orders for closing/renewal.

Parameters

\Drupal\advancedqueue\Entity\QueueInterface $recurring_queue: The recurring queue.

1 call to Cron::enqueueOrders()
Cron::run in src/Cron.php
Runs the cron.

File

src/Cron.php, line 70

Class

Cron
Default cron implementation.

Namespace

Drupal\commerce_recurring

Code

protected function enqueueOrders(QueueInterface $recurring_queue) {
  $order_storage = $this->entityTypeManager
    ->getStorage('commerce_order');
  $order_ids = $order_storage
    ->getQuery()
    ->condition('type', 'recurring')
    ->condition('state', 'draft')
    ->condition('billing_period.ends', $this->time
    ->getRequestTime(), '<=')
    ->accessCheck(FALSE)
    ->execute();
  if (!$order_ids) {
    return;
  }

  /** @var \Drupal\commerce_order\Entity\OrderInterface[] $orders */
  $orders = $order_storage
    ->loadMultiple($order_ids);
  foreach ($orders as $order) {
    $subscriptions = $this->recurringOrderManager
      ->collectSubscriptions($order);
    if (!$subscriptions) {

      // The recurring order is malformed. The referenced subscription
      // might have been deleted manually.
      $order
        ->set('state', 'canceled');
      $order
        ->save();
      continue;
    }
    $subscription = reset($subscriptions);
    if ($subscription
      ->hasScheduledChanges()) {

      // Apply changes that were scheduled to happen on the next billing
      // cycle like suscription cancelation.
      $subscription
        ->applyScheduledChanges();
      $subscription
        ->save();
    }

    // If the subscription was scheduled for cancelation, applying the
    // scheduled changes has resulted in both the subscription and its
    // recurring order being canceled.
    // Canceled orders are considered closed, and don't need to be charged.
    if ($order
      ->getState()
      ->getId() == 'draft') {
      $close_job = Job::create('commerce_recurring_order_close', [
        'order_id' => $order
          ->id(),
      ]);
      $recurring_queue
        ->enqueueJob($close_job);
    }

    // Recurring orders are renewed only if their subscription is active.
    if ($subscription
      ->getState()
      ->getId() == 'active') {
      $renew_job = Job::create('commerce_recurring_order_renew', [
        'order_id' => $order
          ->id(),
      ]);
      $recurring_queue
        ->enqueueJob($renew_job);
    }
  }
}