| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam\Services\Products\Discount; |
| 4 |
|
| 5 |
use SyncBasalam\Admin\Settings\SettingsConfig; |
| 6 |
use SyncBasalam\Config\Endpoints; |
| 7 |
use SyncBasalam\Services\ApiServiceManager; |
| 8 |
|
| 9 |
class DiscountManager |
| 10 |
{ |
| 11 |
private $apiService; |
| 12 |
private $settingsAccessor; |
| 13 |
private string $url; |
| 14 |
|
| 15 |
public function __construct( |
| 16 |
$apiService = null |
| 17 |
) { |
| 18 |
$this->apiService = $apiService ?: syncBasalamContainer()->get(ApiServiceManager::class); |
| 19 |
$this->settingsAccessor = syncBasalamSettings(); |
| 20 |
$vendorId = $this->settingsAccessor->getSettings(SettingsConfig::VENDOR_ID); |
| 21 |
$this->url = sprintf(Endpoints::VENDOR_DISCOUNTS, $vendorId); |
| 22 |
} |
| 23 |
|
| 24 |
public function apply($discountPercent, $productIds, $variationIds, $activeDays = null) |
| 25 |
{ |
| 26 |
if (!$activeDays) $activeDays = $this->settingsAccessor->getSettings(SettingsConfig::DISCOUNT_DURATION) ?? 7; |
| 27 |
|
| 28 |
$data = [ |
| 29 |
'product_filter' => [ |
| 30 |
'product_ids' => $productIds, |
| 31 |
'variation_ids' => $variationIds, |
| 32 |
'status' => [3568, 2976], |
| 33 |
], |
| 34 |
'discount_percent' => $discountPercent, |
| 35 |
'active_days' => $activeDays, |
| 36 |
]; |
| 37 |
|
| 38 |
try { |
| 39 |
return $this->apiService->post($this->url, $data); |
| 40 |
} catch (\Exception $e) { |
| 41 |
return [ |
| 42 |
'status_code' => 500, |
| 43 |
'error' => 'خطا در اع� |
| 44 |
ال تخفیف: ' . $e->getMessage(), |
| 45 |
'body' => null |
| 46 |
]; |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
public function remove($productIds, $variationIds) |
| 51 |
{ |
| 52 |
$data = [ |
| 53 |
'product_filter' => [ |
| 54 |
'product_ids' => $productIds, |
| 55 |
'variation_ids' => $variationIds, |
| 56 |
], |
| 57 |
]; |
| 58 |
|
| 59 |
try { |
| 60 |
return $this->apiService->delete($this->url, [], $data); |
| 61 |
} catch (\Exception $e) { |
| 62 |
return [ |
| 63 |
'status_code' => 500, |
| 64 |
'error' => 'خطا در حذف تخفیف: ' . $e->getMessage(), |
| 65 |
'body' => null |
| 66 |
]; |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
public static function calculateDiscountPercent($primaryPrice, $discountedPrice) |
| 71 |
{ |
| 72 |
if ($primaryPrice <= 0) return 0; |
| 73 |
|
| 74 |
$discountPercent = (($primaryPrice - $discountedPrice) / $primaryPrice) * 100; |
| 75 |
|
| 76 |
return round($discountPercent); |
| 77 |
} |
| 78 |
} |
| 79 |
|