courierService->createShipmentForOrder($order); // Emit event to trigger Slack notification and Trello updates ShipmentCreated::dispatch( $order, $result['waybill_id'], $result['tracking_number'], $result['sticker_path'], $result['waybill_path'], ); return response()->json([ 'success' => true, 'message' => 'Shipment created successfully', 'shipment' => [ '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('Shipment creation failed', [ 'order_uuid' => $order->uuid, 'error' => $e->getMessage(), ]); // Emit failure event ShipmentCreationFailed::dispatch($order, $e->getMessage()); return response()->json([ 'error' => 'Failed to create shipment', 'message' => $e->getMessage(), ], 400); } } /** * Retry shipment creation after previous failure * * POST /admin/orders/{id}/retry-shipment */ public function retryShipment(Request $request, Order $order) { // Verify order exists and has not already been successfully shipped if ($order->courier_waybill_id) { return response()->json([ 'error' => 'Order already has a valid shipment', 'waybill_id' => $order->courier_waybill_id, ], 409); } // Re-run the shipment creation return $this->createShipment($request, $order); } }