diff --git a/modules/order/commerce_order.module b/modules/order/commerce_order.module index 998a3d1fe0..d366bc3e8c 100644 --- a/modules/order/commerce_order.module +++ b/modules/order/commerce_order.module @@ -6,8 +6,11 @@ */ use Drupal\commerce\BundleFieldDefinition; +use Drupal\commerce_order\Entity\Order; +use Drupal\commerce_order\Entity\OrderInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Render\Element; +use Drupal\Core\Session\AccountInterface; /** * Implements hook_theme(). @@ -55,6 +58,40 @@ function commerce_order_local_tasks_alter(&$definitions) { } } +/** + * Implements hook_ENTITY_TYPE_insert() for user entities. + * + * - Assigns any previous guest orders to new user account. + */ +function commerce_order_user_insert(AccountInterface $user) { + $order_ids = \Drupal::entityQuery('commerce_order') + ->condition('mail', $user->getEmail()) + ->execute(); + if ($order_ids) { + $orders = Order::loadMultiple($order_ids); + foreach ($orders as $order) { + $order->setCustomer($user); + $order->save(); + } + } +} + +/** + * Implements hook_ENTITY_TYPE_presave(). + */ +function commerce_order_commerce_order_presave(OrderInterface $order) { + $place_transition = $order->getState()->getWorkflow()->getTransition('place'); + if (!$order->isNew() && empty($order->getPlacedTime()) && $place_transition) { + $from_states = $place_transition->getFromStates(); + $from_state = reset($from_states); + $from_state = $from_state->getId(); + $to_state = $place_transition->getToState()->getId(); + if ($order->original->state->value == $from_state && $order->state->value == $to_state) { + $order->setPlacedTime(REQUEST_TIME); + } + } +} + /** * Implements hook_field_widget_form_alter(). * diff --git a/modules/order/tests/src/Functional/OrderAccountTest.php b/modules/order/tests/src/Functional/OrderAccountTest.php new file mode 100644 index 0000000000..c965e56e46 --- /dev/null +++ b/modules/order/tests/src/Functional/OrderAccountTest.php @@ -0,0 +1,33 @@ +createEntity('commerce_order_item', [ + 'type' => 'product_variation', + ]); + $order = $this->createEntity('commerce_order', [ + 'type' => 'default', + 'uid' => 0, + 'mail' => 'guest@example.com', + 'order_items' => [$order_item], + ]); + $this->assertEmpty($order->getOwnerId(), 'The guest order has no owner account.'); + $user = $this->createUser([], 'guest'); + $order = Order::load($order->id()); + $this->assertEquals($user->id(), $order->getOwnerId(), 'New user account owns previous guest order.'); + } + +}