DHL Modul v0.5 Shipping Label ok

This commit is contained in:
Kevin Adametz 2025-08-22 18:18:26 +02:00
parent 480fdc65ed
commit 8fdaa0ba1d
122 changed files with 17938 additions and 2239 deletions

View file

@ -0,0 +1,144 @@
<?php
namespace App\Jobs;
use App\Models\DhlShipment;
use App\Services\DhlApiService;
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 cancel DHL shipments asynchronously
*
* This job handles the cancellation of DHL shipments in the background,
* preventing API timeouts and improving user experience.
*/
class CancelShipmentJob implements ShouldQueue
{
use BusQueueable, Dispatchable, InteractsWithQueue, SerializesModels;
/**
* @var DhlShipment
*/
public $dhlShipment;
/**
* @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 = 60;
/**
* Create a new job instance.
*
* @param DhlShipment $dhlShipment
* @param array $options
*/
public function __construct(DhlShipment $dhlShipment, array $options = [])
{
$this->dhlShipment = $dhlShipment;
$this->options = $options;
// Set queue name based on priority
if (isset($options['priority']) && $options['priority'] === 'high') {
$this->onQueue('high-priority');
} else {
$this->onQueue('dhl-cancellations');
}
}
/**
* Execute the job.
*/
public function handle(): void
{
try {
Log::info('[DHL Queue] Starting shipment cancellation job', [
'shipment_id' => $this->dhlShipment->id,
'shipment_number' => $this->dhlShipment->shipment_number,
'attempt' => $this->attempts(),
]);
$dhlService = new DhlApiService();
// Cancel the shipment
$success = $dhlService->cancelShipment($this->dhlShipment);
if ($success) {
Log::info('[DHL Queue] Shipment cancelled successfully', [
'shipment_id' => $this->dhlShipment->id,
'shipment_number' => $this->dhlShipment->shipment_number,
]);
} else {
throw new Exception('Cancellation returned false');
}
} catch (Exception $e) {
Log::error('[DHL Queue] Shipment cancellation failed', [
'shipment_id' => $this->dhlShipment->id,
'shipment_number' => $this->dhlShipment->shipment_number,
'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 cancellation permanently failed', [
'shipment_id' => $this->dhlShipment->id,
'error' => $e->getMessage(),
]);
}
throw $e; // Re-throw to trigger retry mechanism
}
}
/**
* Handle a job failure.
*
* @param Exception $exception
*/
public function failed(Exception $exception): void
{
Log::error('[DHL Queue] CancelShipmentJob permanently failed', [
'shipment_id' => $this->dhlShipment->id,
'shipment_number' => $this->dhlShipment->shipment_number,
'error' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
]);
// You could implement additional failure handling here:
// - Send notification to admin
// - Create manual task for staff to handle cancellation
// - Update shipment status to indicate cancellation failed
}
/**
* Determine the time at which the job should timeout.
*
* @return \DateTime
*/
public function retryUntil()
{
return now()->addHour(); // Shorter timeout for cancellations
}
}

View file

