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