generated from boboko/starter
38 lines
1.1 KiB
PHP
38 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Illuminate\Contracts\Auth\Authenticatable;
|
|
use Lunar\Models\Order;
|
|
|
|
/**
|
|
* Attaches placed guest orders to an account when their billing email matches
|
|
* the account's email. Only ever called right after the shopper has proved
|
|
* they own that email (a login code, or the code confirming an email change),
|
|
* which is what makes matching on email safe.
|
|
*
|
|
* Orders already belonging to any customer or user are never touched.
|
|
*/
|
|
class GuestOrderClaimer
|
|
{
|
|
public function claim(Authenticatable $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,
|
|
]);
|
|
}
|
|
}
|