From fde78db51af029df0ec69d0c08ebfc91671e7736 Mon Sep 17 00:00:00 2001 From: Alec Ritson Date: Wed, 1 May 2024 08:15:12 +0100 Subject: [PATCH] Populate `customer_id` on Cart if available. (#1721) --- .../core/src/Actions/Carts/AssociateUser.php | 1 + .../core/src/Managers/CartSessionManager.php | 5 +++- .../Unit/Actions/Carts/AssociateUserTest.php | 29 +++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/core/src/Actions/Carts/AssociateUser.php b/packages/core/src/Actions/Carts/AssociateUser.php index d798f83688..c113ad54c0 100644 --- a/packages/core/src/Actions/Carts/AssociateUser.php +++ b/packages/core/src/Actions/Carts/AssociateUser.php @@ -33,6 +33,7 @@ public function execute(Cart $cart, User $user, $policy = 'merge'): self $cart->update([ 'user_id' => $user->getKey(), + 'customer_id' => $user->latestCustomer()?->getKey(), ]); return $this; diff --git a/packages/core/src/Managers/CartSessionManager.php b/packages/core/src/Managers/CartSessionManager.php index 5697c94089..c82c15ca69 100644 --- a/packages/core/src/Managers/CartSessionManager.php +++ b/packages/core/src/Managers/CartSessionManager.php @@ -234,10 +234,13 @@ public function createOrder($forget = true) */ protected function createNewCart() { + $user = $this->authManager->user(); + $cart = Cart::create([ 'currency_id' => $this->getCurrency()->id, 'channel_id' => $this->getChannel()->id, - 'user_id' => $this->authManager->user()?->id, + 'user_id' => optional($user)->id, + 'customer_id' => optional($user)->latestCustomer()?->id, ]); return $this->use($cart); diff --git a/tests/core/Unit/Actions/Carts/AssociateUserTest.php b/tests/core/Unit/Actions/Carts/AssociateUserTest.php index b4ec4f39f5..ad3f0f37bc 100644 --- a/tests/core/Unit/Actions/Carts/AssociateUserTest.php +++ b/tests/core/Unit/Actions/Carts/AssociateUserTest.php @@ -35,6 +35,35 @@ ]); }); +test('can associate a user with a customer', function () { + $currency = Currency::factory()->create(); + + $cart = Cart::factory()->create([ + 'currency_id' => $currency->id, + ]); + + $this->assertDatabaseHas((new Cart)->getTable(), [ + 'user_id' => null, + 'id' => $cart->id, + 'merged_id' => null, + ]); + + $action = new AssociateUser; + + $user = User::factory()->create(); + $customer = \Lunar\Models\Customer::factory()->create(); + $user->customers()->attach($customer); + + $action->execute($cart, $user); + + $this->assertDatabaseHas((new Cart)->getTable(), [ + 'user_id' => $user->id, + 'customer_id' => $customer->id, + 'id' => $cart->id, + 'merged_id' => null, + ]); +}); + test('cant associate user to cart with order', function () { $currency = Currency::factory()->create();