42 lines
1.4 KiB
PHP
42 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace Modules\Core\Customer\Services;
|
|
|
|
use Illuminate\Contracts\Auth\Authenticatable;
|
|
use Lunar\Base\LunarUser;
|
|
use Lunar\Models\Order;
|
|
|
|
/**
|
|
* Attaches placed guest orders to an account when their billing email
|
|
* matches the account's email, case-insensitively. Only ever called right
|
|
* after the shopper has proved they own that email — a login code
|
|
* (Auth\Events\UserAuthenticated), or the code confirming an email change
|
|
* (a consuming app's own email-change flow, e.g. 3dealer's Account\
|
|
* EmailController::verify()) — which is what makes matching on email safe.
|
|
*
|
|
* Only orders with no customer_id AND no user_id are touched: an order
|
|
* already attached to any account (guest or otherwise) is left alone.
|
|
*/
|
|
class GuestOrderClaimer
|
|
{
|
|
public function claim(Authenticatable&LunarUser $user): int
|
|
{
|
|
$customer = $user->latestCustomer();
|
|
|
|
if (! $customer || ! $user->email) {
|
|
return 0;
|
|
}
|
|
|
|
return Order::query()
|
|
->whereNotNull('placed_at')
|
|
->whereNull('customer_id')
|
|
->whereNull('user_id')
|
|
->whereHas('billingAddress', fn ($query) => $query
|
|
->whereRaw('lower(contact_email) = ?', [strtolower($user->email)]))
|
|
->update([
|
|
'customer_id' => $customer->id,
|
|
'user_id' => $user->id,
|
|
]);
|
|
}
|
|
}
|