Files
core/src/Shipping/Support/VoucherOrderMatcher.php
T

130 lines
4.3 KiB
PHP

<?php
namespace Modules\Core\Shipping\Support;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Lunar\Models\Order;
use Modules\Core\Shipping\DTOs\CarrierVoucher;
use Modules\Core\Shipping\Models\Shipment;
/**
* Suggests the orders a carrier-reported voucher may belong to. It never
* links anything — staff confirm a suggestion with "Link to order".
*
* Best first:
* - the order the reference we sent the carrier points to: the order
* reference (ELTA pel_ref_no, ACS Reference_Key1), Box Now's
* "{reference}-{id}[-{attempt}]" orderNumber, or the bare order id older
* ELTA vouchers were sent;
* - for a return voucher that names its original voucher, that shipment's
* order;
* - then orders with the same postcode and the same phone or recipient
* name, among recent orders with no active shipment with this carrier.
*/
class VoucherOrderMatcher
{
private const SUGGESTION_WINDOW_DAYS = 60;
private const MAX_SUGGESTIONS = 5;
/**
* @return array<int, int> order ids, best first
*/
public function suggestions(CarrierVoucher $voucher): array
{
return collect([$this->referenceMatch($voucher), ...$this->suggestedOrderIds($voucher)])
->filter()
->unique()
->values()
->all();
}
/**
* The order the voucher's own reference (or original voucher) points to.
*/
public function referenceMatch(CarrierVoucher $voucher): ?int
{
if ($voucher->originalVoucher
&& $orderId = Shipment::where('tracking_reference', $voucher->originalVoucher)->value('order_id')) {
return $orderId;
}
$reference = trim((string) $voucher->reference);
if ($reference === '') {
return null;
}
if ($id = Order::where('reference', $reference)->value('id')) {
return $id;
}
// Box Now: "{reference}-{id}", or "{reference}-{id}-{attempt}" for
// a shipment re-created after a cancel.
foreach (['/^(.+)-(\d+)-\d+$/', '/^(.+)-(\d+)$/'] as $pattern) {
if (preg_match($pattern, $reference, $m)
&& Order::whereKey((int) $m[2])->where('reference', $m[1])->exists()) {
return (int) $m[2];
}
}
if (ctype_digit($reference) && Order::whereKey((int) $reference)->exists()) {
return (int) $reference;
}
return null;
}
/**
* @return array<int, int> order ids, best first
*/
public function suggestedOrderIds(CarrierVoucher $voucher): array
{
if (blank($voucher->postcode) || (blank($voucher->recipientName) && blank($voucher->phone))) {
return [];
}
$since = ($voucher->date ?? now())->copy()->subDays(self::SUGGESTION_WINDOW_DAYS);
return Order::query()
->with('shippingAddress')
->where('placed_at', '>=', $since)
->whereHas('shippingAddress', fn ($q) => $q->where('postcode', trim($voucher->postcode)))
->whereDoesntHave('shipments', fn ($q) => $q->where('carrier', $voucher->carrier)->whereNull('cancelled_at'))
->latest('placed_at')
->limit(50)
->get()
->filter(fn (Order $order) => $this->samePhone($voucher->phone, $order->shippingAddress?->contact_phone)
|| $this->sameName($voucher->recipientName, trim($order->shippingAddress?->first_name.' '.$order->shippingAddress?->last_name)))
->take(self::MAX_SUGGESTIONS)
->pluck('id')
->values()
->all();
}
private function samePhone(?string $a, ?string $b): bool
{
$a = substr(preg_replace('/\D/', '', (string) $a), -10);
$b = substr(preg_replace('/\D/', '', (string) $b), -10);
return strlen($a) === 10 && $a === $b;
}
/**
* Carriers report names in capitals, often without accents or in the
* other script's word order, so compare the sets of name words.
*/
private function sameName(?string $a, ?string $b): bool
{
$words = fn (?string $name): Collection => collect(preg_split('/\s+/u', Str::upper(Str::ascii((string) $name))))
->filter()
->sort()
->values();
$a = $words($a);
return $a->isNotEmpty() && $a->all() === $words($b)->all();
}
}