mivita/app/Jobs/CreateShipmentJob.php

171 lines
5.5 KiB
PHP

<?php
namespace App\Jobs;
use App\Models\ShoppingOrder;
use App\Services\DhlDataHelper;
use Exception;
use Illuminate\Bus\Queueable as BusQueueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
/**
* Job to create DHL shipments asynchronously
*
* This job handles the creation of DHL shipments in the background,
* preventing API timeouts and improving user experience.
*/
class CreateShipmentJob implements ShouldQueue
{
use BusQueueable, Dispatchable, InteractsWithQueue, SerializesModels;
/**
* @var ShoppingOrder
*/
public $shoppingOrder;
/**
* @var float
*/
public $weight;
/**
* @var array
*/
public $options;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 3;
/**
* The maximum number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout = 120;
/**
* Create a new job instance.
*
* IMPORTANT: We intentionally never serialize the DHL configuration into
* the queue payload because it contains the DHL API key, basic-auth
* password and billing numbers. Those values would otherwise sit
* unencrypted in Redis/the queue table. The config is reloaded inside
* {@see self::handle()} from the canonical settings source instead.
*
* The legacy `$dhlConfig` parameter is still accepted for backwards
* compatibility but is no longer persisted onto the job instance.
*
* @param array $dhlConfig Deprecated: ignored to avoid secrets in queue
*/
public function __construct(ShoppingOrder $shoppingOrder, float $weight = 1.0, array $options = [], array $dhlConfig = [])
{
$this->shoppingOrder = $shoppingOrder;
$this->weight = $weight;
$this->options = $options;
// Set queue name based on priority
if (isset($options['priority']) && $options['priority'] === 'high') {
$this->onQueue('high-priority');
} else {
$this->onQueue('dhl-shipments');
}
}
/**
* Execute the job.
*/
public function handle(): void
{
try {
Log::info('[DHL Queue] Starting shipment creation job', [
'order_id' => $this->shoppingOrder->id,
'weight' => $this->weight,
'attempt' => $this->attempts(),
]);
// Load DHL configuration here, never from the serialized job payload.
$dhlConfig = (new \App\Http\Controllers\SettingController)->getDhlConfig();
$dhlClient = new \Acme\Dhl\Support\DhlClient(
$dhlConfig['base_url'],
$dhlConfig['api_key'],
$dhlConfig['username'],
$dhlConfig['password']
);
$shippingService = new \Acme\Dhl\Services\ShippingService($dhlClient);
// Prepare order data using helper
$orderData = DhlDataHelper::prepareOrderData($this->shoppingOrder, $this->weight, $this->options, $dhlConfig);
// Create the shipment using new package
$result = $shippingService->createLabel($orderData);
Log::info('[DHL Queue] Shipment created successfully', [
'order_id' => $this->shoppingOrder->id,
'shipment_number' => $result['shipmentNumber'] ?? 'N/A',
'label_path' => $result['labelPath'] ?? 'N/A',
]);
// Trigger follow-up actions if specified (if tracking number available)
if (isset($this->options['auto_track']) && $this->options['auto_track'] && ! empty($result['trackingNumber'])) {
Log::info('[DHL Queue] Scheduling tracking update', [
'tracking_number' => $result['trackingNumber'],
]);
// Note: TrackShipmentJob would need to be updated to work with tracking numbers
}
} catch (Exception $e) {
Log::error('[DHL Queue] Shipment creation failed', [
'order_id' => $this->shoppingOrder->id,
'error' => $e->getMessage(),
'attempt' => $this->attempts(),
'max_tries' => $this->tries,
]);
// If this is the final attempt, mark as permanently failed
if ($this->attempts() >= $this->tries) {
Log::error('[DHL Queue] Shipment creation permanently failed', [
'order_id' => $this->shoppingOrder->id,
'error' => $e->getMessage(),
]);
}
throw $e; // Re-throw to trigger retry mechanism
}
}
/**
* Handle a job failure.
*/
public function failed(Exception $exception): void
{
Log::error('[DHL Queue] CreateShipmentJob permanently failed', [
'order_id' => $this->shoppingOrder->id,
'error' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
]);
// You could implement additional failure handling here:
// - Send notification to admin
// - Update order status
// - Create manual task for staff
}
/**
* Determine the time at which the job should timeout.
*
* @return \DateTime
*/
public function retryUntil()
{
return now()->addHours(2);
}
}