trangshopeeaffiliate/app/Services/HistoryService.php
2026-07-11 22:56:22 +07:00

68 lines
2.1 KiB
PHP

<?php
namespace App\Services;
use App\Models\ConversionHistory;
use App\DTOs\AffiliateResult;
use Illuminate\Pagination\LengthAwarePaginator;
class HistoryService
{
/**
* Log a conversion result to the database.
*/
public function logConversion(
AffiliateResult $result,
?string $code = null,
?string $zaloThreadId = null,
?string $zaloChatName = null,
?string $customerName = null,
?string $customerPhone = null,
?string $productTitle = null,
?string $productImage = null,
float $productPrice = 0.00,
float $estimatedCommission = 0.00
): ConversionHistory {
if ($result->isSuccess && !$code) {
do {
$code = \Illuminate\Support\Str::random(10);
} while (ConversionHistory::whereRaw('BINARY code = ?', [$code])->exists());
}
return ConversionHistory::create([
'code' => $code,
'original_url' => $result->originalUrl,
'affiliate_url' => $result->affiliateUrl,
'converter_type' => $result->converterType,
'session_name' => $result->sessionUsed,
'status' => $result->isSuccess ? 'success' : 'failed',
'error_message' => $result->errorMessage,
'execution_time' => $result->executionTime,
'zalo_thread_id' => $zaloThreadId,
'zalo_chat_name' => $zaloChatName,
'customer_name' => $customerName,
'customer_phone' => $customerPhone,
'product_title' => $productTitle,
'product_image' => $productImage,
'product_price' => $productPrice,
'estimated_commission' => $estimatedCommission,
]);
}
/**
* Get recent conversion history.
*/
public function getRecent(int $limit = 20)
{
return ConversionHistory::orderByDesc('created_at')->limit($limit)->get();
}
/**
* Get paginated history for the UI.
*/
public function getPaginated(int $perPage = 20): LengthAwarePaginator
{
return ConversionHistory::orderByDesc('created_at')->paginate($perPage);
}
}