@ -0,0 +1,148 @@
<?php
namespace App\Jobs;
use App\Models\DhlShipment;
use App\Services\DhlApiService;
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 return labels asynchronously
*
* This job handles the creation of DHL return labels in the background,
* preventing API timeouts and improving user experience.
*/
class CreateReturnLabelJob implements ShouldQueue
{
use BusQueueable, Dispatchable, InteractsWithQueue, SerializesModels;
/**
* @var DhlShipment
*/
public $originalShipment;
/**
* @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.
*
* @param DhlShipment $originalShipment
* @param array $options
*/
public function __construct(DhlShipment $originalShipment, array $options = [])
{
$this->originalShipment = $originalShipment;
$this->options = $options;
// Set queue name based on priority
if (isset($options['priority']) && $options['priority'] === 'high') {
$this->onQueue('high-priority');
} else {
$this->onQueue('dhl-returns');
}
}
/**
* Execute the job.
*/
public function handle(): void
{
try {
Log::info('[DHL Queue] Starting return label creation job', [
'original_shipment_id' => $this->originalShipment->id,
'original_shipment_number' => $this->originalShipment->shipment_number,
'attempt' => $this->attempts(),
]);
$dhlService = new DhlApiService();
// Create the return label
$returnShipment = $dhlService->createReturnLabel(
$this->originalShipment,
$this->options
);
Log::info('[DHL Queue] Return label created successfully', [
'original_shipment_id' => $this->originalShipment->id,
'return_shipment_id' => $returnShipment->id,
'return_shipment_number' => $returnShipment->shipment_number,
]);
// Trigger follow-up actions if specified
if (isset($this->options['auto_track']) && $this->options['auto_track']) {
\App\Jobs\TrackShipmentJob::dispatch($returnShipment)->delay(now()->addMinutes(5));
}
} catch (Exception $e) {
Log::error('[DHL Queue] Return label creation failed', [
'original_shipment_id' => $this->originalShipment->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] Return label creation permanently failed', [
'original_shipment_id' => $this->originalShipment->id,
'error' => $e->getMessage(),
]);
}
throw $e; // Re-throw to trigger retry mechanism
}
}
/**
* Handle a job failure.
*
* @param Exception $exception
*/
public function failed(Exception $exception): void
{
Log::error('[DHL Queue] CreateReturnLabelJob permanently failed', [
'original_shipment_id' => $this->originalShipment->id,
'original_shipment_number' => $this->originalShipment->shipment_number,
'error' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
]);
// You could implement additional failure handling here:
// - Send notification to admin
// - Create manual task for staff to handle return label creation
// - Update original shipment to mark return label creation failed
}
/**
* Determine the time at which the job should timeout.
*
* @return \DateTime
*/
public function retryUntil()
{
return now()->addHours(2);
}
}

View file

@ -0,0 +1,179 @@
<?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;
/**
* @var array
*/
public $dhlConfig;
/**
* 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.
*
* @param ShoppingOrder $shoppingOrder
* @param float $weight
* @param array $options
* @param array|null $dhlConfig
*/
public function __construct(ShoppingOrder $shoppingOrder, float $weight = 1.0, array $options = [], array $dhlConfig = [])
{
$this->shoppingOrder = $shoppingOrder;
$this->weight = $weight;
$this->options = $options;
// Load DHL config once when creating the job
if (empty($dhlConfig)) {
$settingController = new \App\Http\Controllers\SettingController();
$this->dhlConfig = $settingController->getDhlConfig();
} else {
$this->dhlConfig = $dhlConfig;
}
// 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(),
]);
// Use DHL configuration loaded in constructor
$dhlClient = new \Acme\Dhl\Support\DhlClient(
$this->dhlConfig['base_url'],
$this->dhlConfig['api_key'],
$this->dhlConfig['username'],
$this->dhlConfig['password']
);
$shippingService = new \Acme\Dhl\Services\ShippingService($dhlClient);
// Prepare order data using helper
$orderData = DhlDataHelper::prepareOrderData($this->shoppingOrder, $this->weight, $this->options, $this->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.
*
* @param Exception $exception
*/
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);
}
}

View file

