| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam\Services\Orders; |
| 4 |
|
| 5 |
use SyncBasalam\Config\Endpoints; |
| 6 |
use SyncBasalam\Services\ApiServiceManager; |
| 7 |
use SyncBasalam\Logger\Logger; |
| 8 |
use SyncBasalam\Jobs\Exceptions\RetryableException; |
| 9 |
use SyncBasalam\Jobs\Exceptions\NonRetryableException; |
| 10 |
|
| 11 |
defined('ABSPATH') || exit; |
| 12 |
|
| 13 |
class FetchOrdersService |
| 14 |
{ |
| 15 |
private string $url; |
| 16 |
private $apiService; |
| 17 |
|
| 18 |
public function __construct() |
| 19 |
{ |
| 20 |
$this->url = Endpoints::VENDOR_PARCELS; |
| 21 |
$this->apiService = syncBasalamContainer()->get(ApiServiceManager::class); |
| 22 |
} |
| 23 |
|
| 24 |
public function fetchPage(int $day = 7, $cursor = null): array |
| 25 |
{ |
| 26 |
$timestamp = current_time('timestamp', true) - ($day * 24 * 60 * 60); |
| 27 |
$isoDate = gmdate('c', $timestamp); |
| 28 |
|
| 29 |
$url = $this->url . '?per_page=10&created_at%5Bgte%5D=' . urlencode($isoDate); |
| 30 |
|
| 31 |
if ($cursor) $url .= '&cursor=' . urlencode($cursor); |
| 32 |
|
| 33 |
try { |
| 34 |
$response = $this->apiService->get($url); |
| 35 |
|
| 36 |
if (!isset($response['body'])) { |
| 37 |
return [ |
| 38 |
'success' => false, |
| 39 |
'orders' => [], |
| 40 |
'next_cursor' => null, |
| 41 |
'message' => 'پاسخی از API دریافت نشد.' |
| 42 |
]; |
| 43 |
} |
| 44 |
|
| 45 |
$bodyData = json_decode($response['body'], true); |
| 46 |
|
| 47 |
if (!isset($bodyData['data'])) { |
| 48 |
return [ |
| 49 |
'success' => false, |
| 50 |
'orders' => [], |
| 51 |
'next_cursor' => null, |
| 52 |
'message' => 'دادهای در پاسخ API یافت نشد.' |
| 53 |
]; |
| 54 |
} |
| 55 |
|
| 56 |
$nextCursor = $bodyData['next_cursor'] ?? null; |
| 57 |
|
| 58 |
Logger::debug("دریافت صفحه سفارشات: " . count($bodyData['data']) . " سفارش، cursor بعدی: " . ($nextCursor ?: 'ندارد')); |
| 59 |
|
| 60 |
return [ |
| 61 |
'success' => true, |
| 62 |
'orders' => $bodyData['data'], |
| 63 |
'next_cursor' => $nextCursor, |
| 64 |
'message' => null |
| 65 |
]; |
| 66 |
} catch (RetryableException $e) { |
| 67 |
throw $e; |
| 68 |
} catch (NonRetryableException $e) { |
| 69 |
throw $e; |
| 70 |
} catch (\Throwable $th) { |
| 71 |
throw $th; |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
|