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();