@ -0,0 +1,194 @@
<?php
namespace App\Jobs;
use App\Models\DhlShipment;
use App\Services\DhlApiService;
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 track DHL shipments asynchronously
*
* This job handles the tracking of DHL shipments in the background,
* updating tracking status and details automatically.
*/
class TrackShipmentJob implements ShouldQueue
{
use BusQueueable, Dispatchable, InteractsWithQueue, SerializesModels;
/**
* @var DhlShipment
*/
public $dhlShipment;
/**
* @var array
*/
public $options;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 2; // Lower tries for tracking as it's less critical
/**
* The maximum number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout = 60;
/**
* Create a new job instance.
*
* @param DhlShipment $dhlShipment
* @param array $options
*/
public function __construct(DhlShipment $dhlShipment, array $options = [])
{
$this->dhlShipment = $dhlShipment;
$this->options = $options;
// Set queue name - tracking is usually lower priority
$this->onQueue('dhl-tracking');
}
/**
* Execute the job.
*/
public function handle(): void
{
try {
Log::info('[DHL Queue] Starting shipment tracking job', [
'shipment_id' => $this->dhlShipment->id,
'tracking_number' => $this->dhlShipment->tracking_number,
'attempt' => $this->attempts(),
]);
$dhlService = new DhlApiService();
// Get tracking details
$trackingDetails = $dhlService->getTrackingDetails($this->dhlShipment);
Log::info('[DHL Queue] Shipment tracking updated successfully', [
'shipment_id' => $this->dhlShipment->id,
'tracking_status' => $trackingDetails['status'] ?? 'unknown',
'events_count' => isset($trackingDetails['events']) ? count($trackingDetails['events']) : 0,
]);
// Schedule next tracking update if shipment is still in transit
if (isset($this->options['auto_retrack']) && $this->options['auto_retrack']) {
$status = $trackingDetails['status'] ?? '';
if ($this->shouldContinueTracking($status)) {
// Schedule next tracking in 2-6 hours based on current status
$nextTrackingDelay = $this->getNextTrackingDelay($status);
TrackShipmentJob::dispatch($this->dhlShipment, $this->options)
->delay(now()->addMinutes($nextTrackingDelay));
Log::info('[DHL Queue] Next tracking job scheduled', [
'shipment_id' => $this->dhlShipment->id,
'delay_minutes' => $nextTrackingDelay,
]);
}
}
} catch (Exception $e) {
Log::warning('[DHL Queue] Shipment tracking failed', [
'shipment_id' => $this->dhlShipment->id,
'tracking_number' => $this->dhlShipment->tracking_number,
'error' => $e->getMessage(),
'attempt' => $this->attempts(),
'max_tries' => $this->tries,
]);
// For tracking, we don't necessarily need to fail hard
if ($this->attempts() >= $this->tries) {
Log::warning('[DHL Queue] Shipment tracking permanently failed', [
'shipment_id' => $this->dhlShipment->id,
'error' => $e->getMessage(),
]);
// Don't re-throw for final attempt - just log and continue
return;
}
throw $e; // Re-throw to trigger retry mechanism
}
}
/**
* Handle a job failure.
*
* @param Exception $exception
*/
public function failed(Exception $exception): void
{
Log::warning('[DHL Queue] TrackShipmentJob permanently failed', [
'shipment_id' => $this->dhlShipment->id,
'tracking_number' => $this->dhlShipment->tracking_number,
'error' => $exception->getMessage(),
]);
// Tracking failures are less critical - just log them
}
/**
* Determine if we should continue tracking this shipment
*
* @param string $status
* @return bool
*/
private function shouldContinueTracking(string $status): bool
{
$finalStates = [
'delivered',
'delivered_to_recipient',
'delivered_to_pickup_location',
'returned_to_sender',
'cancelled',
'lost',
];
return !in_array(strtolower($status), $finalStates);
}
/**
* Get delay for next tracking update based on current status
*
* @param string $status
* @return int Minutes until next tracking
*/
private function getNextTrackingDelay(string $status): int
{
switch (strtolower($status)) {
case 'picked_up':
case 'in_transit':
return 120; // 2 hours for active shipments
case 'out_for_delivery':
return 60; // 1 hour when out for delivery
case 'exception':
case 'failed_attempt':
return 240; // 4 hours for problem shipments
default:
return 180; // 3 hours default
}
}
/**
* Determine the time at which the job should timeout.
*
* @return \DateTime
*/
public function retryUntil()
{
return now()->addMinutes(30); // Short timeout for tracking
}
}