refactor: Move shipment creation logic to CourierService for DRY principle

- Move all validation (packing, payment, status, duplicates) to CourierService::createShipmentForOrder()
- Move database updates to service layer
- Move document fetching to service layer
- Simplify ShippingController to just handle HTTP concerns (request/response)
- Simplify CreateShipmentOnReadyToShip listener to just dispatch events
- Single source of truth for business logic in CourierService
- Eliminates duplicate validation between controller and listener
This commit is contained in:
twotalesanimation
2026-01-02 18:13:16 +02:00
parent 2ddb3dc19f
commit db0454d102
3 changed files with 145 additions and 191 deletions
+12 -128
View File
@@ -23,120 +23,30 @@ class ShippingController extends Controller
*/
public function createShipment(Request $request, Order $order)
{
Log::info('Initiating shipment creation', ['order_uuid' => $order->uuid]);
// Guard 1: Verify packing completed with valid dimensions
if (! $this->validatePackingGate($order)) {
Log::warning('Packing gate validation failed', [
'order_uuid' => $order->uuid,
'packing_completed_at' => $order->packing_completed_at,
'width' => $order->packing_width,
'length' => $order->packing_length,
'weight' => $order->packing_weight,
]);
return response()->json([
'error' => 'Order not yet packed with valid dimensions',
'details' => [
'packing_completed_at' => $order->packing_completed_at,
'dimensions' => [
'width' => $order->packing_width,
'length' => $order->packing_length,
'weight' => $order->packing_weight,
],
],
], 400);
}
// Guard 2: Verify payment and approval rules
if (! $this->validatePaymentAndApprovalGate($order)) {
$message = $order->is_custom_order ?
'Custom order requires proof approved and balance paid' :
'Standard order must be fully paid';
Log::warning('Payment/approval gate validation failed', [
'order_uuid' => $order->uuid,
'is_custom_order' => $order->is_custom_order,
'payment_status' => $order->payment_status,
]);
return response()->json([
'error' => $message,
'payment_status' => $order->payment_status,
], 403);
}Log::warning('Order status gate validation failed', [
'order_uuid' => $order->uuid,
'expected_status' => 'ready_to_ship',
'current_status' => $order->status,
]);
// Guard 3: Check order status is Ready to Ship
if ($order->status !== 'ready_to_ship') {
return response()->json([
'error' => 'Order must be in Ready to Ship state',
'current_status' => $order->status,
], 409);
}
// Guard 4: Idempotency - if already shipped, return existing shipment
if ($order->courier_waybill_id) {
Log::info('Shipment already exists, returning existing', ['order_uuid' => $order->uuid]);
return response()->json([
'success' => true,
'message' => 'Shipment already created',
'shipment' => [
'waybill_id' => $order->courier_waybill_id,
'tracking_number' => $order->courier_tracking_number,
],
]);
}
try {
// Call courier API
$shipmentData = $this->courierService->createShipment(
$order->id,
$order->packing_width,
$order->packing_length,
$order->packing_weight,
);
$result = $this->courierService->createShipmentForOrder($order);
// Save shipment details
$order->update([
'courier_waybill_id' => $shipmentData['waybill_id'],
'courier_tracking_number' => $shipmentData['tracking_number'],
'courier_status' => 'awaiting_collection',
'status' => 'awaiting_collection',
]);
Log::info('Shipment created with courier', [
'order_uuid' => $order->uuid,
'waybill_id' => $shipmentData['waybill_id'],
'tracking_number' => $shipmentData['tracking_number'],
]);
// Fetch and store shipping documents
$stickerPath = $this->courierService->fetchSticker($shipmentData['shipment_id'], $order->id);
$waybillPath = $this->courierService->fetchWaybill($shipmentData['shipment_id'], $order->id);
// Emit event to trigger Trello update, Slack notification, document attachment
// Emit event to trigger Slack notification and Trello updates
ShipmentCreated::dispatch(
$order,
$shipmentData['waybill_id'],
$shipmentData['tracking_number'],
$stickerPath,
$waybillPath,
$result['waybill_id'],
$result['tracking_number'],
$result['sticker_path'],
$result['waybill_path'],
);
return response()->json([
'success' => true,
'message' => 'Shipment created successfully',
'shipment' => [
'waybill_id' => $shipmentData['waybill_id'],
'tracking_number' => $shipmentData['tracking_number'],
'sticker' => $stickerPath ? route('storage.file', $stickerPath) : null,
'waybill' => $waybillPath ? route('storage.file', $waybillPath) : null,
'waybill_id' => $result['waybill_id'],
'tracking_number' => $result['tracking_number'],
'sticker' => $result['sticker_path'] ? route('storage.file', $result['sticker_path']) : null,
'waybill' => $result['waybill_path'] ? route('storage.file', $result['waybill_path']) : null,
],
]);
} catch (\Exception $e) {
Log::error('Failed to create shipment', [
Log::error('Shipment creation failed', [
'order_uuid' => $order->uuid,
'error' => $e->getMessage(),
]);
@@ -147,7 +57,7 @@ class ShippingController extends Controller
return response()->json([
'error' => 'Failed to create shipment',
'message' => $e->getMessage(),
], 500);
], 400);
}
}
@@ -169,30 +79,4 @@ class ShippingController extends Controller
// Re-run the shipment creation
return $this->createShipment($request, $order);
}
/**
* Validate packing gate: order must be packed with dimensions
*/
private function validatePackingGate(Order $order): bool
{
return $order->packing_completed_at !== null &&
$order->packing_width > 0 &&
$order->packing_length > 0 &&
$order->packing_weight > 0;
}
/**
* Validate payment and approval gate
*/
private function validatePaymentAndApprovalGate(Order $order): bool
{
// Standard orders: must be fully paid
if ($order->is_custom_order === false) {
return $order->payment_status === 'paid';
}
// Custom orders: proof must be approved and balance must be paid
// TODO: Add proof_approved and balance_status fields to CustomOrder model
return true; // Placeholder - update when custom order model is ready
}
}
+5 -60
View File
@@ -28,71 +28,16 @@ class CreateShipmentOnReadyToShip
'order_uuid' => $order->uuid,
]);
// Validate packing
if (! $order->packing_completed_at || ! $order->packing_width || ! $order->packing_length || ! $order->packing_weight) {
Log::warning('Cannot create shipment - order not packed', [
'order_uuid' => $order->uuid,
'packing_completed_at' => $order->packing_completed_at,
]);
return;
}
// Validate payment
if ($order->is_custom_order === false && $order->payment_status !== 'paid') {
Log::warning('Cannot create shipment - order not paid', [
'order_uuid' => $order->uuid,
'payment_status' => $order->payment_status,
]);
return;
}
// Prevent duplicate shipments
if ($order->courier_waybill_id) {
Log::info('Shipment already exists for this order', [
'order_uuid' => $order->uuid,
'waybill_id' => $order->courier_waybill_id,
]);
return;
}
try {
Log::debug('Calling courier API to create shipment', [
'order_uuid' => $order->uuid,
]);
// Call courier API
$shipmentData = $this->courierService->createShipment(
$order->id,
$order->packing_width,
$order->packing_length,
$order->packing_weight,
);
// Save shipment details
$order->update([
'courier_waybill_id' => $shipmentData['waybill_id'],
'courier_tracking_number' => $shipmentData['tracking_number'],
'courier_status' => 'awaiting_collection',
'status' => 'awaiting_collection',
]);
Log::info('Shipment created successfully from webhook', [
'order_uuid' => $order->uuid,
'waybill_id' => $shipmentData['waybill_id'],
'tracking_number' => $shipmentData['tracking_number'],
]);
// Fetch shipping documents
$stickerPath = $this->courierService->fetchSticker($shipmentData['shipment_id'], $order->id);
$waybillPath = $this->courierService->fetchWaybill($shipmentData['shipment_id'], $order->id);
$result = $this->courierService->createShipmentForOrder($order);
// Emit event to trigger Slack/Trello updates
ShipmentCreated::dispatch(
$order,
$shipmentData['waybill_id'],
$shipmentData['tracking_number'],
$stickerPath,
$waybillPath,
$result['waybill_id'],
$result['tracking_number'],
$result['sticker_path'],
$result['waybill_path'],
);
} catch (\Exception $e) {
Log::error('Failed to create shipment from Ready to Ship intent', [
+128 -3
View File
@@ -2,6 +2,7 @@
namespace App\Services;
use App\Models\Order;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
@@ -18,7 +19,83 @@ class CourierService
}
/**
* Create a shipment with Shiplogic
* Create shipment with full validation and database updates
*
* @param Order $order
* @return array{waybill_id: string, tracking_number: string, sticker_path: ?string, waybill_path: ?string}
* @throws \Exception
*/
public function createShipmentForOrder(Order $order): array
{
Log::info('Creating shipment for order', ['order_uuid' => $order->uuid]);
// Guard 1: Validate packing
if (! $this->validatePacking($order)) {
throw new \Exception('Order not yet packed with valid dimensions');
}
// Guard 2: Validate payment/approval
if (! $this->validatePayment($order)) {
throw new \Exception($order->is_custom_order ?
'Custom order requires proof approved and balance paid' :
'Standard order must be fully paid'
);
}
// Guard 3: Validate order status
if ($order->status !== 'ready_to_ship') {
throw new \Exception('Order must be in Ready to Ship state');
}
// Guard 4: Prevent duplicates
if ($order->courier_waybill_id) {
throw new \Exception('Shipment already exists for this order');
}
try {
// Call API to create shipment
$shipmentData = $this->callCreateShipmentApi(
$order->id,
$order->packing_width,
$order->packing_length,
$order->packing_weight,
);
// Save shipment details to database
$order->update([
'courier_waybill_id' => $shipmentData['waybill_id'],
'courier_tracking_number' => $shipmentData['tracking_number'],
'courier_status' => 'awaiting_collection',
'status' => 'awaiting_collection',
]);
Log::info('Shipment created successfully', [
'order_uuid' => $order->uuid,
'waybill_id' => $shipmentData['waybill_id'],
]);
// Fetch shipping documents
$stickerPath = $this->fetchSticker($shipmentData['shipment_id'], $order->id);
$waybillPath = $this->fetchWaybill($shipmentData['shipment_id'], $order->id);
return [
'waybill_id' => $shipmentData['waybill_id'],
'tracking_number' => $shipmentData['tracking_number'],
'sticker_path' => $stickerPath,
'waybill_path' => $waybillPath,
];
} catch (\Exception $e) {
Log::error('Failed to create shipment', [
'order_uuid' => $order->uuid,
'error' => $e->getMessage(),
]);
throw $e;
}
}
/**
* Create a shipment with Shiplogic API
*
* @param string $orderId
* @param float $width Width in cm
@@ -27,7 +104,7 @@ class CourierService
* @return array{shipment_id: string, waybill_id: string, tracking_number: string}
* @throws \Exception
*/
public function createShipment(string $orderId, float $width, float $length, float $weight): array
private function callCreateShipmentApi(string $orderId, float $width, float $length, float $weight): array
{
if (! $this->isConfigured()) {
throw new \Exception('Courier API not configured');
@@ -69,7 +146,7 @@ class CourierService
'tracking_number' => $data['tracking_number'] ?? null,
];
} catch (\Exception $e) {
Log::error('Failed to create shipment with courier', [
Log::error('Failed to call courier API', [
'order_id' => $orderId,
'error' => $e->getMessage(),
]);
@@ -78,6 +155,54 @@ class CourierService
}
}
/**
* Validate packing gate: order must be packed with dimensions
*/
private function validatePacking(Order $order): bool
{
$valid = $order->packing_completed_at !== null &&
$order->packing_width > 0 &&
$order->packing_length > 0 &&
$order->packing_weight > 0;
if (! $valid) {
Log::warning('Packing validation failed', [
'order_uuid' => $order->uuid,
'packing_completed_at' => $order->packing_completed_at,
'width' => $order->packing_width,
'length' => $order->packing_length,
'weight' => $order->packing_weight,
]);
}
return $valid;
}
/**
* Validate payment and approval gate
*/
private function validatePayment(Order $order): bool
{
// Standard orders: must be fully paid
if ($order->is_custom_order === false) {
$valid = $order->payment_status === 'paid';
} else {
// Custom orders: proof must be approved and balance must be paid
// TODO: Add proof_approved and balance_status fields to CustomOrder model
$valid = true; // Placeholder
}
if (! $valid) {
Log::warning('Payment validation failed', [
'order_uuid' => $order->uuid,
'is_custom_order' => $order->is_custom_order,
'payment_status' => $order->payment_status,
]);
}
return $valid;
}
/**
* Fetch shipping label/sticker PDF from Shiplogic
*/